generatesaas 3.1.1 → 3.2.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,30 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{Command as kl}from"commander";import*as os from"@clack/prompts";import{existsSync as Nc,readdirSync as Cc,rmSync as $c}from"fs";import{join as Lc,resolve as jc}from"path";import{Option as ne}from"commander";import*as b from"@clack/prompts";import*as Rt from"@clack/prompts";import er from"picocolors";function Ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(er.bgYellow(er.black(t)))}function Fr(){Rt.outro(er.yellow("Happy building!"))}import*as u from"@clack/prompts";import h from"picocolors";var at={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},Pt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},At={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Vr={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 Ie={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 G={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}},Te={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"}]}},_e={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"}]}},He=[{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."}],Ye=[{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)."}],cs=[{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 ie(e){return cs.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var se={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"}}},Oe=Object.keys(se);function tr(e){let t=[];for(let r of He)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 Ye)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Br=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function We(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 qe=["fullstack","separate"],ze=["stripe","polar","none"],Je=["smtp","ses","resend"];var Kr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],B=["sentry","posthog"];function Gr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _t(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Hr=["runner"];function rr(e){if(!Hr.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 ct(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place 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 Yr(e){return Hr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Wr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place 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 qr(e){let t=ls(e,e.desktopAi);return delete e.desktopAi,t}function ls(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 zr(e){let t={};if(e.name!==void 0){if(!_t(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.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),rr(t),ct(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(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ae.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ae.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ce.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ce.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.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=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Oe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Oe.join(", ")}`);let r=se[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 Xe={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Jr(e){let t=e.projectName??Xe.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(t),i=e.deploymentTarget??Xe.deploymentTarget,o=G[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":Xe.databaseProvider),a=e.cacheProvider??(o?"upstash":Xe.cacheProvider),p=e.emailProvider??(o?"resend":Xe.emailProvider),m={...Xe,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};m.paymentProvider==="none"&&(m.credits=!1);for(let g of He){if(m.deploymentTarget!==g.target)continue;let k=m.databaseProvider===g.provider?"database":"cache";if(m.databaseProvider===g.provider||m.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ye)if(m.architecture===g.architecture&&m.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ie(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return ct(m),m}function S(e){u.isCancel(e)&&(u.cancel("Setup cancelled."),process.exit(0))}function nr(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Xr(e,t){let r=!1;e&&rr(e),e&&ct(e),u.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!_t(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Tt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return S(c),c==="."?process.cwd():c})();u.log.info(h.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[...Oe.map(d=>({value:d,label:se[d].label,hint:se[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(S(c),c!=="custom"){let d=se[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,u.log.info(`${se[c].label}: ${se[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});S(c),a=c}let p=e?.architecture?Ye.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let m=ie({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ye.filter(c=>c.target===a).map(c=>c.architecture)),k=qe.filter(c=>!g.has(c)),A=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return u.log.info(`Auto-selected ${at[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:k.map(d=>({value:d,label:at[d].label,hint:at[d].hint}))});return S(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ce.filter(T=>!He.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return S(d),d})(),$=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=le.filter(T=>!He.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${_e[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:_e[T].label,hint:_e[T].hint}))});return S(d),d})();if(G[a]?.edgeRuntime){let c=Br.map(d=>` - ${d}`).join(`
3
- `);u.note(c,"Unavailable on edge runtime")}u.log.info(h.bold("Features"));let J=e?.paymentProvider??await(async()=>{r=!0;let c=await u.select({message:"Payment provider:",options:ze.map(d=>({value:d,label:Pt[d].label,hint:Pt[d].hint}))});return S(c),c})(),fe=e?.defaultCurrency??await(async()=>{if(J==="none")return"USD";r=!0;let c=await u.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Ie[d].name}))});return S(c),c})(),X=e?.emailProvider??await(async()=>{r=!0;let c=await u.select({message:"Email provider:",options:Je.map(d=>({value:d,label:At[d].label,hint:At[d].hint}))});return S(c),c})(),he=e?.observability??await(async()=>{r=!0;let c=await u.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:B.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return S(c),c})(),Ee=e?.multiTenancy??await(async()=>{r=!0;let c=await u.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),Se=e?.blog??await(async()=>{r=!0;let c=await u.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),Re=e?.docs??await(async()=>{r=!0;let c=await u.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),v=t?.desktopAllowed!==!1,x=e?.desktop??(v?await(async()=>{r=!0;let c=await u.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return S(c),c})():(u.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),L=e?.ai??await(async()=>{r=!0;let c=await u.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the runner)",initialValue:!1});return S(c),c})(),ge=t?.runnerAllowed!==!1,U=e?.webAi===!1,F=!L||w||U?!1:e?.runner??(ge?await(async()=>{r=!0;let c=await u.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 S(c),c})():(u.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));L&&w?u.log.info(h.dim(`Runner: ${G[a].label} cannot hold a connection open - skipped.`)):L&&U&&u.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let V=e?.webAi??(x&&L&&!F?await(async()=>{r=!0;let c=await u.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return S(c),c})():!0);ct({webAi:V,ai:L,desktop:x,runner:F});let Pe=e?.revenueSharing??await(async()=>{r=!0;let c=await u.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),Ge=J==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await u.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),R=e?.demo,Ae=nr({databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,demo:R}),ot={};if(Ae.length>0&&r){u.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Ae)if(r=!0,c.secret){let d=await u.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(ot[c.key]=d.trim())}else{let d=await u.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(ot[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(o)}`,` Architecture: ${h.cyan(at[A].label)}`].join(`
4
- `),d=[` Deploy target: ${h.cyan(G[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Te[f].label)}`,` Cache: ${h.cyan(_e[$].label)}`].filter(Boolean).join(`
5
- `),T=[J!=="none"?` Payment: ${h.cyan(Pt[J].label)} (${fe})`:` Payment: ${h.dim("none")}`,` Credits: ${Ge?h.cyan("Yes"):h.dim("No")}`,` AI features: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` Runner: ${F?h.cyan("Yes"):h.dim("No")}`]:[],...V?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(At[X].label)}`,` Observability: ${he.length===0?h.dim("none"):h.cyan(he.map(Qt=>It[Qt].label).join(", "))}`,` Multi-tenancy: ${Ee?h.cyan("Yes"):h.dim("No")}`,` Blog: ${Se?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${Re?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${x?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${Pe?h.cyan("Yes"):h.dim("No")}`].join(`
6
- `),ye=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),T];if(Ae.length>0){let Qt=Ae.map(Mr=>{let as=ot[Mr.key]?h.green("provided"):h.dim("skipped");return` ${Mr.key}: ${as}`}).join(`
7
- `);ye.push("",h.bold("Credentials"),Qt)}u.note(ye.join(`
8
- `),"Summary");let jr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(jr)||!jr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:A,deploymentTarget:a,databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,observability:he,multiTenancy:Ee,blog:Se,docs:Re,desktop:x,ai:L,webAi:V,runner:F,revenueSharing:Pe,credits:Ge,defaultCurrency:fe,...Object.keys(ot).length>0?{credentials:ot}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...R!==void 0?{demo:R}:{}}}import{createReadStream as ln,existsSync as bs}from"fs";import{mkdir as ws}from"fs/promises";import{join as ks}from"path";import{Readable as Es}from"stream";import{pipeline as ur}from"stream/promises";import{extract as Ss}from"tar";import{join as xe}from"path";import{homedir as ps}from"os";var lt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",H=".generatesaas",ve=xe(H,"manifest.json"),Zr="nextjs",ir="nuxt",sr="2.4.1",Qr=xe(H,"hashes.json"),Ot=xe(H,"template-hashes.json"),xt=xe(H,"template"),en=xe(H,"staging"),tn=xe(H,"staging.json"),pe=xe(ps(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function de(e){return{apiKey:e,baseUrl:lt}}async function be(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.1.1"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as ds,readFileSync as us,writeFileSync as ms,mkdirSync as fs}from"fs";import{dirname as hs}from"path";import*as we from"@clack/prompts";function pt(){if(!ds(pe))return null;try{let e=JSON.parse(us(pe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&we.log.warning(`Found old GitHub token in ${pe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function De(e){fs(hs(pe),{recursive:!0}),ms(pe,JSON.stringify({apiKey:e},null," ")+`
9
- `,{mode:384})}async function Ze(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=pt();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 dt()}async function dt(){let e=await we.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return we.isCancel(e)&&(we.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as gs}from"fs/promises";async function ke(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await gs(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 be(e,"/versions")).json()}async function rn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await be(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function nn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
- `,scripts:{}}:await(await be(e,`/skill/${encodeURIComponent(t)}`)).json()}function Dt(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var or="nextjs";function sn(e){return{frontend:or,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function ar(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await be(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function on(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await be(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function cr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function an(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var lr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),pr=new Set(["pnpm-lock.yaml"]);function Qe(e){if(dr(e))return!0;for(let t of e.split("/"))if(pr.has(t))return!0;return!1}var ys=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),cn=["scripts/docs-lint.ts"],vs=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.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 dr(e){let t=e.split("/");for(let r of t)if(lr.has(r))return!0;if(cn.includes(e)||cn.some(r=>r.startsWith(e+"/")))return!1;if(ys.has(t[0]))return!0;for(let r of vs)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Nt(e,t,r){await ws(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=ks(n,`v${t}.tar.gz`);if(!bs(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ur(ln(a),mr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await ur(ln(i),mr(r));return}let o=await be(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=Es.fromWeb(o.body);await ur(s,mr(r))}function mr(e){return Ss({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!dr(r):!0},sync:!1})}import{readdir as mn,readFile as ft,rm as fr,writeFile as ht}from"fs/promises";import{join as Q}from"path";import{readFile as mt,rm as Ds}from"fs/promises";import{join as ut}from"path";import{mkdir as Rs,readdir as Ps,rm as As,rmdir as Is,writeFile as Ts}from"fs/promises";import{dirname as Ct,join as _s,relative as Os,sep as xs}from"path";function Ne(e){return e.split(xs).join("/")}async function $t(e){await Rs(e,{recursive:!0})}async function l(e,t){await $t(Ct(e)),await Ts(e,t,"utf-8")}async function Lt(e,t){await As(e,{force:!0});let r=Ct(e);for(;r!==t&&r!==Ct(r);){try{await Is(r)}catch{return}r=Ct(r)}}async function ue(e,t,r,n){let i=[],o=await Ps(e,{withFileTypes:!0});for(let s of o){let a=_s(e,s.name),p=Ne(Os(t,a));r(p)||(s.isDirectory()?i.push(...await ue(a,t,r,n)):s.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}function Ns(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Z(e,t,r,n){let i=Ns(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,`
11
-
12
- `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function Y(e,t,r,n,i){let o=await mt(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.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Ce(e,t,r,n){let i=/\n([\t ]+)"/.exec(await mt(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
13
- `)}async function Cs(e,t,r){let n=ut(e,"ai.mdx"),o=(await mt(n,"utf-8")).split(`
14
- `).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 Y(n,`${o}
15
- `,"",`ai.mdx ${t} card`,r)}async function $s(e,t,r){let n=ut(e,"ai.mdx"),i=`| **${t}** |`,s=(await mt(n,"utf-8")).split(`
16
- `).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await Y(n,`${s}
17
- `,"",`ai.mdx ${t} hub-table row`,r)}async function pn(e,t,r,n,i){let o=ut(e,"docs/(platform)");await Ds(ut(o,t),{recursive:!0}),await Y(ut(o,"meta.json"),` "${t}",
18
- `,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await Cs(o,s,n);i!==void 0&&await $s(o,i,n)}function Ls(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]!==`
19
- `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
20
- `&&(t+=`
21
- `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
22
- `&&(t+=`
23
- `),r++;r++;continue}t+=n,r++}return t}async function dn(e){let t=`import { config } from "@repo/config";
24
- `,r=await mt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Ls(n);/\bconfig\b/.test(i)||await l(e,n)}var js=["apps/web/public/images/blog"];async function fn(e){let t=Q(e,"packages/content"),r=[];try{r=(await mn(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...js.map(n=>fr(Q(e,n),{recursive:!0,force:!0})),...r.map(n=>fr(Q(t,n,"blog"),{recursive:!0,force:!0}))])}var Ms=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function hn(e){let t="removeDesktopDemoScreen";await fr(Q(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Ms){let n=Q(e,r);await ht(n,Z(await ft(n,"utf-8"),r,"demo",t))}}var Us="packages/config/src/blog.ts";async function gn(e){let t=Q(e,Us),r=await ft(t,"utf-8"),n=un(un(r,"blogCategories",t),"blogAuthors",t);await ht(t,n)}function un(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 yn(e){let t=Q(e,"packages/i18n/translations"),r;try{r=await mn(t)}catch{return}for(let n of r){let i=Q(t,n,"web.json"),o;try{o=await ft(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await ht(i,JSON.stringify(s,null," ")+`
25
- `))}}var Fs="packages/config/src/ai/tasks.ts",Vs="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.",Bs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function vn(e){let t=Q(e,Fs),r=await ft(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(Vs,Bs);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 ht(t,i)}async function bn(e){let t=Q(e,".claude","settings.json"),r;try{r=await ft(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(Ks)),await ht(t,JSON.stringify(n,null," ")+`
26
- `)}function Ks(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as wn}from"path";var Gs={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Hs={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Ys={redis:"Redis",upstash:"Upstash Redis"},Ws={node:"Node.js / Docker",vercel:"Vercel"},jt="apps/web",kn="Next.js 16",qs="`app/` routes, `components/`, `lib/`",zs={stripe:"Stripe",polar:"Polar"};function Js(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${jt}\`. 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=Ys[e.cacheProvider],o=Ws[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
27
- - **Payments:** ${zs[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=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 \`${jt}/i18n/request.ts\`.`;return`# AGENTS.md
2
+ import{Command as wl}from"commander";import*as so from"@clack/prompts";import{existsSync as Dc,readdirSync as Nc,rmSync as Cc}from"fs";import{join as $c,resolve as Lc}from"path";import{Option as re}from"commander";import*as b from"@clack/prompts";import*as Rt from"@clack/prompts";import tr from"picocolors";function Ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(tr.bgYellow(tr.black(t)))}function Fr(){Rt.outro(tr.yellow("Happy building!"))}import*as u from"@clack/prompts";import m from"picocolors";var ct={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)"}},At={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Pt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Vr={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 Pe={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 H={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}},Ie={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"}]}},Te={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"}]}},Ye=[{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."}],We=[{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)."}],co=[{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 ne(e){return co.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var ie={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},_e=Object.keys(ie);function rr(e){let t=[];for(let r of Ye)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 We)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Br=["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 ze=["fullstack","separate"],Je=["stripe","polar","none"],Xe=["smtp","ses","resend"];var Kr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],se=["node","vercel"],ae=["postgres","neon","supabase"],ce=["redis","upstash"],B=["sentry","posthog"];function Gr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _t(e){return/^[a-z][a-z0-9-]*$/.test(e)}function x(e){return e instanceof Error?e.message:String(e)}var Hr=["runner"];function nr(e){if(!Hr.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 lt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place 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 Yr(e){return Hr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Wr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place 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 qr(e){let t=lo(e,e.desktopAi);return delete e.desktopAi,t}function lo(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 zr(e){let t={};if(e.name!==void 0){if(!_t(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.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),nr(t),lt(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(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!se.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${se.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ae.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ae.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ce.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ce.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=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!_e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${_e.join(", ")}`);let r=ie[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 Ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Jr(e){let t=e.projectName??Ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(t),i=e.deploymentTarget??Ze.deploymentTarget,s=H[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":Ze.databaseProvider),a=e.cacheProvider??(s?"upstash":Ze.cacheProvider),p=e.emailProvider??(s?"resend":Ze.emailProvider),f={...Ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};f.paymentProvider==="none"&&(f.credits=!1);for(let y of Ye){if(f.deploymentTarget!==y.target)continue;let w=f.databaseProvider===y.provider?"database":"cache";if(f.databaseProvider===y.provider||f.cacheProvider===y.provider)throw new Error(`Incompatible: --deploy ${y.target} + --${w} ${y.provider}. ${y.reason}`)}for(let y of We)if(f.architecture===y.architecture&&f.deploymentTarget===y.target)throw new Error(`Incompatible: --architecture ${y.architecture} + --deploy ${y.target}. ${y.reason}`);let k=ne(f);if(k)throw new Error(`Incompatible: --${k.feature} + --deploy ${k.target}. ${k.reason}`);return lt(f),f}function R(e){u.isCancel(e)&&(u.cancel("Setup cancelled."),process.exit(0))}function ir(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Xr(e,t){let r=!1;e&&nr(e),e&&lt(e),u.log.info(m.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!_t(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Tt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return R(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return R(c),c==="."?process.cwd():c})();u.log.info(m.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[..._e.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(c),c!=="custom"){let d=ie[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,u.log.info(`${ie[c].label}: ${ie[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:se.map(d=>({value:d,label:H[d].label,hint:H[d].hint}))});R(c),a=c}let p=e?.architecture?We.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let f=ne({...e,deploymentTarget:a});if(f)throw new Error(`Incompatible: --${f.feature} + --deploy ${f.target}. ${f.reason}`);let k=ne({runner:!0,deploymentTarget:a})!==void 0,y=new Set(We.filter(c=>c.target===a).map(c=>c.architecture)),w=ze.filter(c=>!y.has(c)),A=e?.architecture??await(async()=>{if(w.length===1){let d=w[0];return u.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${H[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:w.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return R(c),c})(),h=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=ae.filter(T=>!Ye.some(ge=>ge.target===a&&ge.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Ie[T].label} (only compatible option for ${H[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Ie[T].label,hint:Ie[T].hint}))});return R(d),d})(),C=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=ce.filter(T=>!Ye.some(ge=>ge.target===a&&ge.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${H[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return R(d),d})();if(H[a]?.edgeRuntime){let c=Br.map(d=>` - ${d}`).join(`
3
+ `);u.note(c,"Unavailable on edge runtime")}u.log.info(m.bold("Features"));let F=e?.paymentProvider??await(async()=>{r=!0;let c=await u.select({message:"Payment provider:",options:Je.map(d=>({value:d,label:At[d].label,hint:At[d].hint}))});return R(c),c})(),me=e?.defaultCurrency??await(async()=>{if(F==="none")return"USD";r=!0;let c=await u.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Pe[d].name}))});return R(c),c})(),X=e?.emailProvider??await(async()=>{r=!0;let c=await u.select({message:"Email provider:",options:Xe.map(d=>({value:d,label:Pt[d].label,hint:Pt[d].hint}))});return R(c),c})(),fe=e?.observability??await(async()=>{r=!0;let c=await u.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:B.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return R(c),c})(),Se=e?.multiTenancy??await(async()=>{r=!0;let c=await u.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(c),c})(),Re=e?.projects??await(async()=>{r=!0;let c=await u.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(c),c})(),Ae=e?.blog??await(async()=>{r=!0;let c=await u.confirm({message:"Enable blog?",initialValue:!0});return R(c),c})(),v=e?.docs??await(async()=>{r=!0;let c=await u.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(c),c})(),$=t?.desktopAllowed!==!1,G=e?.desktop??($?await(async()=>{r=!0;let c=await u.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return R(c),c})():(u.log.info(m.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),L=e?.ai??await(async()=>{r=!0;let c=await u.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(c),c})(),V=t?.runnerAllowed!==!1,Z=e?.webAi===!1,U=!L||k||Z?!1:e?.runner??(V?await(async()=>{r=!0;let c=await u.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(c),c})():(u.log.info(m.dim("Runner: available on the Pro plan and up - skipped.")),!1));L&&k?u.log.info(m.dim(`Runner: ${H[a].label} cannot hold a connection open - skipped.`)):L&&Z&&u.log.info(m.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let he=e?.webAi??(G&&L&&!U?await(async()=>{r=!0;let c=await u.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return R(c),c})():!0);lt({webAi:he,ai:L,desktop:G,runner:U});let Ge=e?.revenueSharing??await(async()=>{r=!0;let c=await u.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(c),c})(),P=F==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await u.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(c),c})(),He=e?.demo,St=ir({databaseProvider:h,cacheProvider:C,paymentProvider:F,emailProvider:X,demo:He}),at={};if(St.length>0&&r){u.log.info(m.bold("Credentials")+m.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of St)if(r=!0,c.secret){let d=await u.password({message:c.message,mask:"*"});R(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}else{let d=await u.text({message:c.message,placeholder:c.placeholder});R(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}}if(r){let c=[` Name: ${m.cyan(n)}`,` App name: ${m.cyan(i)}`,` Location: ${m.cyan(s)}`,` Architecture: ${m.cyan(ct[A].label)}`].join(`
4
+ `),d=[` Deploy target: ${m.cyan(H[a]?.label??"Node.js / Docker")}`,` Database: ${m.cyan(Ie[h].label)}`,` Cache: ${m.cyan(Te[C].label)}`].filter(Boolean).join(`
5
+ `),T=[F!=="none"?` Payment: ${m.cyan(At[F].label)} (${me})`:` Payment: ${m.dim("none")}`,` Credits: ${P?m.cyan("Yes"):m.dim("No")}`,` AI features: ${L?m.cyan("Yes"):m.dim("No")}`,...L?[` Runner: ${U?m.cyan("Yes"):m.dim("No")}`]:[],...he?[]:[` Web AI: ${m.dim("No")} (desktop-first)`],` Email: ${m.cyan(Pt[X].label)}`,` Observability: ${fe.length===0?m.dim("none"):m.cyan(fe.map(er=>It[er].label).join(", "))}`,` Multi-tenancy: ${Se?m.cyan("Yes"):m.dim("No")}`,` Projects: ${Re?m.cyan("Yes"):m.dim("No")}`,` Blog: ${Ae?m.cyan("Yes"):m.dim("No")}`,` Docs app: ${v?m.cyan("Yes"):m.dim("No")}`,` Desktop app: ${G?m.cyan("Yes"):m.dim("No")}`,` Rev. sharing: ${Ge?m.cyan("Yes"):m.dim("No")}`].join(`
6
+ `),ge=[m.bold("Project"),c,"",m.bold("Infrastructure"),d,"",m.bold("Features"),T];if(St.length>0){let er=St.map(Mr=>{let ao=at[Mr.key]?m.green("provided"):m.dim("skipped");return` ${Mr.key}: ${ao}`}).join(`
7
+ `);ge.push("",m.bold("Credentials"),er)}u.note(ge.join(`
8
+ `),"Summary");let jr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(jr)||!jr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:A,deploymentTarget:a,databaseProvider:h,cacheProvider:C,paymentProvider:F,emailProvider:X,observability:fe,multiTenancy:Se,projects:Re,blog:Ae,docs:v,desktop:G,ai:L,webAi:he,runner:U,revenueSharing:Ge,credits:P,defaultCurrency:me,...Object.keys(at).length>0?{credentials:at}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...He!==void 0?{demo:He}:{}}}import{createReadStream as ln,existsSync as wo}from"fs";import{mkdir as ko}from"fs/promises";import{join as Eo}from"path";import{Readable as So}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ro}from"tar";import{join as Oe}from"path";import{homedir as po}from"os";var pt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Y=".generatesaas",ye=Oe(Y,"manifest.json"),Zr="nextjs",or="nuxt",sr="2.4.1",Qr=Oe(Y,"hashes.json"),Ot=Oe(Y,"template-hashes.json"),xt=Oe(Y,"template"),en=Oe(Y,"staging"),tn=Oe(Y,"staging.json"),le=Oe(po(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function pe(e){return{apiKey:e,baseUrl:pt}}async function ve(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.2.0"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new j(i.status,s,o)}return i}import{existsSync as uo,readFileSync as mo,writeFileSync as fo,mkdirSync as ho}from"fs";import{dirname as go}from"path";import*as be from"@clack/prompts";function dt(){if(!uo(le))return null;try{let e=JSON.parse(mo(le,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&be.log.warning(`Found old GitHub token in ${le}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function xe(e){ho(go(le),{recursive:!0}),fo(le,JSON.stringify({apiKey:e},null," ")+`
9
+ `,{mode:384})}async function Qe(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=dt();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 ut()}async function ut(){let e=await be.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return be.isCancel(e)&&(be.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as yo}from"fs/promises";async function we(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await yo(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 ve(e,"/versions")).json()}async function rn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await ve(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function nn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
+ `,scripts:{}}:await(await ve(e,`/skill/${encodeURIComponent(t)}`)).json()}function Dt(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var ar="nextjs";function on(e){return{frontend:ar,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await ve(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function sn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await ve(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function lr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function an(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out"]),dr=new Set(["pnpm-lock.yaml"]);function et(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var vo=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),cn=["scripts/docs-lint.ts"],bo=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.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 ur(e){let t=e.split("/");for(let r of t)if(pr.has(r))return!0;if(cn.includes(e)||cn.some(r=>r.startsWith(e+"/")))return!1;if(vo.has(t[0]))return!0;for(let r of bo)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Nt(e,t,r){await ko(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Eo(n,`v${t}.tar.gz`);if(!wo(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(ln(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(ln(i),fr(r));return}let s=await ve(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=So.fromWeb(s.body);await mr(o,fr(r))}function fr(e){return Ro({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as un,readFile as Ct,rm as pn,writeFile as $t}from"fs/promises";import{join as ke}from"path";var Ao=["apps/web/public/images/blog"];async function mn(e){let t=ke(e,"packages/content"),r=[];try{r=(await un(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...Ao.map(n=>pn(ke(e,n),{recursive:!0,force:!0})),...r.map(n=>pn(ke(t,n,"blog"),{recursive:!0,force:!0}))])}var Po="packages/config/src/blog.ts";async function fn(e){let t=ke(e,Po),r=await Ct(t,"utf-8"),n=dn(dn(r,"blogCategories",t),"blogAuthors",t);await $t(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 hn(e){let t=ke(e,"packages/i18n/translations"),r;try{r=await un(t)}catch{return}for(let n of r){let i=ke(t,n,"web.json"),s;try{s=await Ct(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.blog||o.blog.categories===void 0||(o.blog.categories={},await $t(i,JSON.stringify(o,null," ")+`
11
+ `))}}var Io="packages/config/src/ai/tasks.ts",To="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.",_o="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function gn(e){let t=ke(e,Io),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(To,_o);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 $t(t,i)}async function yn(e){let t=ke(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(Oo)),await $t(t,JSON.stringify(n,null," ")+`
12
+ `)}function Oo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as vn}from"path";import{mkdir as xo,readdir as Do,rm as No,rmdir as Co,writeFile as $o}from"fs/promises";import{dirname as Lt,join as Lo,relative as jo,sep as Mo}from"path";function De(e){return e.split(Mo).join("/")}async function jt(e){await xo(e,{recursive:!0})}async function l(e,t){await jt(Lt(e)),await $o(e,t,"utf-8")}async function Mt(e,t){await No(e,{force:!0});let r=Lt(e);for(;r!==t&&r!==Lt(r);){try{await Co(r)}catch{return}r=Lt(r)}}async function de(e,t,r,n){let i=[],s=await Do(e,{withFileTypes:!0});for(let o of s){let a=Lo(e,o.name),p=De(jo(t,a));r(p)||(o.isDirectory()?i.push(...await de(a,t,r,n)):o.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var Uo={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Fo={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Vo={redis:"Redis",upstash:"Upstash Redis"},Bo={node:"Node.js / Docker",vercel:"Vercel"},Ut="apps/web",bn="Next.js 16",Ko="`app/` routes, `components/`, `lib/`",Go={stripe:"Stripe",polar:"Polar"};function Ho(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Ut}\`. 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=Vo[e.cacheProvider],s=Bo[e.deploymentTarget],o=e.paymentProvider==="none"?"":`
13
+ - **Payments:** ${Go[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=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.":"",f=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Ut}/i18n/request.ts\`.`;return`# AGENTS.md
28
14
 
29
15
  Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
30
16
  Keep this file tight: add a rule only when it prevents a recurring mistake - too
@@ -38,7 +24,7 @@ and go find it:
38
24
 
39
25
  1. \`docs/(platform)/index.mdx\` - the catalog of every shipped feature and its config flag.
40
26
  2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
41
- 3. Search \`packages/\` and \`${jt}/\` for the name before creating anything.
27
+ 3. Search \`packages/\` and \`${Ut}/\` for the name before creating anything.
42
28
 
43
29
  Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
44
30
  billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
@@ -50,13 +36,13 @@ flag, route, or translation is the most common and most costly mistake in this r
50
36
 
51
37
  ## Stack
52
38
 
53
- - **Frontend:** ${kn} ${r}
39
+ - **Frontend:** ${bn} ${r}
54
40
  - **API:** Hono, RPC-typed. ${n}
55
- - **Database:** Drizzle ORM + ${Gs[e.databaseProvider]}
41
+ - **Database:** Drizzle ORM + ${Uo[e.databaseProvider]}
56
42
  - **Cache + jobs:** ${i} + Inngest
57
- - **Auth:** Better Auth${s}
58
- - **Email:** ${Hs[e.emailProvider]}
59
- - **Deploy:** ${o}
43
+ - **Auth:** Better Auth${o}
44
+ - **Email:** ${Fo[e.emailProvider]}
45
+ - **Deploy:** ${s}
60
46
 
61
47
  ## Where things live (extend these - don't reinvent)
62
48
 
@@ -66,7 +52,7 @@ flag, route, or translation is the most common and most costly mistake in this r
66
52
  - \`packages/auth/src/config.ts\` - Better Auth config.
67
53
  - \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
68
54
  - \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
69
- - \`${jt}\` - the ${kn} app (${qs}).${p}
55
+ - \`${Ut}\` - the ${bn} app (${Ko}).${p}
70
56
  - \`docs/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${a}.
71
57
 
72
58
  ## Code style
@@ -84,7 +70,7 @@ flag, route, or translation is the most common and most costly mistake in this r
84
70
 
85
71
  - **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
86
72
  - **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
87
- - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${m} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
73
+ - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${f} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
88
74
  - **Navigation:** \`next/link\` for links; \`redirect()\` from \`next/navigation\` for programmatic redirects in Server Components.
89
75
  - **Routes:** use \`config.routes.*\`, never hardcoded path strings.
90
76
  - **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
@@ -96,12 +82,12 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
96
82
  ## This project
97
83
 
98
84
  Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
99
- `}async function En(e){await l(wn(e.projectDir,"AGENTS.md"),Js(e)),await l(wn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
100
- `)}import{join as Xs}from"path";var Sn="apps/web",hr="Next.js 16",Zs={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Qs(e){let t=e.appName.trim()||e.projectName,r=Zs[e.databaseProvider],n=e.architecture==="fullstack"?`${hr} app at \`${Sn}/\` 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.`:`${hr} app at \`${Sn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
85
+ `}async function wn(e){await l(vn(e.projectDir,"AGENTS.md"),Ho(e)),await l(vn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
86
+ `)}import{join as Yo}from"path";var kn="apps/web",hr="Next.js 16",Wo={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function qo(e){let t=e.appName.trim()||e.projectName,r=Wo[e.databaseProvider],n=e.architecture==="fullstack"?`${hr} app at \`${kn}/\` 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.`:`${hr} app at \`${kn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
101
87
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
102
88
  - API: http://localhost:3010
103
- - Inngest dev server: http://127.0.0.1:8288`,o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
104
- `,s=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
89
+ - Inngest dev server: http://127.0.0.1:8288`,s=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
90
+ `,o=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
105
91
 
106
92
  ${n}
107
93
 
@@ -121,7 +107,7 @@ pnpm install
121
107
  # A ready-to-run \`.env\` was generated for you - open it and fill in the
122
108
  # values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
123
109
  # reference. All apps load the single root \`.env\`.
124
- ${o}pnpm db:setup # first run: create the database schema (idempotent)
110
+ ${s}pnpm db:setup # first run: create the database schema (idempotent)
125
111
  pnpm dev
126
112
  \`\`\`
127
113
 
@@ -145,7 +131,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
145
131
  pnpm auth:generate # regenerate Better Auth schema after config changes
146
132
  \`\`\`
147
133
 
148
- ${s}
134
+ ${o}
149
135
 
150
136
  ## Removing the GenerateSaaS license
151
137
 
@@ -158,27 +144,28 @@ pnpm dlx generatesaas eject
158
144
  ## Updates
159
145
 
160
146
  To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
161
- `}async function Rn(e){await l(Xs(e.projectDir,"README.md"),Qs(e))}import{access as eo}from"fs/promises";import{join as Mt}from"path";async function to(e,t,r){let n=Mt(e,"apps/electron/dev-app-update.yml");try{await eo(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
147
+ `}async function En(e){await l(Yo(e.projectDir,"README.md"),qo(e))}import{access as zo}from"fs/promises";import{join as Ft}from"path";async function Jo(e,t,r){let n=Ft(e,"apps/electron/dev-app-update.yml");try{await zo(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
162
148
  url: ${t}
163
149
  updaterCacheDirName: ${r}
164
- `)}function ro(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function no(e,t){let r=Gr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var et={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 io(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(et.name)},`,` binary: ${JSON.stringify(et.binary)},`,` envPrefix: ${JSON.stringify(et.envPrefix)},`,` repoUrl: ${JSON.stringify(et.repoUrl)},`,` installBase: ${JSON.stringify(et.installBase)},`,` image: ${JSON.stringify(et.image)}`," }"," }"].join(`
165
- `):'{ enabled: false, clientId: "runner" }'}function so(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(`
150
+ `)}function Xo(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Zo(e,t){let r=Gr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var tt={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(tt.name)},`,` binary: ${JSON.stringify(tt.binary)},`,` envPrefix: ${JSON.stringify(tt.envPrefix)},`,` repoUrl: ${JSON.stringify(tt.repoUrl)},`,` installBase: ${JSON.stringify(tt.installBase)},`,` image: ${JSON.stringify(tt.image)}`," }"," }"].join(`
151
+ `):'{ enabled: false, clientId: "runner" }'}function es(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(`
166
152
  `),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(`
167
153
  `)),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(`
168
154
  `):`${t}
169
155
  observability: {
170
156
  ${r.join(`,
171
157
  `)}
172
- },`}async function Pn(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=ro(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
158
+ },`}async function Sn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",s=Xo(i),o=e.demo?"false":"true",a=e.multiTenancy?`{
173
159
  multiTenant: true,
174
- organizationLimit: 5
175
- }`:"{ multiTenant: false }",p=so(e.observability),m=e.demo?`{
160
+ organizationLimit: 5,
161
+ defaultOrganizationName: "Personal"
162
+ }`:"{ multiTenant: false }",p=e.projects?"{ enabled: true }":"{ enabled: false }",f=es(e.observability),k=e.demo?`{
176
163
  enableInDev: true,
177
164
  chatwoot: {
178
165
  baseUrl: "https://support.alexchelan.com",
179
166
  websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
180
167
  }
181
- }`:"{}",w=e.architecture==="fullstack"?"false":"true",g=no(t,o),k=`https://cdn.${o}/desktop`,A=io(e),f=`import type { AppConfig } from "@repo/config/types";
168
+ }`:"{}",y=e.architecture==="fullstack"?"false":"true",w=Zo(t,s),A=`https://cdn.${s}/desktop`,h=Qo(e),C=`import type { AppConfig } from "@repo/config/types";
182
169
  import { desktopConfig } from "./desktop.mjs";
183
170
  import { supportConfig } from "./support";
184
171
 
@@ -199,7 +186,7 @@ export const config: AppConfig = {
199
186
  fullSiteName: "${t}",
200
187
  domain: "${i}",
201
188
  baseUrl: "${n}",
202
- indexable: ${s},
189
+ indexable: ${o},
203
190
  logo: {
204
191
  main: "/images/logo.svg",
205
192
  square: "/images/logo-square.svg"
@@ -207,6 +194,7 @@ export const config: AppConfig = {
207
194
  origins: ["http://localhost:3000", "http://localhost:5173"],
208
195
  waitlist: false,
209
196
  tenancy: ${a},
197
+ projects: ${p},
210
198
  theme: {
211
199
  default: "system",
212
200
  switcher: true,
@@ -224,16 +212,16 @@ export const config: AppConfig = {
224
212
  limitPerSecond: 3,
225
213
  senders: {
226
214
  transactional: {
227
- email: "noreply@${o}",
215
+ email: "noreply@${s}",
228
216
  senderName: "${t}"
229
217
  },
230
218
  marketing: {
231
- email: "hello@${o}",
219
+ email: "hello@${s}",
232
220
  senderName: "${t}",
233
221
  signatureName: "Alex"
234
222
  },
235
223
  support: {
236
- email: "support@${o}",
224
+ email: "support@${s}",
237
225
  senderName: "${t} Support"
238
226
  }
239
227
  },
@@ -261,8 +249,8 @@ export const config: AppConfig = {
261
249
  prefix: "key_"
262
250
  },
263
251
  apiDocs: true,
264
- performanceMonitor: { enabled: ${w} },
265
- ${p}
252
+ performanceMonitor: { enabled: ${y} },
253
+ ${f}
266
254
  notifications: {
267
255
  enabled: true,
268
256
  maxPerUser: 100,
@@ -306,7 +294,7 @@ ${p}
306
294
  }`:`{
307
295
  base: "${e.defaultCurrency}",
308
296
  list: [
309
- { symbol: "${Ie[e.defaultCurrency].symbol}", name: "${Ie[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ie[e.defaultCurrency].place}", space: ${Ie[e.defaultCurrency].space} }
297
+ { symbol: "${Pe[e.defaultCurrency].symbol}", name: "${Pe[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Pe[e.defaultCurrency].place}", space: ${Pe[e.defaultCurrency].space} }
310
298
  ],
311
299
  countryMap: {
312
300
  default: "${e.defaultCurrency}"
@@ -349,9 +337,9 @@ ${p}
349
337
  // What every user starts on (their own choice, once made, always wins). Plain
350
338
  // OpenRouter model ids.
351
339
  defaults: { model: "anthropic/claude-opus-4.8" },
352
- // Let end-users author their own AI schedules. Set to false to ship only the
353
- // create-disabled view (existing schedules still list/run/edit/delete).
354
- userSchedules: true,
340
+ // Let end-users author their own AI automations. Set to false to ship only the
341
+ // create-disabled view (existing automations still list/run/edit/delete).
342
+ userAutomations: true,
355
343
  // Server-side chat thread limits: at most \`cap\` stored threads per user (chat history lives in
356
344
  // Mastra Memory threads; the server evicts the oldest-by-activity beyond the cap).
357
345
  chats: {
@@ -365,7 +353,7 @@ ${p}
365
353
  },
366
354
  desktop: desktopConfig,
367
355
  // Runner: the AgentRunner daemon your users install to run their own subscription CLIs for this app. Off by default.
368
- runner: ${A},
356
+ runner: ${h},
369
357
  // Outward MCP server exposing the capability layer to external agents. Its code ships with every
370
358
  // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
371
359
  mcpServer: { enabled: ${e.demo?"true":"false"} },
@@ -389,7 +377,7 @@ ${p}
389
377
  onboarding: "/onboarding",
390
378
  settings: "/settings/profile",
391
379
  chat: "/chat",
392
- schedules: "/schedules",
380
+ automations: "/automations",
393
381
  settingsModels: "/settings/models",
394
382
  settingsIntegrations: "/settings/integrations",
395
383
  settingsRunners: "/settings/runners",
@@ -413,10 +401,11 @@ export * from "./i18n";
413
401
  export * from "./landing";
414
402
  export * from "./nav-active";
415
403
  export * from "./pricing";
404
+ export * from "./projects";
416
405
  export * from "./roles";
417
406
  export * from "./section-tabs";
418
407
  export * from "./tenancy";
419
- `,$=Mt(e.projectDir,"packages/config/src/index.ts");await l($,f),await l(Mt(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
408
+ `,F=Ft(e.projectDir,"packages/config/src/index.ts");await l(F,C),await l(Ft(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
420
409
 
421
410
  /**
422
411
  * Live-chat (support widget) configuration, re-exported by the config index as
@@ -428,8 +417,8 @@ export * from "./tenancy";
428
417
  * Node, which cannot resolve the index's extensionless relative imports. Keep any relative
429
418
  * import here type-only.
430
419
  */
431
- export const supportConfig: SupportConfig = ${m};
432
- `),await l(Mt(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
420
+ export const supportConfig: SupportConfig = ${k};
421
+ `),await l(Ft(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
433
422
  // TypeScript config index reads it directly: the Electron main + renderer bundles,
434
423
  // the CSP policy builder, and the electron-builder packaging config. Edit these
435
424
  // values once to rebrand - they are the same in dev and production, so they live in
@@ -437,14 +426,14 @@ export const supportConfig: SupportConfig = ${m};
437
426
 
438
427
  export const desktopConfig = {
439
428
  enabled: ${e.desktop},
440
- appId: "${g.appId}",
441
- productName: "${g.productName}",
442
- protocol: "${g.protocol}",
429
+ appId: "${w.appId}",
430
+ productName: "${w.productName}",
431
+ protocol: "${w.protocol}",
443
432
  baseUrl: "${n}",
444
433
  // Public base URL the release workflow uploads to; electron-updater polls
445
434
  // \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
446
435
  // the per-installer blockmaps, and the stable installer download links live under it.
447
- autoUpdate: { url: "${k}" },
436
+ autoUpdate: { url: "${A}" },
448
437
  // Whether the support live-chat widget you configured in config.support (Crisp,
449
438
  // Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
450
439
  // every surface. Set false to keep live chat on your website only - the app then
@@ -455,7 +444,7 @@ export const desktopConfig = {
455
444
  // user's machine: credentials are encrypted with the OS keychain and never reach your
456
445
  // backend.
457
446
  // { id, name, description?, kind: "mcp" | "api", credentials: [{ key, label, secret? }], mcp? }
458
- // An \`mcp\` entry becomes a local MCP server for chats, schedules and terminal sessions
447
+ // An \`mcp\` entry becomes a local MCP server for chats, automations and terminal sessions
459
448
  // once every credential is set; give it \`mcp: { command, args?, env? }\` and reference a
460
449
  // credential in an env VALUE as the whole string "{credential:KEY}". An \`api\` entry only
461
450
  // stores the credentials - read them from your own main-process code with
@@ -474,21 +463,21 @@ export const desktopConfig = {
474
463
  // "Sign in" is offered only for a provider whose clientId is set here; the
475
464
  // boilerplate ships none, so it starts empty.
476
465
  oauth: {},
477
- // Let end users author their own background schedules on the Schedules screen.
478
- // Set to false to ship only builder-registered schedules.
479
- userSchedules: true,
466
+ // Let end users author their own background automations on the Automations screen.
467
+ // Set to false to ship only builder-registered automations.
468
+ userAutomations: true,
480
469
  // Cap how many chat conversations are kept per agent on the user's machine;
481
470
  // creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
482
471
  maxChatsPerAgent: 20,
483
472
  // Whether agent work continues after the window closes. OFF by default: the runtime is a
484
473
  // child process of the app and is killed at quit. Turn it on if your product's value
485
- // depends on schedules firing while the app is closed; end users then get a
474
+ // depends on automations firing while the app is closed; end users then get a
486
475
  // "Keep running after I close the window" toggle.
487
476
  background: false
488
477
  }
489
478
  };
490
- `),e.desktop&&await to(e.projectDir,k,`${g.protocol}-updater`)}import{join as oo}from"path";function ao(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function gr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
491
- `)}async function An(e){let t=oo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let A=`import type { PricingConfig } from "@repo/config/types";
479
+ `),e.desktop&&await Jo(e.projectDir,A,`${w.protocol}-updater`)}import{join as ts}from"path";function rs(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function gr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxAutomations!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxAutomations: ${e.maxAutomations}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
480
+ `)}async function Rn(e){let t=ts(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let A=`import type { PricingConfig } from "@repo/config/types";
492
481
 
493
482
  export const pricingConfig: PricingConfig = {
494
483
  defaultPlan: "free",
@@ -517,21 +506,21 @@ export const pricingConfig: PricingConfig = {
517
506
  credits: { enabled: false },
518
507
  products: { enabled: false, items: [] }
519
508
  };
520
- `;await l(t,A);return}let n=e.paymentProvider,i=ao(n),o=e.credits,s=!!e.ai,a=gr({credits:5,rateLimit:100,withCredits:o,...s&&{maxSchedules:3}}),p=gr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxSchedules:10}}),m=gr({credits:50,rateLimit:5e3,withCredits:o}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
509
+ `;await l(t,A);return}let n=e.paymentProvider,i=rs(n),s=e.credits,o=!!e.ai,a=gr({credits:5,rateLimit:100,withCredits:s,...o&&{maxAutomations:3}}),p=gr({credits:10,rateLimit:1e3,withCredits:s,...o&&{maxAutomations:10}}),f=gr({credits:50,rateLimit:5e3,withCredits:s}),k=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
521
510
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
522
511
  // !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
523
512
  // !! 20% markup) - and raise prices or creditsPerUsd if they do not.
524
- `;o&&r!=="USD"&&console.warn(`
513
+ `;s&&r!=="USD"&&console.warn(`
525
514
  !! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
526
515
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
527
516
  !! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
528
517
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
529
- `);let g=o?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
518
+ `);let y=s?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
530
519
  // 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
531
520
  // external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
532
521
  // the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
533
522
  // full utilization runs you at a loss.
534
- ${w} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",k=`import type { PricingConfig } from "@repo/config/types";
523
+ ${k} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",w=`import type { PricingConfig } from "@repo/config/types";
535
524
 
536
525
  export const pricingConfig: PricingConfig = {
537
526
  defaultPlan: "free",
@@ -612,20 +601,20 @@ ${i}
612
601
  anchorAmounts: { ${r}: 349 }
613
602
  }
614
603
  ],
615
- ${m}
604
+ ${f}
616
605
  }
617
606
  ],
618
- ${g},
607
+ ${y},
619
608
  products: {
620
609
  enabled: false,
621
610
  items: []
622
611
  }
623
612
  };
624
- `;await l(t,k)}var co={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"}]},lo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Ut(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function gt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function yr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function _n(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var po="https://your-app.example.com/api";function Ft(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function In(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=_n(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"),gt(Ut(Te[e.databaseProvider].envVars,r),o),o.push("","# Cache"),gt(Ut(_e[e.cacheProvider].envVars,r),o),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Ft(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Ft(o,"CONTENT_API_KEY",yr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Ft(o,"INNGEST_EVENT_KEY",yr(32),t),Ft(o,"INNGEST_SIGNING_KEY",yr(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=co[e.emailProvider];if(s&&(o.push("","# Email"),gt(Ut(s,r),o)),e.paymentProvider!=="none"){let p=lo[e.paymentProvider];p&&(o.push("","# Payment"),gt(Ut(p,r),o))}o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),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)"),gt(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 provider API 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."),o.push(""),o.join(`
625
- `)}var Tn="NEXT_PUBLIC_API_URL";function uo(e){let{apiUrl:t}=_n(e),r=["# API Configuration",`${Tn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Tn}=${po}`),r.push(""),r.join(`
626
- `)}async function On(e){let t=uo(e);await l(`${e.projectDir}/.env`,t+`
627
- `+In(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
628
- `+In(e,"example"))}import{join as mo}from"path";async function xn(e){let t=We(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
613
+ `;await l(t,w)}var ns={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"}]},is={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function mt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function yr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function In(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var os="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function An(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=In(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),mt(Vt(Ie[e.databaseProvider].envVars,r),s),s.push("","# Cache"),mt(Vt(Te[e.cacheProvider].envVars,r),s),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(s,"CONTENT_API_KEY",yr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(s,"INNGEST_EVENT_KEY",yr(32),t),Bt(s,"INNGEST_SIGNING_KEY",yr(32),t),s.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=ns[e.emailProvider];if(o&&(s.push("","# Email"),mt(Vt(o,r),s)),e.paymentProvider!=="none"){let p=is[e.paymentProvider];p&&(s.push("","# Payment"),mt(Vt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(s.push("","# Error and product reporting (optional)"),mt(a,s)),s.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only provider API 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."),s.push(""),s.join(`
614
+ `)}var Pn="NEXT_PUBLIC_API_URL";function ss(e){let{apiUrl:t}=In(e),r=["# API Configuration",`${Pn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${Pn}=${os}`),r.push(""),r.join(`
615
+ `)}async function Tn(e){let t=ss(e);await l(`${e.projectDir}/.env`,t+`
616
+ `+An(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
617
+ `+An(e,"example"))}import{join as as}from"path";async function _n(e){let t=qe(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
629
618
  image: postgres:18-alpine
630
619
  restart: unless-stopped
631
620
  ports:
@@ -660,7 +649,7 @@ ${g},
660
649
  - "\${MAILPIT_UI_PORT:-8025}:8025"
661
650
  environment:
662
651
  MP_SMTP_AUTH_ACCEPT_ANY: 1
663
- MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let s=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
652
+ MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let o=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
664
653
  image: inngest/inngest:v1.17.4
665
654
  restart: unless-stopped
666
655
  ports:
@@ -675,25 +664,25 @@ ${g},
675
664
  # Linux, which is what \`extra_hosts\` supplies.
676
665
  command: >-
677
666
  inngest dev
678
- -u ${s}
667
+ -u ${o}
679
668
  extra_hosts:
680
- - "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
669
+ - "host.docker.internal:host-gateway"`)}let s=`name: ${`${e.projectName}-infra`}
681
670
 
682
671
  services:
683
672
  ${r.join(`
684
673
 
685
674
  `)}
686
- `;n.length>0&&(o+=`
675
+ `;n.length>0&&(s+=`
687
676
  volumes:
688
677
  ${n.join(`
689
678
  `)}
690
- `),await l(mo(e.projectDir,"infra/docker-compose.yml"),o)}import{join as fo}from"path";var yt="Next.js";function ho(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:yt,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/electron",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 go(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${yt} + Backend + Inngest)`,configurations:["Backend",yt,"Inngest"]}):t.push({name:`Dev (${yt} + Inngest)`,configurations:[yt,"Inngest"]}),t}async function Dn(e){let t={version:"0.2.0",configurations:ho(e),compounds:go(e)};await l(fo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
691
- `)}import{readFile as yo}from"fs/promises";import{join as vo}from"path";var vr='import { drizzle } from "drizzle-orm/node-postgres";',br=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
692
- export const pool = db.$client;`,bo={postgres:{importLine:vr,instantiation:br},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
679
+ `),await l(as(e.projectDir,"infra/docker-compose.yml"),s)}import{join as cs}from"path";var ft="Next.js";function ls(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:ft,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/electron",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 ps(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${ft} + Backend + Inngest)`,configurations:["Backend",ft,"Inngest"]}):t.push({name:`Dev (${ft} + Inngest)`,configurations:[ft,"Inngest"]}),t}async function On(e){let t={version:"0.2.0",configurations:ls(e),compounds:ps(e)};await l(cs(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
680
+ `)}import{readFile as ds}from"fs/promises";import{join as us}from"path";var vr='import { drizzle } from "drizzle-orm/node-postgres";',br=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
681
+ export const pool = db.$client;`,ms={postgres:{importLine:vr,instantiation:br},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
693
682
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
694
683
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
695
684
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
696
- export const db = drizzle(client, { schema });`}};async function Nn(e){let t=vo(e.projectDir,"packages/database/src/index.ts"),r=await yo(t,"utf-8");if(!r.includes(vr)||!r.includes(br))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=bo[e.databaseProvider],i=r.replace(vr,n.importLine).replace(br,n.instantiation);await l(t,i)}import{join as Vt}from"path";async function Cn(e){switch(e.cacheProvider){case"redis":await wo(e),await ko(e);break;case"upstash":await Eo(e),await So(e);break}}async function wo(e){await l(Vt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
685
+ export const db = drizzle(client, { schema });`}};async function xn(e){let t=us(e.projectDir,"packages/database/src/index.ts"),r=await ds(t,"utf-8");if(!r.includes(vr)||!r.includes(br))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=ms[e.databaseProvider],i=r.replace(vr,n.importLine).replace(br,n.instantiation);await l(t,i)}import{join as Kt}from"path";async function Dn(e){switch(e.cacheProvider){case"redis":await fs(e),await hs(e);break;case"upstash":await gs(e),await ys(e);break}}async function fs(e){await l(Kt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
697
686
  import { Redis } from "ioredis";
698
687
  import { RedisStore } from "rate-limit-redis";
699
688
  import type { RedisReply } from "rate-limit-redis";
@@ -840,7 +829,7 @@ export async function closeRedis() {
840
829
  closed = true;
841
830
  }
842
831
  }
843
- `)}async function ko(e){await l(Vt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
832
+ `)}async function hs(e){await l(Kt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
844
833
  import { redis } from "./redis";
845
834
 
846
835
  export class MutexTimeoutError extends Error {
@@ -900,7 +889,7 @@ export async function withMutex<T>(
900
889
  });
901
890
  }
902
891
  }
903
- `)}async function Eo(e){await l(Vt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
892
+ `)}async function gs(e){await l(Kt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
904
893
  import type { Store } from "hono-rate-limiter";
905
894
  import { env } from "./env";
906
895
 
@@ -1047,7 +1036,7 @@ export function createLimiterStore(): Store {
1047
1036
 
1048
1037
  /** No persistent connection to close with Upstash REST. */
1049
1038
  export async function closeRedis(): Promise<void> {}
1050
- `)}async function So(e){await l(Vt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1039
+ `)}async function ys(e){await l(Kt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1051
1040
  import { redis } from "./redis";
1052
1041
 
1053
1042
  export class MutexTimeoutError extends Error {
@@ -1125,10 +1114,10 @@ export async function withMutex<T>(
1125
1114
  });
1126
1115
  }
1127
1116
  }
1128
- `)}import{readFile as Ro}from"fs/promises";import{join as Po}from"path";var $n=" REDIS_URL: z.string(),",Ao=` UPSTASH_REDIS_REST_URL: z.string(),
1129
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Ln(e){let t=Po(e.projectDir,"packages/runtime/src/env.ts"),r=await Ro(t,"utf-8");if(!r.includes($n))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($n,Ao):r;await l(t,n)}import{readFile as jn}from"fs/promises";import{join as ee}from"path";var Bt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function tt(e){let t=await jn(e,"utf-8");return JSON.parse(t)}async function rt(e,t){let r=/\n([\t ]+)"/.exec(await jn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
1130
- `)}function $e(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function vt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Mn(e){await Io(e),await To(e),await _o(e),await Do(e),await No(e),await jo(e)}async function Io(e){let t=ee(e.projectDir,"packages/api/package.json"),r=await tt(t);$e(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&$e(r,["ioredis"]),await rt(t,r)}async function To(e){let t=ee(e.projectDir,"apps/web/package.json"),r=await tt(t);$e(r,["@upstash/ratelimit","@upstash/redis"]),await rt(t,r)}async function _o(e){let t=ee(e.projectDir,"packages/runtime/package.json"),r=await tt(t);e.cacheProvider==="upstash"&&($e(r,["ioredis","rate-limit-redis","redis-semaphore"]),vt(r,"@upstash/redis",Bt["@upstash/redis"]),vt(r,"@upstash/lock",Bt["@upstash/lock"])),await rt(t,r)}var wr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Oo=["@sentry/electron"],xo=[...wr.sentry,...wr.posthog];async function Do(e){let t=ee(e.projectDir,"packages/observability/package.json"),r=await tt(t),n=new Set(e.observability.flatMap(i=>wr[i]));if(!e.desktop)for(let i of Oo)n.delete(i);$e(r,xo.filter(i=>!n.has(i))),await rt(t,r)}async function No(e){let t=ee(e.projectDir,"packages/database/package.json"),r=await tt(t);e.databaseProvider==="neon"?($e(r,["pg","@types/pg"]),vt(r,"@neondatabase/serverless",Bt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&($e(r,["pg","@types/pg"]),vt(r,"postgres",Bt.postgres)),await rt(t,r)}var Co=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function $o(e){let t=await tt(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],vt(t,"@repo/api",r,!0),await rt(e,t))}var Lo=["instrumentation.ts","tests/instrumentation.test.ts"];async function jo(e){if(e.architecture!=="separate")return;let t=ee(e.projectDir,"apps/web");await Lt(ee(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Co)await Lt(ee(t,r),t);for(let r of Lo)await Lt(ee(t,r),t);await $o(ee(t,"package.json"))}import{readFile as Mo}from"fs/promises";import{join as Uo}from"path";var Fo=["base.json","node.json","next.json"],Un="GenerateSaaS ";async function Fn(e){if(!e.demo)for(let t of Fo){let r=Uo(e.projectDir,"tooling/typescript",t),n;try{n=await Mo(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Un)||(i.display=i.display.slice(Un.length),await l(r,JSON.stringify(i,null," ")+`
1131
- `))}}import{readFile as Bn,rm as Vo}from"fs/promises";import{join as bt}from"path";async function Kn(e){e.cacheProvider==="upstash"&&(await Promise.all([Vn(bt(e.projectDir,"packages/runtime/tests/setup.ts")),Vn(bt(e.projectDir,"packages/mail/tests/setup.ts")),Ko(e.projectDir),Vo(bt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Bo(e.projectDir))}async function Bo(e){await l(bt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1117
+ `)}import{readFile as vs}from"fs/promises";import{join as bs}from"path";var Nn=" REDIS_URL: z.string(),",ws=` UPSTASH_REDIS_REST_URL: z.string(),
1118
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Cn(e){let t=bs(e.projectDir,"packages/runtime/src/env.ts"),r=await vs(t,"utf-8");if(!r.includes(Nn))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(Nn,ws):r;await l(t,n)}import{readFile as $n}from"fs/promises";import{join as Q}from"path";var Gt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function rt(e){let t=await $n(e,"utf-8");return JSON.parse(t)}async function nt(e,t){let r=/\n([\t ]+)"/.exec(await $n(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
1119
+ `)}function Ne(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function ht(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Ln(e){await ks(e),await Es(e),await Ss(e),await Ps(e),await Is(e),await xs(e)}async function ks(e){let t=Q(e.projectDir,"packages/api/package.json"),r=await rt(t);Ne(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ne(r,["ioredis"]),await nt(t,r)}async function Es(e){let t=Q(e.projectDir,"apps/web/package.json"),r=await rt(t);Ne(r,["@upstash/ratelimit","@upstash/redis"]),await nt(t,r)}async function Ss(e){let t=Q(e.projectDir,"packages/runtime/package.json"),r=await rt(t);e.cacheProvider==="upstash"&&(Ne(r,["ioredis","rate-limit-redis","redis-semaphore"]),ht(r,"@upstash/redis",Gt["@upstash/redis"]),ht(r,"@upstash/lock",Gt["@upstash/lock"])),await nt(t,r)}var wr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Rs=["@sentry/electron"],As=[...wr.sentry,...wr.posthog];async function Ps(e){let t=Q(e.projectDir,"packages/observability/package.json"),r=await rt(t),n=new Set(e.observability.flatMap(i=>wr[i]));if(!e.desktop)for(let i of Rs)n.delete(i);Ne(r,As.filter(i=>!n.has(i))),await nt(t,r)}async function Is(e){let t=Q(e.projectDir,"packages/database/package.json"),r=await rt(t);e.databaseProvider==="neon"?(Ne(r,["pg","@types/pg"]),ht(r,"@neondatabase/serverless",Gt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ne(r,["pg","@types/pg"]),ht(r,"postgres",Gt.postgres)),await nt(t,r)}var Ts=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function _s(e){let t=await rt(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],ht(t,"@repo/api",r,!0),await nt(e,t))}var Os=["instrumentation.ts","tests/instrumentation.test.ts"];async function xs(e){if(e.architecture!=="separate")return;let t=Q(e.projectDir,"apps/web");await Mt(Q(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Ts)await Mt(Q(t,r),t);for(let r of Os)await Mt(Q(t,r),t);await _s(Q(t,"package.json"))}import{readFile as Ds}from"fs/promises";import{join as Ns}from"path";var Cs=["base.json","node.json","next.json"],jn="GenerateSaaS ";async function Mn(e){if(!e.demo)for(let t of Cs){let r=Ns(e.projectDir,"tooling/typescript",t),n;try{n=await Ds(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(jn)||(i.display=i.display.slice(jn.length),await l(r,JSON.stringify(i,null," ")+`
1120
+ `))}}import{readFile as Fn,rm as $s}from"fs/promises";import{join as gt}from"path";async function Vn(e){e.cacheProvider==="upstash"&&(await Promise.all([Un(gt(e.projectDir,"packages/runtime/tests/setup.ts")),Un(gt(e.projectDir,"packages/mail/tests/setup.ts")),js(e.projectDir),$s(gt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Ls(e.projectDir))}async function Ls(e){await l(gt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1132
1121
 
1133
1122
  /**
1134
1123
  * Regression guards for the Upstash-backed cache layer in src/redis.ts.
@@ -1250,9 +1239,9 @@ describe("cacheScan", () => {
1250
1239
  expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
1251
1240
  });
1252
1241
  });
1253
- `)}async function Vn(e){let t;try{t=await Bn(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",
1242
+ `)}async function Un(e){let t;try{t=await Fn(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",
1254
1243
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1255
- `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function Ko(e){let t=bt(e,"packages/api/tests/setup.ts"),r;try{r=await Bn(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",
1244
+ `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function js(e){let t=gt(e,"packages/api/tests/setup.ts"),r;try{r=await Fn(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",
1256
1245
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1257
1246
  `),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",
1258
1247
  UPSTASH_REDIS_REST_TOKEN: "test-token",
@@ -1281,19 +1270,33 @@ vi.mock("@upstash/lock", () => {
1281
1270
  return { Lock };
1282
1271
  });
1283
1272
 
1284
- $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 l(t,n)}import{readFile as Go}from"fs/promises";var Ho=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Yo=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Gn=32;function Wo(e){let t=e.lastIndexOf(".");return t>=0&&Yo.has(e.slice(t))}async function qo(e){let t=await Go(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Ho,"");r!==t&&await l(e,r)}async function Hn(e){let t=await ue(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Wo);for(let r=0;r<t.length;r+=Gn)await Promise.all(t.slice(r,r+Gn).map(qo))}import{readdir as qn,readFile as Le,rm as te}from"fs/promises";import{join as P}from"path";import{readFile as Wn,rm as I}from"fs/promises";import{join as E}from"path";import{readFile as wt}from"fs/promises";import{join as kt}from"path";async function Yn(e,t){let r=kt(e,"packages/api/src/routes/internal/index.ts");await l(r,Z(await wt(r,"utf-8"),"internal router","runner",t)),await dn(r);let n=kt(e,"packages/api/src/ai/schedule-runner.ts");await l(n,Z(await wt(n,"utf-8"),"schedule-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/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let a=kt(e,s);await l(a,Z(await wt(a,"utf-8"),s,"runner",t))}let i=kt(e,"packages/api/src/ai/settings-store.ts");await l(i,Z(await wt(i,"utf-8"),"settings-store.ts","runner",t));let o=kt(e,"packages/api/tests/ai/settings-store.test.ts");await l(o,Z(await wt(o,"utf-8"),"settings-store.test.ts","runner",t))}async function kr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await I(E(t,"packages/api/src/relay"),{recursive:!0}),await I(E(t,"packages/api/src/runner"),{recursive:!0}),await I(E(t,"packages/api/src/ai/runner-model.ts")),await I(E(t,"packages/api/src/ai/runner-routing.ts")),await I(E(t,"packages/api/tests/relay"),{recursive:!0}),await I(E(t,"packages/api/tests/runner"),{recursive:!0}),await I(E(t,"packages/api/src/routes/internal/runner.ts")),await I(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await I(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await I(E(t,"packages/api/tests/routes/runner.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await I(E(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await I(E(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await I(E(t,"packages/api/tests/ai/runner-model.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await I(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await I(E(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await I(E(t,"packages/api/tests/helpers/redis-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Wn(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 Ce(n,i," ",r),await Yn(t,r),await pn(t,"runner",["/runner"],r,"Runners"),await Y(E(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 Y(E(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=E(t,"docs/(platform)/configuration.mdx"),s="| `runner.enabled` |",a=(await Wn(o,"utf-8")).split(`
1285
- `).find(p=>p.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await Y(o,`${a}
1286
- `,"","configuration.mdx runner config-table row",r)}var zo=new Set(["ci.yml","desktop-release.yml"]),Jo=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],Xo=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function zn(e){let t=P(e.projectDir,".github/workflows"),r=await qn(t).catch(()=>[]);for(let n of r)zo.has(n)||await te(P(t,n),{recursive:!0,force:!0})}async function Zo(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 l(r,JSON.stringify(n,null,o)+`
1287
- `)}async function Jn(e){await Zo(e.projectDir,[...Xo])}async function Xn(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 l(t,JSON.stringify(n,null," ")+`
1288
- `))}async function Zn(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 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await l(t,JSON.stringify(r,null," ")+`
1289
- `)}async function Qn(e){e.docs||await te(P(e.projectDir,"apps/docs"),{recursive:!0})}async function ei(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 Ce(t,r," ","stripUnusedDocsSilo"),e.desktop||await te(P(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await Qo(e)}async function Kt(e,t,r,n){await l(e,Z(await Le(e,"utf-8"),t,r,n))}async function Qo(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 Y(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await Kt(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await Y(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 Y(P(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1290
- `,"","index.mdx desktop app card",r)),i||await Kt(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),!o&&e.runner&&(await Kt(P(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await Kt(P(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ti(e){if(e.desktop)return;await te(P(e.projectDir,"apps/electron"),{recursive:!0});let t=P(e.projectDir,"packages/i18n/translations");for(let i of await qn(t,{withFileTypes:!0}))i.isDirectory()&&await te(P(t,i.name,"desktop.json"),{force:!0});await te(P(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of Jo)await te(P(e.projectDir,i),{recursive:!0});await te(P(e.projectDir,"packages/utils/src/desktop-download.ts")),await te(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 Ce(r,n," ","stripDesktopApp")}function ea(e){return e.desktop}async function ri(e){ea(e)||await te(P(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ta}from"fs/promises";import{join as ra}from"path";var ni=`on:
1273
+ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let s of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(s))throw new Error(`pruneCacheTests: ${t} still contains ${s} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as Ms}from"fs/promises";var Us=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,Fs=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Bn=32;function Vs(e){let t=e.lastIndexOf(".");return t>=0&&Fs.has(e.slice(t))}async function Bs(e){let t=await Ms(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(Us,"");r!==t&&await l(e,r)}async function Kn(e){let t=await de(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Vs);for(let r=0;r<t.length;r+=Bn)await Promise.all(t.slice(r,r+Bn).map(Bs))}import{readdir as qn,readFile as Le,rm as ee}from"fs/promises";import{join as S}from"path";import{readFile as vt,rm as Ks}from"fs/promises";import{join as yt}from"path";function Gs(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Ee(e,t,r,n){let i=Gs(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let s=e.replace(i,"");if(s.includes(`gsaas:${r}-start`)||s.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return s.replace(/\n{3,}/g,`
1274
+
1275
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function W(e,t,r,n,i){let s=await vt(e,"utf-8"),o=s.indexOf(t);if(o===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(s.indexOf(t,o+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,s.slice(0,o)+r+s.slice(o+t.length))}async function Ce(e,t,r,n){let i=/\n([\t ]+)"/.exec(await vt(e,"utf-8"))?.[1];if(i!==r){let s=o=>o===" "?"tab":`${o.length}-space`;throw new Error(`${n}: expected ${e} to be ${s(r)}-indented, but it is ${i===void 0?"not indented":s(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
1276
+ `)}async function Hs(e,t,r){let n=yt(e,"ai.mdx"),s=(await vt(n,"utf-8")).split(`
1277
+ `).find(o=>o.includes(`href="${t}"`));if(s===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await W(n,`${s}
1278
+ `,"",`ai.mdx ${t} card`,r)}async function Ys(e,t,r){let n=yt(e,"ai.mdx"),i=`| **${t}** |`,o=(await vt(n,"utf-8")).split(`
1279
+ `).find(a=>a.startsWith(i));if(o===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await W(n,`${o}
1280
+ `,"",`ai.mdx ${t} hub-table row`,r)}async function Gn(e,t,r,n,i){let s=yt(e,"docs/(platform)");await Ks(yt(s,t),{recursive:!0}),await W(yt(s,"meta.json"),` "${t}",
1281
+ `,"",`docs meta.json ${t} nav entry`,n);for(let o of r)await Hs(s,o,n);i!==void 0&&await Ys(s,i,n)}function Ws(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]!==`
1282
+ `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
1283
+ `&&(t+=`
1284
+ `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let s=n;for(r++;r<e.length&&e[r]!==s;)e[r]==="\\"?r++:e[r]===`
1285
+ `&&(t+=`
1286
+ `),r++;r++;continue}t+=n,r++}return t}async function Hn(e){let t=`import { config } from "@repo/config";
1287
+ `,r=await vt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Ws(n);/\bconfig\b/.test(i)||await l(e,n)}import{readFile as Wn,rm as I}from"fs/promises";import{join as E}from"path";import{readFile as bt}from"fs/promises";import{join as wt}from"path";async function Yn(e,t){let r=wt(e,"packages/api/src/routes/internal/index.ts");await l(r,Ee(await bt(r,"utf-8"),"internal router","runner",t)),await Hn(r);let n=wt(e,"packages/api/src/ai/automation-runner.ts");await l(n,Ee(await bt(n,"utf-8"),"automation-runner.ts","runner",t));for(let o 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"]){let a=wt(e,o);await l(a,Ee(await bt(a,"utf-8"),o,"runner",t))}let i=wt(e,"packages/api/src/ai/settings-store.ts");await l(i,Ee(await bt(i,"utf-8"),"settings-store.ts","runner",t));let s=wt(e,"packages/api/tests/ai/settings-store.test.ts");await l(s,Ee(await bt(s,"utf-8"),"settings-store.test.ts","runner",t))}async function kr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await I(E(t,"packages/api/src/relay"),{recursive:!0}),await I(E(t,"packages/api/src/runner"),{recursive:!0}),await I(E(t,"packages/api/src/ai/runner-model.ts")),await I(E(t,"packages/api/src/ai/runner-routing.ts")),await I(E(t,"packages/api/tests/relay"),{recursive:!0}),await I(E(t,"packages/api/tests/runner"),{recursive:!0}),await I(E(t,"packages/api/src/routes/internal/runner.ts")),await I(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await I(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await I(E(t,"packages/api/tests/routes/runner.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await I(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await I(E(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await I(E(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await I(E(t,"packages/api/tests/ai/runner-model.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await I(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await I(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await I(E(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await I(E(t,"packages/api/tests/helpers/redis-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Wn(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 Ce(n,i," ",r),await Yn(t,r),await Gn(t,"runner",["/runner"],r,"Runners"),await W(E(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 W(E(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let s=E(t,"docs/(platform)/configuration.mdx"),o="| `runner.enabled` |",a=(await Wn(s,"utf-8")).split(`
1288
+ `).find(p=>p.startsWith(o));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await W(s,`${a}
1289
+ `,"","configuration.mdx runner config-table row",r)}var qs=new Set(["ci.yml","desktop-release.yml"]),zs=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],Js=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function zn(e){let t=S(e.projectDir,".github/workflows"),r=await qn(t).catch(()=>[]);for(let n of r)qs.has(n)||await ee(S(t,n),{recursive:!0,force:!0})}async function Xs(e,t){let r=S(e,"package.json"),n=JSON.parse(await Le(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let o of t)o in n.scripts&&(delete n.scripts[o],i=!0);if(!i)return;let s=/\n([\t ]+)"/.exec(await Le(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,s)+`
1290
+ `)}async function Jn(e){await Xs(e.projectDir,[...Js])}async function Xn(e){let t=S(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 l(t,JSON.stringify(n,null," ")+`
1291
+ `))}async function Zn(e){let t=S(e.projectDir,"package.json"),r=JSON.parse(await Le(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await l(t,JSON.stringify(r,null," ")+`
1292
+ `)}async function Qn(e){e.docs||await ee(S(e.projectDir,"apps/docs"),{recursive:!0})}async function ei(e){let t=S(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 Ce(t,r," ","stripUnusedDocsSilo"),e.desktop||await ee(S(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await Zs(e)}async function $e(e,t,r,n){await l(e,Ee(await Le(e,"utf-8"),t,r,n))}async function Zs(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=S(t,"docs/(platform)/configuration.mdx"),i=e.desktop,s=e.desktop&&e.ai;e.desktop||(await W(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await $e(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await W(S(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await $e(S(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await $e(S(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await $e(S(t,"docs/(platform)/testing.mdx"),"testing.mdx desktop e2e callout","desktop-testing-docs",r),await W(S(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1293
+ `,"","index.mdx desktop app card",r)),i||await $e(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),!s&&e.runner&&(await $e(S(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await $e(S(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ti(e){if(e.desktop)return;await ee(S(e.projectDir,"apps/electron"),{recursive:!0});let t=S(e.projectDir,"packages/i18n/translations");for(let i of await qn(t,{withFileTypes:!0}))i.isDirectory()&&await ee(S(t,i.name,"desktop.json"),{force:!0});await ee(S(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of zs)await ee(S(e.projectDir,i),{recursive:!0});await ee(S(e.projectDir,"packages/utils/src/desktop-download.ts")),await ee(S(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=S(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 Ce(r,n," ","stripDesktopApp")}function Qs(e){return e.desktop}async function ri(e){Qs(e)||await ee(S(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ea}from"fs/promises";import{join as ta}from"path";var ni=`on:
1291
1294
  workflow_run:
1292
1295
  workflows: ["Tag Release"]
1293
1296
  branches: [main]
1294
1297
  types: [completed]
1295
- workflow_dispatch:`,na=`on:
1296
- workflow_dispatch:`;async function ii(e){if(!e.desktop)return;let t=ra(e.projectDir,".github/workflows/desktop-release.yml"),r=await ta(t,"utf8");if(!r.includes(ni))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(ni,na))}import{join as ia}from"path";async function si(e){let t=sa(e);await l(ia(e.projectDir,".github/workflows/ci.yml"),t)}function sa(e){let t=e.cacheProvider==="upstash",i=` services:
1298
+ workflow_dispatch:`,ra=`on:
1299
+ workflow_dispatch:`;async function ii(e){if(!e.desktop)return;let t=ta(e.projectDir,".github/workflows/desktop-release.yml"),r=await ea(t,"utf8");if(!r.includes(ni))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(ni,ra))}import{join as na}from"path";async function oi(e){let t=ia(e);await l(na(e.projectDir,".github/workflows/ci.yml"),t)}function ia(e){let t=e.cacheProvider==="upstash",i=` services:
1297
1300
  postgres:
1298
1301
  image: postgres:18-alpine
1299
1302
  env:
@@ -1316,14 +1319,14 @@ ${t?"":` redis:
1316
1319
  --health-interval 10s
1317
1320
  --health-timeout 5s
1318
1321
  --health-retries 5
1319
- `}`,o="postgres://postgres:postgres@localhost:5432/saas",s=t?`
1322
+ `}`,s="postgres://postgres:postgres@localhost:5432/saas",o=t?`
1320
1323
  UPSTASH_REDIS_REST_URL: https://test.upstash.io
1321
1324
  UPSTASH_REDIS_REST_TOKEN: test-token`:`
1322
1325
  REDIS_URL: redis://localhost:6379`,a=(()=>{switch(e.paymentProvider){case"stripe":return`
1323
1326
  STRIPE_SECRET_KEY: test
1324
1327
  STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
1325
1328
  POLAR_ACCESS_TOKEN: test
1326
- POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1329
+ POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let f=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(f)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1327
1330
  # which auto-deploys on push. CI runs in parallel as a quality gate.
1328
1331
  # For PR-based workflows, enable GitHub branch protection to require CI before merging.
1329
1332
 
@@ -1348,7 +1351,7 @@ jobs:
1348
1351
  runs-on: ubuntu-latest
1349
1352
  timeout-minutes: 20
1350
1353
  ${i} env:
1351
- CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
1354
+ CONTENT_API_KEY: test-contentapi-key-16chars${o}${a}
1352
1355
  STORAGE_REGION: test
1353
1356
  STORAGE_ENDPOINT: http://test
1354
1357
  STORAGE_ACCESS_KEY_ID: test
@@ -1364,24 +1367,24 @@ ${i} env:
1364
1367
  - run: pnpm check-types
1365
1368
 
1366
1369
  - name: Write root env
1367
- run: echo "DATABASE_URL=${o}" > .env
1370
+ run: echo "DATABASE_URL=${s}" > .env
1368
1371
 
1369
1372
  - run: pnpm test
1370
- `}import{readFile as oi}from"fs/promises";import{existsSync as oa}from"fs";import{join as Er}from"path";var ai="@repo/database";function aa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function ca(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 la(e,t,r){let n=await oi(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(ai)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,JSON.stringify(i,null," ")+`
1371
- `))}async function pa(e,t){let r=oa(e)?JSON.parse(await oi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(ai)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
1372
- `))}async function ci(e){let t=aa(e.demo===!0),r=ca(e.architecture),n=Er(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await la(Er(n,"package.json"),"start",t);return;case"vercel":await pa(Er(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as da}from"fs/promises";import{existsSync as ua}from"fs";import{join as Gt}from"path";var li=["stripe","polar"],ma=[...li,"none"];async function pi(e){let t=Gt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1373
- // ${ma.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1373
+ `}import{readFile as si}from"fs/promises";import{existsSync as oa}from"fs";import{join as Er}from"path";var ai="@repo/database";function sa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function aa(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 ca(e,t,r){let n=await si(e,"utf-8"),i=JSON.parse(n),s=i.scripts?.[t];if(!s)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);s.includes(ai)||(i.scripts={...i.scripts,[t]:`${r} && ${s}`},await l(e,JSON.stringify(i,null," ")+`
1374
+ `))}async function la(e,t){let r=oa(e)?JSON.parse(await si(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(ai)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
1375
+ `))}async function ci(e){let t=sa(e.demo===!0),r=aa(e.architecture),n=Er(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ca(Er(n,"package.json"),"start",t);return;case"vercel":await la(Er(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as pa}from"fs/promises";import{existsSync as da}from"fs";import{join as Ht}from"path";var li=["stripe","polar"],ua=[...li,"none"];async function pi(e){let t=Ht(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1376
+ // ${ua.filter(s=>s!==r).map(s=>`"./${s}/index"`).join(" or ")} (other folders are kept in place).
1374
1377
  export { ops } from "./${r}/index";
1375
- `;await l(Gt(t,"providers/index.ts"),i),await l(Gt(t,"index.ts"),await fa(t,r))}async function fa(e,t){let r=Gt(e,"index.ts");if(!ua(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await da(r,"utf-8"),i=li.filter(s=>s!==t);return n.split(`
1376
- `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1377
- `)}import{access as ha,readFile as Wt,rm as Ht}from"fs/promises";import{join as W}from"path";var hi=["sentry","posthog"],Sr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Yt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},ga=["tests/resolution.test.ts","tests/export-isolation.test.ts"],ya=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],va=["./desktop-main","./desktop-renderer"],ba=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1378
+ `;await l(Ht(t,"providers/index.ts"),i),await l(Ht(t,"index.ts"),await ma(t,r))}async function ma(e,t){let r=Ht(e,"index.ts");if(!da(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await pa(r,"utf-8"),i=li.filter(o=>o!==t);return n.split(`
1379
+ `).filter(o=>!i.some(a=>o.includes(`./providers/${a}/`))).join(`
1380
+ `)}import{access as fa,readFile as qt,rm as Yt}from"fs/promises";import{join as q}from"path";var hi=["sentry","posthog"],Sr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Wt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},ha=["tests/resolution.test.ts","tests/export-isolation.test.ts"],ga=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],ya=["./desktop-main","./desktop-renderer"],va=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1378
1381
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1379
- `],wa=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],di=`
1382
+ `],ba=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],di=`
1380
1383
  });
1381
- `,ka=" ";async function gi(e){let t=W(e.projectDir,"packages/observability");await ui(t,"packages/observability");let r=e.observability,n=r.filter(s=>!B.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: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await ui(W(t,Sr[s]),`packages/observability/${Sr[s]}`);let i=e.desktop?[...fi,...sc]:fi,o=new Map;for(let s of i)o.set(s.file,await Wt(W(t,s.file),"utf-8"));for(let s of xa(r,e.desktop))await Da(t,s);for(let s of hi)if(!r.includes(s)){await Ht(W(t,Sr[s]),{recursive:!0,force:!0});for(let a of Yt[s])await Ht(W(t,a),{force:!0})}for(let s of ga)await Ht(W(t,s),{force:!0});e.desktop||await Ea(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(W(t,s.file),Pa(a,s,r))}}async function ui(e,t){try{await ha(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Ea(e,t){for(let i of ya)await Ht(W(e,i),{force:!0});t.includes("sentry")&&await Sa(e);let r=W(e,"package.json"),n=JSON.parse(await Wt(r,"utf-8"));for(let i of va){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ce(r,n," ","generateObservabilityProvider")}async function Sa(e){let t=W(e,Yt.sentry[0]),r=await Wt(t,"utf-8");r=Rr(r,ba.map(n=>({find:n,replace:""})),Yt.sentry[0]);for(let n of wa)r=Ra(r,n,Yt.sentry[0]);await l(t,r)}function Ra(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(di,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.indexOf(t,n+t.length)!==-1)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(`
1382
- `).find(a=>a.trim().length>0&&!a.startsWith(`${ka} `));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+di.length;return e[s]===`
1383
- `&&(s+=1),e.slice(0,n)+e.slice(s)}function Pa(e,t,r){let n=hi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=Aa(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:Ta,replace:_a(r)}],t.file)),i=Rr(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Rr(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1384
- `)[0]}`);n=n.replace(i.find,i.replace)}return n}function Aa(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Ia(o)),"")),bindings:n}}function Ia(e){let t=/^import\s+(?:type\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-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var Ta=" * 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 _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 no provider adapter and no reporting
1384
+ `,wa=" ";async function gi(e){let t=q(e.projectDir,"packages/observability");await ui(t,"packages/observability");let r=e.observability,n=r.filter(o=>!B.includes(o));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let o of r)await ui(q(t,Sr[o]),`packages/observability/${Sr[o]}`);let i=e.desktop?[...fi,...ic]:fi,s=new Map;for(let o of i)s.set(o.file,await qt(q(t,o.file),"utf-8"));for(let o of Oa(r,e.desktop))await xa(t,o);for(let o of hi)if(!r.includes(o)){await Yt(q(t,Sr[o]),{recursive:!0,force:!0});for(let a of Wt[o])await Yt(q(t,a),{force:!0})}for(let o of ha)await Yt(q(t,o),{force:!0});e.desktop||await ka(t,r);for(let o of i){let a=s.get(o.file);a!==void 0&&await l(q(t,o.file),Ra(a,o,r))}}async function ui(e,t){try{await fa(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function ka(e,t){for(let i of ga)await Yt(q(e,i),{force:!0});t.includes("sentry")&&await Ea(e);let r=q(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of ya){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ce(r,n," ","generateObservabilityProvider")}async function Ea(e){let t=q(e,Wt.sentry[0]),r=await qt(t,"utf-8");r=Rr(r,va.map(n=>({find:n,replace:""})),Wt.sentry[0]);for(let n of ba)r=Sa(r,n,Wt.sentry[0]);await l(t,r)}function Sa(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(di,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.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let s=e.slice(n+t.length,i).split(`
1385
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${wa} `));if(s!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${s.trim()}`);let o=i+di.length;return e[o]===`
1386
+ `&&(o+=1),e.slice(0,n)+e.slice(o)}function Ra(e,t,r){let n=hi.filter(o=>!r.includes(o)),i=e,s=[];for(let o of n){let a=Aa(i,o);i=a.source,s.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:Ia,replace:Ta(r)}],t.file)),i=Rr(i,t.edits(r),t.file);for(let o of n)if(i.includes(`./providers/${o}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${o} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let o of s)if(new RegExp(String.raw`\b${o}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${o}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Rr(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1387
+ `)[0]}`);n=n.replace(i.find,i.replace)}return n}function Aa(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,s=>(n.push(...Pa(s)),"")),bindings:n}}function Pa(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(o=>o.trim().replace(/^type\s+/,"")).map(o=>o.split(/\s+as\s+/).at(-1)??"").filter(o=>o.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),s=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return s?.[1]?r.push(s[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var Ia=" * 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 Ta(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
1385
1388
  * 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
1386
1389
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1387
1390
  *
@@ -1389,123 +1392,123 @@ export { ops } from "./${r}/index";
1389
1392
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1390
1393
  * update stages nothing while you are already on the latest version, so the switch lands with the
1391
1394
  * next release. Pasting the other provider's credential into \`config.observability\` on its own
1392
- * cannot: the adapter it would need is not here.`}var mi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Oa={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function xa(e,t){return e.includes("sentry")?[]:t?[mi,Oa]:[mi]}async function Da(e,t){let r=await Wt(W(e,t.source),"utf-8"),n=`export interface ${t.name} {
1393
- `,i=r.indexOf(n),o=r.indexOf(`
1395
+ * cannot: the adapter it would need is not here.`}var mi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},_a={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Oa(e,t){return e.includes("sentry")?[]:t?[mi,_a]:[mi]}async function xa(e,t){let r=await qt(q(e,t.source),"utf-8"),n=`export interface ${t.name} {
1396
+ `,i=r.indexOf(n),s=r.indexOf(`
1394
1397
  }
1395
- `,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(`
1396
- `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.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 Na=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Ca=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1397
- `,$a=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1398
+ `,i);if(i===-1||s===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let o=r.slice(i+n.length,s).split(`
1399
+ `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(o.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${o.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var Da=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Na=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1400
+ `,Ca=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1398
1401
  ops.push(posthogServerOps);
1399
1402
  }
1400
- `,La=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1403
+ `,$a=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1401
1404
  await initSentryServer();
1402
1405
  }
1403
- `,ja=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1404
- `,Ma=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1405
- `,Ua=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1406
+ `,La=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1407
+ `,ja=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1408
+ `,Ma=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1406
1409
  `,yi=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1407
1410
  announceMissingDesktopSdk("posthog");
1408
1411
  }
1409
- `,Fa="export type BrowserReportingOptions = SentryBrowserInitOptions;",Va=`export interface BrowserReportingOptions {
1412
+ `,Ua="export type BrowserReportingOptions = SentryBrowserInitOptions;",Fa=`export interface BrowserReportingOptions {
1410
1413
  /** The deployment environment reports are tagged with. */
1411
1414
  environment: string;
1412
- }`,Ba=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1413
- `,Ka=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1414
- `,Ga="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",Ha=`export interface DesktopMainReportingOptions {
1415
+ }`,Va=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1416
+ `,Ba=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1417
+ `,Ka="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",Ga=`export interface DesktopMainReportingOptions {
1415
1418
  /** The deployment environment reports are tagged with. */
1416
1419
  environment: string;
1417
1420
  /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1418
1421
  appIsReady: boolean;
1419
- }`,Ya=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1420
- `,Wa=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1421
- `;function vi(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 qa(e){let t=[{find:Na,replace:" into every browser bundle."},...vi(e,{sentry:Ca,posthog:$a})];return e.includes("sentry")||t.push({find:La,replace:""}),t}function za(e){let t=[...vi(e,{sentry:ja,posthog:Ma})];return e.includes("sentry")||t.push({find:Ua,replace:""},Ja),t}var Ja={find:Fa,replace:Va};function Xa(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Ba,replace:` return [];
1422
- `},{find:Ka,replace:""},{find:Ga,replace:Ha}),t}function Za(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Ya,replace:` return [];
1423
- `},{find:Wa,replace:""}),t}var Qa=` if (!posthogConfigured()) return;
1422
+ }`,Ha=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1423
+ `,Ya=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1424
+ `;function vi(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 Wa(e){let t=[{find:Da,replace:" into every browser bundle."},...vi(e,{sentry:Na,posthog:Ca})];return e.includes("sentry")||t.push({find:$a,replace:""}),t}function qa(e){let t=[...vi(e,{sentry:La,posthog:ja})];return e.includes("sentry")||t.push({find:Ma,replace:""},za),t}var za={find:Ua,replace:Fa};function Ja(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Va,replace:` return [];
1425
+ `},{find:Ba,replace:""},{find:Ka,replace:Ga}),t}function Xa(e){let t=[];return e.includes("posthog")||t.push({find:yi,replace:""}),e.includes("sentry")||t.push({find:Ha,replace:` return [];
1426
+ `},{find:Ya,replace:""}),t}var Za=` if (!posthogConfigured()) return;
1424
1427
  try {
1425
1428
  const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1426
1429
  await capture(event);
1427
1430
  } catch (reportingError) {
1428
1431
  logReportingFailure("[observability] failed to report an AI generation", reportingError);
1429
1432
  }
1430
- `,ec=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1431
- `,tc=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1432
- `,rc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1433
+ `,Qa=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1434
+ `,ec=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1435
+ `,tc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1433
1436
  function posthogConfigured(): boolean {
1434
1437
  return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1435
1438
  }
1436
1439
 
1437
- `,nc=` if (!posthogConfigured()) return;
1440
+ `,rc=` if (!posthogConfigured()) return;
1438
1441
  try {
1439
1442
  const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1440
1443
  await flush();
1441
1444
  } catch (reportingError) {
1442
1445
  logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1443
1446
  }
1444
- `;function ic(e){return e.includes("posthog")?[]:[{find:Qa,replace:ec},{find:nc,replace:tc},{find:rc,replace:""},{find:`import { logReportingFailure } from "./logger";
1447
+ `;function nc(e){return e.includes("posthog")?[]:[{find:Za,replace:Qa},{find:rc,replace:ec},{find:tc,replace:""},{find:`import { logReportingFailure } from "./logger";
1445
1448
  `,replace:""},{find:`import { config } from "@repo/config";
1446
- `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var fi=[{file:"src/resolve-server.ts",edits:qa},{file:"src/resolve-browser.ts",edits:za},{file:"src/llm-analytics.ts",edits:ic,dualMode:!1}],sc=[{file:"src/resolve-desktop-main.ts",edits:Xa},{file:"src/resolve-desktop-renderer.ts",edits:Za}];import{readdir as oc,readFile as ac}from"fs/promises";import{join as bi}from"path";async function wi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=bi(e.projectDir,"packages/i18n/translations"),i;try{i=await oc(n)}catch{return}for(let o of i){let s=bi(n,o,"web.json"),a;try{a=await ac(s,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(s,p)}}async function qt(e){let t=e.projectDir;e.demo||(await fn(t),await gn(t),await yn(t),await vn(t),e.desktop&&await hn(t)),await bn(t),await En(e),await Rn(e),await Pn(e),e.demo||await An(e),await On(e),await xn(e),await Dn(e),await Nn(e),await Cn(e),await Ln(e),await Mn(e),await Fn(e),await Kn(e),await zn(e),await si(e),await Jn(e),await Xn(e),await Zn(e),await Qn(e),await ei(e),await ti(e),await ri(e),await ii(e),await kr(e),await ci(e),await pi(e),await gi(e),await wi(e),await Hn(e)}import{basename as Ei,join as Si,relative as lc}from"path";import{createHash as ki}from"crypto";import{readFile as cc}from"fs/promises";async function zt(e){let t=await cc(e);return ki("sha256").update(t).digest("hex")}function Pr(e){return ki("sha256").update(e).digest("hex")}var pc=new Set(["data",H]);function dc(e){let t=e.split("/");for(let r of t)if(lr.has(r)||pr.has(r)||pc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ri(e,t){return{projectName:e.projectName??Ei(t),appName:e.appName??e.projectName??Ei(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,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 uc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:Zr,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,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 Pi(e,t){let n=(await ue(e.projectDir,e.projectDir,dc)).sort(),i=await Promise.all(n.map(async a=>[Ne(lc(e.projectDir,a)),await zt(a)])),o=Object.fromEntries(i),s=uc(e,t);await l(Si(e.projectDir,ve),JSON.stringify(s,null," ")+`
1447
- `),await l(Si(e.projectDir,Qr),JSON.stringify(o,null," ")+`
1448
- `)}import{relative as mc}from"path";async function nt(e){let r=(await ue(e,e,Qe)).sort(),n=await Promise.all(r.map(async i=>[Ne(mc(e,i)),await zt(i)]));return Object.fromEntries(n)}import{copyFile as fc,mkdir as hc,rm as gc}from"fs/promises";import{dirname as yc,join as Ai,relative as vc}from"path";import{existsSync as bc}from"fs";async function Ar(e,t){bc(t)&&await gc(t,{recursive:!0,force:!0});let n=(await ue(e,e,Qe)).map(i=>({file:i,dest:Ai(t,Ne(vc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>yc(i)))].map(i=>hc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>fc(i,o)))}async function Ii(e,t){await Ar(e,Ai(t,xt))}import{existsSync as wc}from"fs";import{readFile as Ti,readdir as kc}from"fs/promises";import{join as re,dirname as Ec,resolve as Sc,sep as Rc}from"path";import{fileURLToPath as Pc}from"url";var Ac={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},je=Object.values(Ac),Ir="generatesaas-update",_i=Ec(Pc(import.meta.url));function Ic(){let e=re(_i,"skill","content");return wc(e)?e:re(_i,"content")}async function Tr(e,t,r){for(let n of je){let i=re(e,n,Ir),o=re(i,"scripts"),s=re(i,"references");await $t(o),await $t(s),await l(re(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(re(s,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let m=Sc(o,a);m.startsWith(o+Rc)&&await l(m,p)}}}async function Oi(e){let t=Ic(),r=await Ti(re(t,"SKILL.md"),"utf-8"),n=re(t,"scripts"),i=await kc(n),o={};for(let s of i)s!==".gitkeep"&&(o[s]=await Ti(re(n,s),"utf-8"));await Tr(e,r,o)}import{execFile as Tc,execFileSync as _c}from"child_process";import{access as xi,readFile as Oc}from"fs/promises";import{join as _r}from"path";import*as N from"@clack/prompts";function Ue(e){try{let t=process.platform==="win32"?"where":"which";return _c(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Me(e,t,r,n=3e5){return new Promise((i,o)=>{Tc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,p)=>{if(s){let m=String(a||"").trim(),g=[String(p||"").trim(),m].filter(Boolean).join(`
1449
- `);o(new Error(g?`${s.message}
1450
- ${g}`:s.message))}else i()})})}async function Di(e){if(!Ue("pnpm"))return N.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Me("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return N.log.warn(`Lockfile regeneration failed: ${r}`),N.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Ni(e){if(!Ue("pnpm"))return N.log.warn("pnpm not found. Skipping dependency installation."),N.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=N.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Me("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 N.log.warn(`pnpm install failed: ${n}`),N.log.warn("You can run it manually later."),!1}}async function Ci(e){if(!Ue("pnpm"))return!1;let t=N.spinner();t.start("Generating baseline database migration...");try{return await Me("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 N.log.warn(`Could not generate baseline migration: ${n}`),N.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function $i(e){try{return await xi(_r(e,".git")),N.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ue("git"))return N.log.warn("git not found. Skipping repository initialization."),!1;let t=N.spinner();t.start("Initializing git repository...");try{return await Me("git",["init"],e),await Me("git",["add","-A"],e),await Me("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),N.log.warn("You can run git init manually later."),!1}}async function Li(e){if(!Ue("pnpm"))return!1;try{await xi(_r(e,".git"))}catch{return!1}try{let t=JSON.parse(await Oc(_r(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 Me("pnpm",["exec","simple-git-hooks"],e),!0}catch{return N.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Fe from"@clack/prompts";import q from"picocolors";function ji(e,t){let r=We(e);t.dockerAvailable||Fe.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Fe.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 - deploying without it crash-loops the container.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${q.dim(`# ${r.map(a=>Vr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${q.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(q.dim("Fill in remaining TODO values in .env"))),Fe.note(n.join(`
1451
- `),q.yellow("Start Development"));let i=[];i.push(`App ${q.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${q.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${q.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${q.cyan("http://localhost:8288")}`),Fe.note(i.join(`
1452
- `),q.yellow("Dev Tools"));let o=[],s=xc(e);s.length>0&&o.push(`Set in production: ${q.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(Dc(e)),Fe.note(o.join(`
1453
- `),q.yellow("Deployment"))}function xc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];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 Dc(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 it(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 Ve(e,t){let r=it(e),n=it(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 Jt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Mi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:it(e)===null}function Xt(e,t,r="3.1.1"){if(Mi(r))return{ok:!0};let n=Jt(e,e.latest);return!n||it(n)===null?{ok:!0}:Ve(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 Ui(e,t,r="3.1.1"){if(Mi(r))return{ok:!0};let n=Jt(e,t);return!n||it(n)===null?{ok:!0}:Ve(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 Mc from"picocolors";var Uc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Fc(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 Fi(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([...qe])).addOption(new ne("--payment <provider>","payment provider").choices([...ze])).addOption(new ne("--email <provider>","email provider").choices([...Je])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, schedules, 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 app is the AI product. Requires --desktop and --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([...oe])).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([...Oe])).addOption(new ne("--deploy <target>","deployment target").choices([...ae])).addOption(new ne("--database <provider>","database provider").choices([...ce])).addOption(new ne("--cache <provider>","cache provider").choices([...le])).option("--observability <providers>",`comma-separated observability providers (${B.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 Vc(t?{...r,apiKey:t}:r)})}async function Vc(e){let t=performance.now();Ur("3.1.1");let r;try{r=zr(e)}catch(v){b.cancel(D(v)),process.exit(1)}let n=b.spinner(),i;try{i=await Ze({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(D(v)),process.exit(1)}e.demo&&Pr(i)!==Uc&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=de(i),s,a=async()=>{s=await ke(o);let v=Xt(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}};n.start("Verifying access...");let p,m,w=!0,g=!0;try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await dt(),o=de(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(x){n.stop("Access verification failed."),b.cancel(x instanceof j&&x.status===401?"Invalid API key.":D(x)),process.exit(1)}}else b.cancel(D(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!w&&(b.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(b.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let k;e.yes?k=Jr({...r,...w?{}:{desktop:!1},...g?{}:{runner:!1}}):k=await Xr(r,{desktopAllowed:w,runnerAllowed:g});let A;n.start("Activating license...");try{let v=e.demo&&k.baseUrl?await Fc(k.baseUrl):crypto.randomUUID(),x=()=>({frontend:or,version:m,installId:v,projectName:k.projectName,options:sn(k)}),L;try{L=await ar(o,x())}catch(ge){let U=Dt(ge);if(!U?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let F=Ui(s,U.lastAllowedVersion);if(F.ok||(b.cancel(`${U.message} ${F.message}`),process.exit(1)),e.yes){let Pe=Jt(s,U.lastAllowedVersion);b.cancel(`${U.message} Re-run ${Pe?`npx generatesaas@${Pe} init`:"init"} without --yes to continue with v${U.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let V=await b.confirm({message:`Your update window has ended. Continue with v${U.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(V)||!V)&&(b.cancel("Setup cancelled."),process.exit(0)),m=U.lastAllowedVersion,n.start(`Activating license for v${m}...`),L=await ar(o,x())}A={token:L.token,keyHash:Pr(i),installId:L.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(D(v)),process.exit(1)}let f=jc(k.projectDir);if(Nc(f)&&Cc(f).length>0)if(e.yes)b.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let x=await b.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"}]});(b.isCancel(x)||x==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),x==="overwrite"&&$c(f,{recursive:!0,force:!0})}let $={...k,projectDir:f,version:m,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Nt(o,m,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(D(v)),process.exit(1)}n.start("Generating project files...");try{if(await qt($),!e.demo){let v=await nt(f);await l(Lc(f,Ot),JSON.stringify(v,null," ")+`
1454
- `),await Ii(f,f)}await Oi(f),await Pi($,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await Di(f)&&$.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Ni(f),X=$.demo!==!0&&e.dbMigration!==!1,he=!1;X&&fe&&(await Ci(f),he=!0),await $i(f),fe&&await Li(f);let Ee=Ue("docker"),Re=nr($).map(v=>v.key).filter(v=>!$.credentials?.[v]);ji($,{pnpmInstalled:fe,dockerAvailable:Ee,skippedCredentials:Re,baselineMigrationMissing:X&&!he}),Fr(),b.log.info(Mc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Nr}from"fs";import{readFile as zi}from"fs/promises";import{join as st,resolve as zc}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as Bc,rm as Kc}from"fs/promises";import{tmpdir as Gc}from"os";import{join as Hc}from"path";async function Or(e,t,r,n){let i=await Bc(Hc(Gc(),"generatesaas-stage-"));try{await Nt(e,t,i),await qt({...r,projectDir:i}),await Ar(i,n)}finally{await Kc(i,{recursive:!0,force:!0})}}function Et(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var xr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:qe,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:ae,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:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:ze,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Je,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:B,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:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",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/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, 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, schedules, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop 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 the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop 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.runner!==!0,requiresLabel:"requires AI features and the desktop 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&&ie({...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=>Et(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 Yc(e,t){return e[t]!==void 0}function Vi(e){return xr.filter(t=>t.adoptable&&!Yc(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 Wc(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 qc(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 Bi(e){let t=[];for(let r of xr){let n=e[r.key];n!==void 0&&(Wc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${qc(r)}.`))}return t}function Ki(e){let t={};for(let r of xr)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 Gi(e){return e?"ON":"OFF"}var St="packages/config/src/index.ts";function Hi(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 Yi(e){return[...We({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Dr=[{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 ${St} 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 ${St} 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 ${St}. 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===Et(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Gi(e.aiBuiltin)}, but it is now a plain config value generated ${Gi(Et(e))} for a project ${Et(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${St} 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 ${St} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Hi(e).join(",")===Yi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Hi(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 ${Yi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Kr.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 (${je.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.`}],sf=Dr.map(e=>e.key);function Wi(e){for(let t of Dr)t.normalize?.(e)}function qi(e){let t=[];for(let r of Dr){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 Ji(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=zc(r.cwd??process.cwd()),o=st(i,ve),s;try{s=JSON.parse(await zi(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===ir&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
1449
+ `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var fi=[{file:"src/resolve-server.ts",edits:Wa},{file:"src/resolve-browser.ts",edits:qa},{file:"src/llm-analytics.ts",edits:nc,dualMode:!1}],ic=[{file:"src/resolve-desktop-main.ts",edits:Ja},{file:"src/resolve-desktop-renderer.ts",edits:Xa}];import{readdir as oc,readFile as sc}from"fs/promises";import{join as bi}from"path";async function wi(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=bi(e.projectDir,"packages/i18n/translations"),i;try{i=await oc(n)}catch{return}for(let s of i){let o=bi(n,s,"web.json"),a;try{a=await sc(o,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(o,p)}}async function zt(e){let t=e.projectDir;e.demo||(await mn(t),await fn(t),await hn(t),await gn(t)),await yn(t),await wn(e),await En(e),await Sn(e),e.demo||await Rn(e),await Tn(e),await _n(e),await On(e),await xn(e),await Dn(e),await Cn(e),await Ln(e),await Mn(e),await Vn(e),await zn(e),await oi(e),await Jn(e),await Xn(e),await Zn(e),await Qn(e),await ei(e),await ti(e),await ri(e),await ii(e),await kr(e),await ci(e),await pi(e),await gi(e),await wi(e),await Kn(e)}import{basename as Ei,join as Si,relative as cc}from"path";import{createHash as ki}from"crypto";import{readFile as ac}from"fs/promises";async function Jt(e){let t=await ac(e);return ki("sha256").update(t).digest("hex")}function Ar(e){return ki("sha256").update(e).digest("hex")}var lc=new Set(["data",Y]);function pc(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||lc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ri(e,t){return{projectName:e.projectName??Ei(t),appName:e.appName??e.projectName??Ei(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,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 dc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:Zr,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,blog:e.blog,docs:e.docs,desktop:e.desktop,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 Ai(e,t){let n=(await de(e.projectDir,e.projectDir,pc)).sort(),i=await Promise.all(n.map(async a=>[De(cc(e.projectDir,a)),await Jt(a)])),s=Object.fromEntries(i),o=dc(e,t);await l(Si(e.projectDir,ye),JSON.stringify(o,null," ")+`
1450
+ `),await l(Si(e.projectDir,Qr),JSON.stringify(s,null," ")+`
1451
+ `)}import{relative as uc}from"path";async function it(e){let r=(await de(e,e,et)).sort(),n=await Promise.all(r.map(async i=>[De(uc(e,i)),await Jt(i)]));return Object.fromEntries(n)}import{copyFile as mc,mkdir as fc,rm as hc}from"fs/promises";import{dirname as gc,join as Pi,relative as yc}from"path";import{existsSync as vc}from"fs";async function Pr(e,t){vc(t)&&await hc(t,{recursive:!0,force:!0});let n=(await de(e,e,et)).map(i=>({file:i,dest:Pi(t,De(yc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>gc(i)))].map(i=>fc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:s})=>mc(i,s)))}async function Ii(e,t){await Pr(e,Pi(t,xt))}import{existsSync as bc}from"fs";import{readFile as Ti,readdir as wc}from"fs/promises";import{join as te,dirname as kc,resolve as Ec,sep as Sc}from"path";import{fileURLToPath as Rc}from"url";var Ac={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},je=Object.values(Ac),Ir="generatesaas-update",_i=kc(Rc(import.meta.url));function Pc(){let e=te(_i,"skill","content");return bc(e)?e:te(_i,"content")}async function Tr(e,t,r){for(let n of je){let i=te(e,n,Ir),s=te(i,"scripts"),o=te(i,"references");await jt(s),await jt(o),await l(te(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(te(o,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let f=Ec(s,a);f.startsWith(s+Sc)&&await l(f,p)}}}async function Oi(e){let t=Pc(),r=await Ti(te(t,"SKILL.md"),"utf-8"),n=te(t,"scripts"),i=await wc(n),s={};for(let o of i)o!==".gitkeep"&&(s[o]=await Ti(te(n,o),"utf-8"));await Tr(e,r,s)}import{execFile as Ic,execFileSync as Tc}from"child_process";import{access as xi,readFile as _c}from"fs/promises";import{join as _r}from"path";import*as D from"@clack/prompts";function Ue(e){try{let t=process.platform==="win32"?"where":"which";return Tc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Me(e,t,r,n=3e5){return new Promise((i,s)=>{Ic(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(o,a,p)=>{if(o){let f=String(a||"").trim(),y=[String(p||"").trim(),f].filter(Boolean).join(`
1452
+ `);s(new Error(y?`${o.message}
1453
+ ${y}`:o.message))}else i()})})}async function Di(e){if(!Ue("pnpm"))return D.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Me("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return D.log.warn(`Lockfile regeneration failed: ${r}`),D.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Ni(e){if(!Ue("pnpm"))return D.log.warn("pnpm not found. Skipping dependency installation."),D.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=D.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Me("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 D.log.warn(`pnpm install failed: ${n}`),D.log.warn("You can run it manually later."),!1}}async function Ci(e){if(!Ue("pnpm"))return!1;let t=D.spinner();t.start("Generating baseline database migration...");try{return await Me("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 D.log.warn(`Could not generate baseline migration: ${n}`),D.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function $i(e){try{return await xi(_r(e,".git")),D.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ue("git"))return D.log.warn("git not found. Skipping repository initialization."),!1;let t=D.spinner();t.start("Initializing git repository...");try{return await Me("git",["init"],e),await Me("git",["add","-A"],e),await Me("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),D.log.warn("You can run git init manually later."),!1}}async function Li(e){if(!Ue("pnpm"))return!1;try{await xi(_r(e,".git"))}catch{return!1}try{let t=JSON.parse(await _c(_r(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 Me("pnpm",["exec","simple-git-hooks"],e),!0}catch{return D.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Fe from"@clack/prompts";import z from"picocolors";function ji(e,t){let r=qe(e);t.dockerAvailable||Fe.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Fe.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 - deploying without it crash-loops the container.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${z.dim(`# ${r.map(a=>Vr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${z.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(z.dim("Fill in remaining TODO values in .env"))),Fe.note(n.join(`
1454
+ `),z.yellow("Start Development"));let i=[];i.push(`App ${z.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${z.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${z.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${z.cyan("http://localhost:8288")}`),Fe.note(i.join(`
1455
+ `),z.yellow("Dev Tools"));let s=[],o=Oc(e);o.length>0&&s.push(`Set in production: ${z.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(xc(e)),Fe.note(s.join(`
1456
+ `),z.yellow("Deployment"))}function Oc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];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 xc(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 ot(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 Ve(e,t){let r=ot(e),n=ot(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 Xt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Mi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ot(e)===null}function Zt(e,t,r="3.2.0"){if(Mi(r))return{ok:!0};let n=Xt(e,e.latest);return!n||ot(n)===null?{ok:!0}:Ve(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 Ui(e,t,r="3.2.0"){if(Mi(r))return{ok:!0};let n=Xt(e,t);return!n||ot(n)===null?{ok:!0}:Ve(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 jc from"picocolors";var Mc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Uc(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 Fi(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 re("--architecture <type>","fullstack or separate").choices([...ze])).addOption(new re("--payment <provider>","payment provider").choices([...Je])).addOption(new re("--email <provider>","email provider").choices([...Xe])).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("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").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 app is the AI product. Requires --desktop and --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 re("--currency <code>","default currency for billing").choices([...oe])).addOption(new re("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([..._e])).addOption(new re("--deploy <target>","deployment target").choices([...se])).addOption(new re("--database <provider>","database provider").choices([...ae])).addOption(new re("--cache <provider>","cache provider").choices([...ce])).option("--observability <providers>",`comma-separated observability providers (${B.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 re("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new re("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Fc(t?{...r,apiKey:t}:r)})}async function Fc(e){let t=performance.now();Ur("3.2.0");let r;try{r=zr(e)}catch(v){b.cancel(x(v)),process.exit(1)}let n=b.spinner(),i;try{i=await Qe({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(x(v)),process.exit(1)}e.demo&&Ar(i)!==Mc&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=pe(i),o,a=async()=>{o=await we(s);let v=Zt(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,runnerAllowed:o.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,f,k=!0,y=!0;try{({latestVersion:p,selectedVersion:f,desktopAllowed:k,runnerAllowed:y}=await a()),n.stop("Access verified."),xe(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await ut(),s=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:f,desktopAllowed:k,runnerAllowed:y}=await a()),n.stop("Access verified."),xe(i)}catch($){n.stop("Access verification failed."),b.cancel($ instanceof j&&$.status===401?"Invalid API key.":x($)),process.exit(1)}}else b.cancel(x(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!k&&(b.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&&(b.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let w;e.yes?w=Jr({...r,...k?{}:{desktop:!1},...y?{}:{runner:!1}}):w=await Xr(r,{desktopAllowed:k,runnerAllowed:y});let A;n.start("Activating license...");try{let v=e.demo&&w.baseUrl?await Uc(w.baseUrl):crypto.randomUUID(),$=()=>({frontend:ar,version:f,installId:v,projectName:w.projectName,options:on(w)}),G;try{G=await cr(s,$())}catch(L){let V=Dt(L);if(!V?.lastAllowedVersion||!o)throw L;n.stop("License activation failed.");let Z=Ui(o,V.lastAllowedVersion);if(Z.ok||(b.cancel(`${V.message} ${Z.message}`),process.exit(1)),e.yes){let he=Xt(o,V.lastAllowedVersion);b.cancel(`${V.message} Re-run ${he?`npx generatesaas@${he} init`:"init"} without --yes to continue with v${V.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let U=await b.confirm({message:`Your update window has ended. Continue with v${V.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(U)||!U)&&(b.cancel("Setup cancelled."),process.exit(0)),f=V.lastAllowedVersion,n.start(`Activating license for v${f}...`),G=await cr(s,$())}A={token:G.token,keyHash:Ar(i),installId:G.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(x(v)),process.exit(1)}let h=Lc(w.projectDir);if(Dc(h)&&Nc(h).length>0)if(e.yes)b.log.info(`Directory ${h} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let $=await b.select({message:`Directory ${h} 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"}]});(b.isCancel($)||$==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),$==="overwrite"&&Cc(h,{recursive:!0,force:!0})}let C={...w,projectDir:h,version:f,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Nt(s,f,h),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(x(v)),process.exit(1)}n.start("Generating project files...");try{if(await zt(C),!e.demo){let v=await it(h);await l($c(h,Ot),JSON.stringify(v,null," ")+`
1457
+ `),await Ii(h,h)}await Oi(h),await Ai(C,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(x(v)),process.exit(1)}!await Di(h)&&C.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let me=await Ni(h),X=C.demo!==!0&&e.dbMigration!==!1,fe=!1;X&&me&&(await Ci(h),fe=!0),await $i(h),me&&await Li(h);let Se=Ue("docker"),Ae=ir(C).map(v=>v.key).filter(v=>!C.credentials?.[v]);ji(C,{pnpmInstalled:me,dockerAvailable:Se,skippedCredentials:Ae,baselineMigrationMissing:X&&!fe}),Fr(),b.log.info(jc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Nr}from"fs";import{readFile as zi}from"fs/promises";import{join as st,resolve as qc}from"path";import*as g from"@clack/prompts";import N from"picocolors";import{mkdtemp as Vc,rm as Bc}from"fs/promises";import{tmpdir as Kc}from"os";import{join as Gc}from"path";async function Or(e,t,r,n){let i=await Vc(Gc(Kc(),"generatesaas-stage-"));try{await Nt(e,t,i),await zt({...r,projectDir:i}),await Pr(i,n)}finally{await Bc(i,{recursive:!0,force:!0})}}function kt(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var xr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:ze,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:se,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:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Je,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,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:B,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:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",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/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{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 desktop-first shape: the desktop 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 the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop 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.runner!==!0,requiresLabel:"requires AI features and the desktop 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&&ne({...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=>kt(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 Hc(e,t){return e[t]!==void 0}function Vi(e){return xr.filter(t=>t.adoptable&&!Hc(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 Yc(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 Wc(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 Bi(e){let t=[];for(let r of xr){let n=e[r.key];n!==void 0&&(Yc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Wc(r)}.`))}return t}function Ki(e){let t={};for(let r of xr)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 Gi(e){return e?"ON":"OFF"}var Et="packages/config/src/index.ts";function Hi(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 Yi(e){return[...qe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Dr=[{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 ${Et} 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 ${Et} 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 ${Et}. 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===kt(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Gi(e.aiBuiltin)}, but it is now a plain config value generated ${Gi(kt(e))} for a project ${kt(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${Et} 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 ${Et} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Hi(e).join(",")===Yi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Hi(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 ${Yi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Kr.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 (${je.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.`}],rf=Dr.map(e=>e.key);function Wi(e){for(let t of Dr)t.normalize?.(e)}function qi(e){let t=[];for(let r of Dr){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 Ji(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=qc(r.cwd??process.cwd()),s=st(i,ye),o;try{o=JSON.parse(await zi(s,"utf-8"))}catch{g.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===or&&(g.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${or}"\`).
1455
1458
 
1456
1459
  v${sr} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1457
1460
 
1458
- Your project keeps working exactly as it is - stay on v${sr}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Bi(s);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1461
+ Your project keeps working exactly as it is - stay on v${sr}, or start a fresh project on Next.js with ${N.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Bi(o);a.length>0&&(g.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1459
1462
 
1460
- ${a.map(f=>` - ${f}`).join(`
1463
+ ${a.map(h=>` - ${h}`).join(`
1461
1464
  `)}
1462
1465
 
1463
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),Wi(s);let p=ie(s);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
1466
+ Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1)),Wi(o);let p=ne(o);p&&(g.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
1464
1467
 
1465
1468
  ${p.reason}
1466
1469
 
1467
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let m=tr(s);m.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1470
+ Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let f=rr(o);f.length>0&&(g.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1468
1471
 
1469
- ${m.map(f=>` - ${f}`).join(`
1472
+ ${f.map(h=>` - ${h}`).join(`
1470
1473
  `)}
1471
1474
 
1472
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let w=Wr(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:
1475
+ Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let k=Wr(o);k.length>0&&(g.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1473
1476
 
1474
- ${w.map(f=>` - ${f}`).join(`
1477
+ ${k.map(h=>` - ${h}`).join(`
1475
1478
  `)}
1476
1479
 
1477
- Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await Ze()}catch(f){y.cancel(D(f)),process.exit(1)}let k=de(g),A=y.spinner();try{A.start("Verifying access...");let f;try{f=await ke(k)}catch(R){throw R instanceof j&&R.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):R}let $=Xt(f,"update");if(!$.ok)throw new Error($.message);A.stop("Access verified."),De(g),A.start("Fetching latest skill files...");let J=await nn(k,f.latest);await Tr(i,J.skillMd,J.scripts);let fe=je;if(A.stop("Skills updated."),y.log.success(`Skill files installed to ${C.cyan(fe.length.toString())} locations.`),s.version===f.latest){y.log.info(`Already on the latest version (${s.version}).`);return}let X=f.entitlements;X&&(s.desktop&&!X.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&&!X.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)));let he=JSON.stringify(s);Yr(s),await Jc(s,qr(s),n),await Zc(qi(s),n);let Ee=Vi(s),Se=Ki(s),Re=tr(Se);Re.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1480
+ Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let y;try{y=await Qe()}catch(h){g.cancel(x(h)),process.exit(1)}let w=pe(y),A=g.spinner();try{A.start("Verifying access...");let h;try{h=await we(w)}catch(P){throw P instanceof j&&P.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):P}let C=Zt(h,"update");if(!C.ok)throw new Error(C.message);A.stop("Access verified."),xe(y),A.start("Fetching latest skill files...");let F=await nn(w,h.latest);await Tr(i,F.skillMd,F.scripts);let me=je;if(A.stop("Skills updated."),g.log.success(`Skill files installed to ${N.cyan(me.length.toString())} locations.`),o.version===h.latest){g.log.info(`Already on the latest version (${o.version}).`);return}let X=h.entitlements;X&&(o.desktop&&!X.desktopAllowed&&(g.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),o.runner&&!X.runnerAllowed&&(g.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)));let fe=JSON.stringify(o);Yr(o),await zc(o,qr(o),n),await Xc(qi(o),n);let Se=Vi(o),Re=Ki(o),Ae=rr(Re);Ae.length>0&&(g.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1478
1481
 
1479
- ${Re.map(R=>` - ${R}`).join(`
1482
+ ${Ae.map(P=>` - ${P}`).join(`
1480
1483
  `)}
1481
1484
 
1482
- 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(Se)!==he;if(s=Se,s.licenseToken)try{let R=await on(k,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=R.token,R.licenseKeyHash&&(s.licenseKeyHash=R.licenseKeyHash),await l(o,JSON.stringify(s,null," ")+`
1483
- `),v=!1,y.log.success("License refreshed.")}catch(R){let Ae=Dt(R);Ae&&(y.cancel(Ae.message),process.exit(1)),y.log.warn("License refresh skipped.")}v&&await l(o,JSON.stringify(s,null," ")+`
1484
- `);let x=Ri(s,i),L=st(i,en);A.start(`Staging v${f.latest} (shaped for your config)...`),await Or(k,f.latest,x,L),A.stop("Template staged.");let{text:ge,title:U}=await tl(k,f,s.version);ge&&y.note(ge,U);let F=st(i,Ot),V=st(i,xt),Pe=!Nr(V),Ge=!Nr(F);if(Pe){if(A.start("Building baseline template (one-time migration)..."),await Or(k,s.version,x,V),Ge){let R=await nt(V);await l(F,JSON.stringify(R,null," ")+`
1485
- `)}if(A.stop("Baseline template stored."),!Ge){let R=await rl(F,V);R>0&&y.log.warn(`Rebuilt baseline differs from the original for ${R} 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(Ge){A.start("Computing baseline template hashes...");let R=await nt(V);await l(F,JSON.stringify(R,null," ")+`
1486
- `),A.stop("Baseline hashes computed.")}await l(st(i,tn),JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:ge,stagedAt:new Date().toISOString(),...Ee.length>0?{newOptions:Ee}:{},...n?{mode:n}:{}},null," ")+`
1487
- `),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&&Nr(st(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${C.cyan("apps/electron")}). 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")}.`)}catch(f){A.stop("Failed."),y.cancel(`Update failed: ${D(f)}`),process.exit(1)}})}async function Jc(e,t,r){if(t.kind==="none")return;let n=el[t.kind];r==="auto"&&(y.cancel(`${n.message}
1485
+ Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let v=JSON.stringify(Re)!==fe;if(o=Re,o.licenseToken)try{let P=await sn(w,{currentToken:o.licenseToken,newVersion:h.latest});o.licenseToken=P.token,P.licenseKeyHash&&(o.licenseKeyHash=P.licenseKeyHash),await l(s,JSON.stringify(o,null," ")+`
1486
+ `),v=!1,g.log.success("License refreshed.")}catch(P){let He=Dt(P);He&&(g.cancel(He.message),process.exit(1)),g.log.warn("License refresh skipped.")}v&&await l(s,JSON.stringify(o,null," ")+`
1487
+ `);let $=Ri(o,i),G=st(i,en);A.start(`Staging v${h.latest} (shaped for your config)...`),await Or(w,h.latest,$,G),A.stop("Template staged.");let{text:L,title:V}=await el(w,h,o.version);L&&g.note(L,V);let Z=st(i,Ot),U=st(i,xt),he=!Nr(U),Ge=!Nr(Z);if(he){if(A.start("Building baseline template (one-time migration)..."),await Or(w,o.version,$,U),Ge){let P=await it(U);await l(Z,JSON.stringify(P,null," ")+`
1488
+ `)}if(A.stop("Baseline template stored."),!Ge){let P=await tl(Z,U);P>0&&g.log.warn(`Rebuilt baseline differs from the original for ${P} 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(Ge){A.start("Computing baseline template hashes...");let P=await it(U);await l(Z,JSON.stringify(P,null," ")+`
1489
+ `),A.stop("Baseline hashes computed.")}await l(st(i,tn),JSON.stringify({currentVersion:o.version,targetVersion:h.latest,changelog:L,stagedAt:new Date().toISOString(),...Se.length>0?{newOptions:Se}:{},...n?{mode:n}:{}},null," ")+`
1490
+ `),g.log.info(`Update staged: ${N.cyan(o.version)} \u2192 ${N.cyan(h.latest)}`),g.log.info(`Ask your AI coding assistant to ${N.cyan("'update my GenerateSaaS project'")}.`),o.desktop===!0&&Nr(st(i,"apps/tauri"))&&g.log.warn(`Desktop: the app moved to an Electron shell (${N.cyan("apps/electron")}). Your project still has the old Tauri shell (${N.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${N.cyan("/desktop/updates")}.`)}catch(h){A.stop("Failed."),g.cancel(`Update failed: ${x(h)}`),process.exit(1)}})}async function zc(e,t,r){if(t.kind==="none")return;let n=Qc[t.kind];r==="auto"&&(g.cancel(`${n.message}
1488
1491
 
1489
- This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var Xc={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 Zc(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Xc[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){t==="auto"&&(y.cancel(`${n.message}
1492
+ This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let i=await g.select({message:n.message,options:n.options});g.isCancel(i)&&(g.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var Jc={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 Xc(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?Jc[n.key]:void 0;if(!i){g.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(g.cancel(`${n.message}
1490
1493
 
1491
- This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let o=await y.select({message:n.message,options:i});(y.isCancel(o)||o==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function Qc(e){e.desktop=!1}var el={"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?",options:[{value:{apply:e=>{e.ai=!0}},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"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"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?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:Qc},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function tl(e,t,r){let n=t.latest,i=t.versions.filter(p=>Ve(p.version,r)>0&&Ve(p.version,n)<=0).sort((p,m)=>Ve(p.version,m.version)),o=async p=>{try{return await rn(e,p)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(p=>o(p.version)));return{text:i.map((p,m)=>{let w=p.date?` (${p.date.slice(0,10)})`:"",g=p.breaking?" [BREAKING]":"",k=s[m]??"_No changelog available for this release._";return`# v${p.version}${w}${g}
1494
+ This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let s=await g.select({message:n.message,options:i});(g.isCancel(s)||s==="stop")&&(g.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function Zc(e){e.desktop=!1}var Qc={"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?",options:[{value:{apply:e=>{e.ai=!0}},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"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"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?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:Zc},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function el(e,t,r){let n=t.latest,i=t.versions.filter(p=>Ve(p.version,r)>0&&Ve(p.version,n)<=0).sort((p,f)=>Ve(p.version,f.version)),s=async p=>{try{return await rn(e,p)}catch{return null}};if(i.length<=1)return{text:await s(n),title:`Changelog v${n}`};let o=await Promise.all(i.map(p=>s(p.version)));return{text:i.map((p,f)=>{let k=p.date?` (${p.date.slice(0,10)})`:"",y=p.breaking?" [BREAKING]":"",w=o[f]??"_No changelog available for this release._";return`# v${p.version}${k}${y}
1492
1495
 
1493
- ${k}`}).join(`
1496
+ ${w}`}).join(`
1494
1497
 
1495
- `),title:`Changelog v${r} \u2192 v${n}`}}async function rl(e,t){let r=JSON.parse(await zi(e,"utf-8")),n=await nt(t),i=0;for(let[o,s]of Object.entries(r))Qe(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as K from"@clack/prompts";import me from"picocolors";import{readFile as nl}from"fs/promises";import{join as il,resolve as sl}from"path";function Xi(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=sl(t.cwd??process.cwd()),n=il(r,ve),i;try{i=JSON.parse(await nl(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${me.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${me.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${me.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${me.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1496
- `);K.note(o,me.bold("Project Status"));let s=K.spinner();s.start("Checking for updates...");try{let a=await Ze(),p=de(a),w=(await ke(p)).latest;i.version===w?(s.stop("Up to date."),K.log.success(`Already on the latest version (${me.green(w)})`)):(s.stop("Update available."),K.log.warning(`Update available: ${me.yellow(i.version)} \u2192 ${me.green(w)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${me.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof j&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as ol}from"fs/promises";import*as O from"@clack/prompts";import _ from"picocolors";function al(){return process.env.GENERATESAAS_API_KEY??pt()}function cl(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 ll(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function pl(e){switch(e.verdict){case"licensed":return O.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return O.log.success(`${_.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 O.log.error(`${_.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 O.log.error(`${_.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${_.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return O.log.error(`${_.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return O.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Zi(e,t){let r=process.env.GENERATESAAS_API_URL??lt,n=al();e.start("Cross-referencing license records...");try{let i=n?cl(await an(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):ll(await cr(r,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),pl(i)}catch(i){return e.stop(`${_.yellow("Skipped")} - ${D(i)}`),null}}function dl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Cr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Qi(e){O.note([`License ID: ${_.cyan(String(e.lid??"unknown"))}`,`Version: ${_.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Cr(e.pat)}`,`Last updated: ${Cr(e.uat)}`,`Expires: ${Cr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1497
- `),_.yellow("License Details"))}function ul(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 es(e){let t=O.spinner(),r=null,n="no candidates";for(let s of ul(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${D(a)}`,t.stop(`${_.yellow("Unreachable")} - ${n}`)}}if(r===null){O.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=ts(e);return s?await Zi(t,{domain:s})??!1:!1}let i;try{i=dl(r)}catch{return O.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??lt,a=await cr(s,{token:r});if(a.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),O.log.warn("Signature not verified. Displaying unverified claims:"),Qi(i),!1}return Qi(i),await Zi(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:ts(e)})??!0}function ts(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function rs(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&&(O.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await ol(r.file,"utf-8")).split(`
1498
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(O.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await es(s)&&o++,O.log.info("");O.log.success(`${o}/${i.length} sites verified.`)}else await es(t)||process.exit(1)})}import{existsSync as ml,rmSync as fl}from"fs";import*as z from"@clack/prompts";function ns(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){ml(pe)?(fl(pe),z.log.success("API key removed.")):z.log.info("No API key configured.");return}let r=pt();r?z.log.info(`Current API key: ****${r.slice(-4)}`):z.log.info("No API key configured.");let n=await dt(),i=de(n),o=z.spinner();o.start("Verifying API key...");try{await ke(i),o.stop("API key verified."),De(n),z.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof j&&s.status===401?z.cancel("Invalid API key."):z.cancel(D(s)),process.exit(1)}})}import{existsSync as Zt,rmSync as hl,readFileSync as Lr,writeFileSync as is}from"fs";import{join as Be}from"path";import*as M from"@clack/prompts";var gl=["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"],yl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1498
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function tl(e,t){let r=JSON.parse(await zi(e,"utf-8")),n=await it(t),i=0;for(let[s,o]of Object.entries(r))et(s)||n[s]!==o&&i++;for(let s of Object.keys(n))s in r||i++;return i}import*as K from"@clack/prompts";import ue from"picocolors";import{readFile as rl}from"fs/promises";import{join as nl,resolve as il}from"path";function Xi(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=il(t.cwd??process.cwd()),n=nl(r,ye),i;try{i=JSON.parse(await rl(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s=[`Version: ${ue.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${ue.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${ue.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${ue.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1499
+ `);K.note(s,ue.bold("Project Status"));let o=K.spinner();o.start("Checking for updates...");try{let a=await Qe(),p=pe(a),k=(await we(p)).latest;i.version===k?(o.stop("Up to date."),K.log.success(`Already on the latest version (${ue.green(k)})`)):(o.stop("Update available."),K.log.warning(`Update available: ${ue.yellow(i.version)} \u2192 ${ue.green(k)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${ue.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){o.stop("Check failed."),a instanceof j&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${x(a)}`)}})}import{readFile as ol}from"fs/promises";import*as O from"@clack/prompts";import _ from"picocolors";function sl(){return process.env.GENERATESAAS_API_KEY??dt()}function al(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 cl(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function ll(e){switch(e.verdict){case"licensed":return O.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return O.log.success(`${_.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 O.log.error(`${_.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 O.log.error(`${_.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${_.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return O.log.error(`${_.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return O.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function Zi(e,t){let r=process.env.GENERATESAAS_API_URL??pt,n=sl();e.start("Cross-referencing license records...");try{let i=n?al(await an(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):cl(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),ll(i)}catch(i){return e.stop(`${_.yellow("Skipped")} - ${x(i)}`),null}}function pl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Cr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Qi(e){O.note([`License ID: ${_.cyan(String(e.lid??"unknown"))}`,`Version: ${_.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Cr(e.pat)}`,`Last updated: ${Cr(e.uat)}`,`Expires: ${Cr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1500
+ `),_.yellow("License Details"))}function dl(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 eo(e){let t=O.spinner(),r=null,n="no candidates";for(let o of dl(e)){t.start(`Checking ${o}...`);try{let a=await fetch(o);if(!a.ok){n=`${o} returned ${a.status}`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${o} did not return a JWT`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(a){n=`${o}: ${x(a)}`,t.stop(`${_.yellow("Unreachable")} - ${n}`)}}if(r===null){O.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let o=to(e);return o?await Zi(t,{domain:o})??!1:!1}let i;try{i=pl(r)}catch{return O.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??pt,a=await lr(o,{token:r});if(a.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),O.log.warn("Signature not verified. Displaying unverified claims:"),Qi(i),!1}return Qi(i),await Zi(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:to(e)})??!0}function to(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ro(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&&(O.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await ol(r.file,"utf-8")).split(`
1501
+ `).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#"));i.length===0&&(O.cancel("No URLs found in file."),process.exit(1));let s=0;for(let o of i)await eo(o)&&s++,O.log.info("");O.log.success(`${s}/${i.length} sites verified.`)}else await eo(t)||process.exit(1)})}import{existsSync as ul,rmSync as ml}from"fs";import*as J from"@clack/prompts";function no(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){ul(le)?(ml(le),J.log.success("API key removed.")):J.log.info("No API key configured.");return}let r=dt();r?J.log.info(`Current API key: ****${r.slice(-4)}`):J.log.info("No API key configured.");let n=await ut(),i=pe(n),s=J.spinner();s.start("Verifying API key...");try{await we(i),s.stop("API key verified."),xe(n),J.log.success("API key saved.")}catch(o){s.stop("Verification failed."),o instanceof j&&o.status===401?J.cancel("Invalid API key."):J.cancel(x(o)),process.exit(1)}})}import{existsSync as Qt,rmSync as fl,readFileSync as Lr,writeFileSync as io}from"fs";import{join as Be}from"path";import*as M from"@clack/prompts";var hl=["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"],gl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1499
1502
  `,` licenseHeartbeatFunction,
1500
1503
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1501
1504
  `,` .route("/license", licenseRoutes)
1502
1505
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1503
- `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function vl(){return je.map(e=>Be(e,Ir))}function $r(e){return Zt(e)?(hl(e,{recursive:!0}),!0):!1}function bl(e,t,r=[]){if(!Zt(e))return!1;let n=Lr(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:(is(e,i,"utf-8"),!0)}function wl(e){let t=Be(e,".gitignore");if(!Zt(t))return!1;let r=Lr(t,"utf-8"),n=r.split(`
1506
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function yl(){return je.map(e=>Be(e,Ir))}function $r(e){return Qt(e)?(fl(e,{recursive:!0}),!0):!1}function vl(e,t,r=[]){if(!Qt(e))return!1;let n=Lr(e,"utf-8"),i=n;for(let s of t)i=i.replace(s,"");for(let{from:s,to:o}of r)i=i.replace(s,o);return i===n?!1:(io(e,i,"utf-8"),!0)}function bl(e){let t=Be(e,".gitignore");if(!Qt(t))return!1;let r=Lr(t,"utf-8"),n=r.split(`
1504
1507
  `).filter(i=>!i.includes(".generatesaas")).join(`
1505
- `);return n===r?!1:(is(t,n,"utf-8"),!0)}function ss(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Be(t,ve),n;try{n=JSON.parse(Lr(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.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(M.isCancel(i)&&(M.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)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of vl())$r(Be(t,a))&&o.push(a);for(let a of gl)$r(Be(t,a))&&o.push(a);$r(Be(t,H))&&o.push(H+"/");for(let a of yl){let p=Be(t,a.file);bl(p,a.removals,a.replacements)?s.push(a.file):Zt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}wl(t)&&s.push(".gitignore");for(let a of o)M.log.info(`Deleted ${a}`);for(let a of s)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Ke=new kl().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.1.1").addHelpText("after",`
1508
+ `);return n===r?!1:(io(t,n,"utf-8"),!0)}function oo(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Be(t,ye),n;try{n=JSON.parse(Lr(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.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(M.isCancel(i)&&(M.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)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of yl())$r(Be(t,a))&&s.push(a);for(let a of hl)$r(Be(t,a))&&s.push(a);$r(Be(t,Y))&&s.push(Y+"/");for(let a of gl){let p=Be(t,a.file);vl(p,a.removals,a.replacements)?o.push(a.file):Qt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}bl(t)&&o.push(".gitignore");for(let a of s)M.log.info(`Deleted ${a}`);for(let a of o)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Ke=new wl().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.2.0").addHelpText("after",`
1506
1509
  Examples:
1507
1510
  $ generatesaas init Interactive setup
1508
1511
  $ generatesaas init -n my-app -y Quick setup with defaults
1509
1512
  $ generatesaas status Check for updates
1510
1513
  $ generatesaas auth Set or update API key
1511
- `);Fi(Ke);Ji(Ke);Xi(Ke);rs(Ke);ns(Ke);ss(Ke);Ke.parseAsync().catch(e=>{os.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1514
+ `);Fi(Ke);Ji(Ke);Xi(Ke);ro(Ke);no(Ke);oo(Ke);Ke.parseAsync().catch(e=>{so.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});