generatesaas 3.4.5 → 3.5.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
@@ -5,7 +5,7 @@ import{Command as Ml}from"commander";import*as hs from"@clack/prompts";import{ex
5
5
  `),_=[M!=="none"?` Payment: ${h.cyan(Rt[M].label)} (${fe})`:` Payment: ${h.dim("none")}`,` Credits: ${Ye?h.cyan("Yes"):h.dim("No")}`,` AI features: ${$?h.cyan("Yes"):h.dim("No")}`,...$?[` Runner: ${V?h.cyan("Yes"):h.dim("No")}`]:[],...B?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(It[Z].label)}`,` Observability: ${he.length===0?h.dim("none"):h.cyan(he.map(er=>Tt[er].label).join(", "))}`,` Multi-tenancy: ${Se?h.cyan("Yes"):h.dim("No")}`,` Projects: ${Ae?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${Pe?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${D?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${Re?h.cyan("Yes"):h.dim("No")}`].join(`
6
6
  `),ye=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),_];if(Ie.length>0){let er=Ie.map(Br=>{let gs=lt[Br.key]?h.green("provided"):h.dim("skipped");return` ${Br.key}: ${gs}`}).join(`
7
7
  `);ye.push("",h.bold("Credentials"),er)}m.note(ye.join(`
8
- `),"Summary");let Vr=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Vr)||!Vr)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:P,deploymentTarget:a,databaseProvider:f,cacheProvider:L,paymentProvider:M,emailProvider:Z,observability:he,multiTenancy:Se,projects:Ae,docs:Pe,desktop:D,ai:$,webAi:B,runner:V,revenueSharing:Re,credits:Ye,defaultCurrency:fe,...Object.keys(lt).length>0?{credentials:lt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...I!==void 0?{demo:I}:{}}}import{createReadStream as mn,existsSync as Ts}from"fs";import{mkdir as _s}from"fs/promises";import{join as Os}from"path";import{Readable as xs}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ds}from"tar";import{join as De}from"path";import{homedir as ws}from"os";var ut=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",ve=De(z,"manifest.json"),rn="nextjs",sr="nuxt",or="2.4.1",nn=De(z,"hashes.json"),xt=De(z,"template-hashes.json"),Dt=De(z,"template"),sn=De(z,"staging"),on=De(z,"staging.json"),le=De(ws(),".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:ut}}async function we(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.4.5"}});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 bs,readFileSync as ks,writeFileSync as Es,mkdirSync as Ss}from"fs";import{dirname as As}from"path";import*as be from"@clack/prompts";function mt(){if(!bs(le))return null;try{let e=JSON.parse(ks(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 Ne(e){Ss(As(le),{recursive:!0}),Es(le,JSON.stringify({apiKey:e},null," ")+`
8
+ `),"Summary");let Vr=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Vr)||!Vr)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:P,deploymentTarget:a,databaseProvider:f,cacheProvider:L,paymentProvider:M,emailProvider:Z,observability:he,multiTenancy:Se,projects:Ae,docs:Pe,desktop:D,ai:$,webAi:B,runner:V,revenueSharing:Re,credits:Ye,defaultCurrency:fe,...Object.keys(lt).length>0?{credentials:lt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...I!==void 0?{demo:I}:{}}}import{createReadStream as mn,existsSync as Ts}from"fs";import{mkdir as _s}from"fs/promises";import{join as Os}from"path";import{Readable as xs}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ds}from"tar";import{join as De}from"path";import{homedir as ws}from"os";var ut=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",ve=De(z,"manifest.json"),rn="nextjs",sr="nuxt",or="2.4.1",nn=De(z,"hashes.json"),xt=De(z,"template-hashes.json"),Dt=De(z,"template"),sn=De(z,"staging"),on=De(z,"staging.json"),le=De(ws(),".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:ut}}async function we(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.5.0"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as bs,readFileSync as ks,writeFileSync as Es,mkdirSync as Ss}from"fs";import{dirname as As}from"path";import*as be from"@clack/prompts";function mt(){if(!bs(le))return null;try{let e=JSON.parse(ks(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 Ne(e){Ss(As(le),{recursive:!0}),Es(le,JSON.stringify({apiKey:e},null," ")+`
9
9
  `,{mode:384})}async function et(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=mt();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 ft()}async function ft(){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 Ps}from"fs/promises";async function ke(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ps(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 we(e,"/versions")).json()}async function an(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await we(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function cn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skills:{"generatesaas-update":{skillMd:`# Offline skill stub
10
10
  `,scripts:{},references:{}}}}:await(await we(e,`/skills/${encodeURIComponent(t)}`)).json()}function Nt(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var ar="nextjs";function ln(e){return{frontend:ar,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,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 we(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await we(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 dn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),dr=new Set(["pnpm-lock.yaml"]);function tt(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var Rs=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),un=["scripts/docs-lint.ts"],Is=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","packages/database/tests/no-migration-history.test.ts","apps/web/tests/content/competitor-claims.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(un.includes(e)||un.some(r=>r.startsWith(e+"/")))return!1;if(Rs.has(t[0]))return!0;for(let r of Is)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Ct(e,t,r){await _s(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Os(n,`v${t}.tar.gz`);if(!Ts(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(mn(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(mn(i),fr(r));return}let o=await we(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=xs.fromWeb(o.body);await mr(s,fr(r))}function fr(e){return Ds({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as Lt,readFile as rt,rm as hn,rmdir as Ns,writeFile as ht}from"fs/promises";import{join as G}from"path";async function gn(e){let t;try{t=await Lt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=G(e,n.name);if(n.isDirectory()){await gn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await hn(i,{force:!0})}return r||await Ns(e).catch(()=>{}),r}async function yn(e){let t=G(e,"packages/content"),r=[];try{r=(await Lt(t,{withFileTypes:!0})).filter(s=>s.isDirectory()).map(s=>s.name)}catch{return}let n=new Set;for(let s of r){let a=G(t,s),p;try{p=(await Lt(a,{withFileTypes:!0})).filter(u=>u.isDirectory())}catch{continue}for(let u of p)n.add(u.name),await gn(G(a,u.name))}let i=await js(e),o=new Set([...n].filter(s=>i===void 0||i.has(s)));await Promise.all([...o].map(s=>hn(G(e,"apps/web/public/images",s),{recursive:!0,force:!0}))),await Ms(e,o)}var Cs="packages/config/src/index.ts",Ls=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,$s=/\bslug:\s*"([^"]+)"/g;async function js(e){let t;try{t=await rt(G(e,Cs),"utf-8")}catch{return}let r=Ls.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll($s)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var Us="packages/translate/.meta/mdx-translation-meta.json";async function Ms(e,t){if(t.size===0)return;let r=G(e,Us),n;try{n=JSON.parse(await rt(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let o=i.files,s={};for(let[a,p]of Object.entries(o)){let u=a.split("/"),v=u.length>1?u[0]:void 0,g=u[u.length-1]?.startsWith("_")===!0;v!==void 0&&t.has(v)&&!g||(s[a]=p)}await ht(r,JSON.stringify({...i,files:s},null," ")+`
11
11
  `)}var Fs="packages/config/src/blog.ts";async function vn(e){let t=G(e,Fs),r=await rt(t,"utf-8"),n=fn(fn(r,"blogCategories",t),"blogAuthors",t);await ht(t,n)}function fn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function wn(e){let t=G(e,"packages/i18n/translations"),r;try{r=await Lt(t)}catch{return}for(let n of r){let i=G(t,n,"web.json"),o;try{o=await rt(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.content?.categories||s.content.categories.blog===void 0||(s.content.categories.blog={},await ht(i,JSON.stringify(s,null," ")+`
@@ -637,7 +637,7 @@ ${g},
637
637
  items: []
638
638
  }
639
639
  };
640
- `;await l(t,w)}var Po={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"}]},Ro={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(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 wr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function On(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Io="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Tn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=On(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(Vt(_e[e.databaseProvider].envVars,r),o),o.push("","# Cache"),gt(Vt(Oe[e.cacheProvider].envVars,r),o),e.cacheProvider==="redis"&&o.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(o,"CONTENT_API_KEY",wr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(o,"INNGEST_EVENT_KEY",wr(32),t),Bt(o,"INNGEST_SIGNING_KEY",wr(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=Po[e.emailProvider];if(s&&(o.push("","# Email"),gt(Vt(s,r),o)),e.paymentProvider!=="none"){let p=Ro[e.paymentProvider];p&&(o.push("","# Payment"),gt(Vt(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 MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# EITHER key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with both keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper on each, at high quality; extract is slower","# on a page it has not already indexed. Note its customer terms include a license to","# train on submitted queries. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&o.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),o.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),o.push(""),o.join(`
640
+ `;await l(t,w)}var Po={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"}]},Ro={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(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 wr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function On(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Io="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Tn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=On(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(Vt(_e[e.databaseProvider].envVars,r),o),o.push("","# Cache"),gt(Vt(Oe[e.cacheProvider].envVars,r),o),e.cacheProvider==="redis"&&o.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(o,"CONTENT_API_KEY",wr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(o,"INNGEST_EVENT_KEY",wr(32),t),Bt(o,"INNGEST_SIGNING_KEY",wr(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=Po[e.emailProvider];if(s&&(o.push("","# Email"),gt(Vt(s,r),o)),e.paymentProvider!=="none"){let p=Ro[e.paymentProvider];p&&(o.push("","# Payment"),gt(Vt(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 MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# ANY one key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with several keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper on each, at high quality; extract is slower","# on a page it has not already indexed. Note its customer terms include a license to","# train on submitted queries. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY=","# TinyFish (optional) - both tools at a $0 list price, rate-limited instead (30 searches","# and 150 pages a minute per API key by default, shared by every user), so a call bills","# the user nothing unless you set a price in config.ai.webTools. Note its terms include","# a license to train on submitted content. Set config.ai.webTools.searchEngine or",'# .extractEngine to "tinyfish" to use it alongside another key.',"# https://agent.tinyfish.ai/","#TINYFISH_API_KEY="),e.desktop&&o.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),o.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),o.push(""),o.join(`
641
641
  `)}var _n="NEXT_PUBLIC_API_URL";function To(e){let{apiUrl:t}=On(e),r=["# API Configuration",`${_n}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${_n}=${Io}`),r.push(""),r.join(`
642
642
  `)}async function xn(e){let t=To(e);await l(`${e.projectDir}/.env`,t+`
643
643
  `+Tn(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
@@ -1406,7 +1406,7 @@ function posthogConfigured(): boolean {
1406
1406
  ${g}`:s.message))}else i()})})}async function Vi(e){if(!Fe("pnpm"))return C.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 C.log.warn(`Lockfile regeneration failed: ${r}`),C.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Bi(e){if(!Fe("pnpm"))return C.log.warn("pnpm not found. Skipping dependency installation."),C.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=C.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await 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 C.log.warn(`pnpm install failed: ${n}`),C.log.warn("You can run it manually later."),!1}}async function Ki(e){if(!Fe("pnpm"))return!1;let t=C.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 C.log.warn(`Could not generate baseline migration: ${n}`),C.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Gi(e){try{return await Fi(Cr(e,".git")),C.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Fe("git"))return C.log.warn("git not found. Skipping repository initialization."),!1;let t=C.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."),C.log.warn("You can run git init manually later."),!1}}async function Hi(e){if(!Fe("pnpm"))return!1;try{await Fi(Cr(e,".git"))}catch{return!1}try{let t=JSON.parse(await zc(Cr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Me("pnpm",["exec","simple-git-hooks"],e),!0}catch{return C.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Ve from"@clack/prompts";import J from"picocolors";function Yi(e,t){let r=qe(e);t.dockerAvailable||Ve.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Ve.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - otherwise your first deploy pushes the schema untracked.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${J.dim(`# ${r.map(a=>Hr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${J.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(J.dim("Fill in remaining TODO values in .env"))),Ve.note(n.join(`
1407
1407
  `),J.yellow("Start Development"));let i=[];i.push(`App ${J.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${J.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${J.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${J.cyan("http://localhost:8288")}`),Ve.note(i.join(`
1408
1408
  `),J.yellow("Dev Tools"));let o=[],s=qc(e);s.length>0&&o.push(`Set in production: ${J.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push(Jc(e)),Ve.note(o.join(`
1409
- `),J.yellow("Deployment"))}function qc(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 Jc(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 at(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 Be(e,t){let r=at(e),n=at(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 Wi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:at(e)===null}function Xt(e,t,r="3.4.5"){if(Wi(r))return{ok:!0};let n=Jt(e,e.latest);return!n||at(n)===null?{ok:!0}:Be(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 zi(e,t,r="3.4.5"){if(Wi(r))return{ok:!0};let n=Jt(e,t);return!n||at(n)===null?{ok:!0}:Be(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 rl from"picocolors";var nl="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function il(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 qi(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([...Je])).addOption(new re("--payment <provider>","payment provider").choices([...Xe])).addOption(new re("--email <provider>","email provider").choices([...Ze])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--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([...se])).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([...xe])).addOption(new re("--deploy <target>","deployment target").choices([...oe])).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 (${K.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new 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 sl(t?{...r,apiKey:t}:r)})}async function sl(e){let t=performance.now();Kr("3.4.5");let r;try{r=Qr(e)}catch(b){k.cancel(N(b)),process.exit(1)}let n=k.spinner(),i;try{i=await et({apiKey:e.apiKey,prompt:!e.yes})}catch(b){k.cancel(N(b)),process.exit(1)}e.demo&&Tr(i)!==nl&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=pe(i),s,a=async()=>{s=await ke(o);let b=Xt(s,"init");if(!b.ok)throw new Error(b.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,u,v=!0,g=!0;try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(b){if(n.stop("Access verification failed."),b instanceof j&&b.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),i=await ft(),o=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(D){n.stop("Access verification failed."),k.cancel(D instanceof j&&D.status===401?"Invalid API key.":N(D)),process.exit(1)}}else k.cancel(N(b)),process.exit(1)}k.log.success(`Latest version: ${p}`),r.desktop===!0&&!v&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(k.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=en({...r,...v?{}:{desktop:!1},...g?{}:{runner:!1}}):w=await tn(r,{desktopAllowed:v,runnerAllowed:g});let P;n.start("Activating license...");try{let b=e.demo&&w.baseUrl?await il(w.baseUrl):crypto.randomUUID(),D=()=>({frontend:ar,version:u,installId:b,projectName:w.projectName,options:ln(w)}),$;try{$=await cr(o,D())}catch(ge){let F=Nt(ge);if(!F?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let V=zi(s,F.lastAllowedVersion);if(V.ok||(k.cancel(`${F.message} ${V.message}`),process.exit(1)),e.yes){let Re=Jt(s,F.lastAllowedVersion);k.cancel(`${F.message} Re-run ${Re?`npx generatesaas@${Re} init`:"init"} without --yes to continue with v${F.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await k.confirm({message:`Your update window has ended. Continue with v${F.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(B)||!B)&&(k.cancel("Setup cancelled."),process.exit(0)),u=F.lastAllowedVersion,n.start(`Activating license for v${u}...`),$=await cr(o,D())}P={token:$.token,keyHash:Tr(i),installId:$.installId??b},n.stop("License activated.")}catch(b){n.stop("License activation failed."),k.cancel(N(b)),process.exit(1)}let f=tl(w.projectDir);if(Xc(f)&&Zc(f).length>0)if(e.yes)k.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let D=await k.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(k.isCancel(D)||D==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),D==="overwrite"&&Qc(f,{recursive:!0,force:!0})}let L={...w,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(o,u,f),n.stop("Template downloaded.")}catch(b){n.stop("Download failed."),k.cancel(N(b)),process.exit(1)}n.start("Generating project files...");try{if(await zt(L),!e.demo){let b=await ot(f);await l(el(f,xt),JSON.stringify(b,null," ")+`
1409
+ `),J.yellow("Deployment"))}function qc(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 Jc(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 at(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 Be(e,t){let r=at(e),n=at(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 Wi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:at(e)===null}function Xt(e,t,r="3.5.0"){if(Wi(r))return{ok:!0};let n=Jt(e,e.latest);return!n||at(n)===null?{ok:!0}:Be(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 zi(e,t,r="3.5.0"){if(Wi(r))return{ok:!0};let n=Jt(e,t);return!n||at(n)===null?{ok:!0}:Be(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 rl from"picocolors";var nl="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function il(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 qi(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([...Je])).addOption(new re("--payment <provider>","payment provider").choices([...Xe])).addOption(new re("--email <provider>","email provider").choices([...Ze])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/desktop, built with Electron)").option("--no-desktop","exclude the desktop app").option("--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([...se])).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([...xe])).addOption(new re("--deploy <target>","deployment target").choices([...oe])).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 (${K.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new 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 sl(t?{...r,apiKey:t}:r)})}async function sl(e){let t=performance.now();Kr("3.5.0");let r;try{r=Qr(e)}catch(b){k.cancel(N(b)),process.exit(1)}let n=k.spinner(),i;try{i=await et({apiKey:e.apiKey,prompt:!e.yes})}catch(b){k.cancel(N(b)),process.exit(1)}e.demo&&Tr(i)!==nl&&(k.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=pe(i),s,a=async()=>{s=await ke(o);let b=Xt(s,"init");if(!b.ok)throw new Error(b.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,u,v=!0,g=!0;try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(b){if(n.stop("Access verification failed."),b instanceof j&&b.status===401){e.yes&&(k.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),k.log.warning("Invalid API key."),i=await ft(),o=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:u,desktopAllowed:v,runnerAllowed:g}=await a()),n.stop("Access verified."),Ne(i)}catch(D){n.stop("Access verification failed."),k.cancel(D instanceof j&&D.status===401?"Invalid API key.":N(D)),process.exit(1)}}else k.cancel(N(b)),process.exit(1)}k.log.success(`Latest version: ${p}`),r.desktop===!0&&!v&&(k.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(k.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=en({...r,...v?{}:{desktop:!1},...g?{}:{runner:!1}}):w=await tn(r,{desktopAllowed:v,runnerAllowed:g});let P;n.start("Activating license...");try{let b=e.demo&&w.baseUrl?await il(w.baseUrl):crypto.randomUUID(),D=()=>({frontend:ar,version:u,installId:b,projectName:w.projectName,options:ln(w)}),$;try{$=await cr(o,D())}catch(ge){let F=Nt(ge);if(!F?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let V=zi(s,F.lastAllowedVersion);if(V.ok||(k.cancel(`${F.message} ${V.message}`),process.exit(1)),e.yes){let Re=Jt(s,F.lastAllowedVersion);k.cancel(`${F.message} Re-run ${Re?`npx generatesaas@${Re} init`:"init"} without --yes to continue with v${F.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await k.confirm({message:`Your update window has ended. Continue with v${F.lastAllowedVersion} (the last version your license covers)?`});(k.isCancel(B)||!B)&&(k.cancel("Setup cancelled."),process.exit(0)),u=F.lastAllowedVersion,n.start(`Activating license for v${u}...`),$=await cr(o,D())}P={token:$.token,keyHash:Tr(i),installId:$.installId??b},n.stop("License activated.")}catch(b){n.stop("License activation failed."),k.cancel(N(b)),process.exit(1)}let f=tl(w.projectDir);if(Xc(f)&&Zc(f).length>0)if(e.yes)k.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let D=await k.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(k.isCancel(D)||D==="cancel")&&(k.cancel("Setup cancelled."),process.exit(0)),D==="overwrite"&&Qc(f,{recursive:!0,force:!0})}let L={...w,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(o,u,f),n.stop("Template downloaded.")}catch(b){n.stop("Download failed."),k.cancel(N(b)),process.exit(1)}n.start("Generating project files...");try{if(await zt(L),!e.demo){let b=await ot(f);await l(el(f,xt),JSON.stringify(b,null," ")+`
1410
1410
  `),await $i(f,f)}await Mi(f),await Ci(L,P),n.stop("Project files generated.")}catch(b){n.stop("Generation failed."),k.cancel(N(b)),process.exit(1)}!await Vi(f)&&L.demo===!0&&(k.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Bi(f),Z=L.demo!==!0&&e.dbMigration!==!1,he=!1;Z&&fe&&(await Ki(f),he=!0),await Gi(f),fe&&await Hi(f);let Se=Fe("docker"),Pe=ir(L).map(b=>b.key).filter(b=>!L.credentials?.[b]);Yi(L,{pnpmInstalled:fe,dockerAvailable:Se,skippedCredentials:Pe,baselineMigrationMissing:Z&&!he}),Gr(),k.log.info(rl.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Zt}from"fs";import{readFile as is}from"fs/promises";import{join as Ke,resolve as ml}from"path";import*as y from"@clack/prompts";import T from"picocolors";import{mkdtemp as ol,rm as al}from"fs/promises";import{tmpdir as cl}from"os";import{join as ll}from"path";async function Lr(e,t,r,n){let i=await ol(ll(cl(),"generatesaas-stage-"));try{await Ct(e,t,i),await zt({...r,projectDir:i}),await _r(i,n)}finally{await al(i,{recursive:!0,force:!0})}}function At(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var $r=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Je,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:oe,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:Xe,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:se,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ze,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:K,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/desktop, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"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=>At(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 pl(e,t){return e[t]!==void 0}function Ji(e){return $r.filter(t=>t.adoptable&&!pl(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 dl(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 ul(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 Xi(e){let t=[];for(let r of $r){let n=e[r.key];n!==void 0&&(dl(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${ul(r)}.`))}return t}function Zi(e){let t={};for(let r of $r)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 Qi(e){return e?"ON":"OFF"}var ct="packages/config/src/index.ts";function es(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 ts(e){return[...qe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var jr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${ct} 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 ${ct} 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 ${ct}. 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===At(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Qi(e.aiBuiltin)}, but it is now a plain config value generated ${Qi(At(e))} for a project ${At(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${ct} 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 ${ct} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>es(e).join(",")===ts(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${es(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 ${ts(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Wr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${Ue.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${ct} to drop a section for good.`}],_f=jr.map(e=>e.key);function rs(e){for(let t of jr)t.normalize?.(e)}function ns(e){let t=[];for(let r of jr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function ss(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=ml(r.cwd??process.cwd()),o=Ke(i,ve),s;try{s=JSON.parse(await is(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===sr&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${sr}"\`).
1411
1411
 
1412
1412
  v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
@@ -1458,7 +1458,7 @@ ${g}`}).join(`
1458
1458
  `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1459
1459
  `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function $l(){return Ue.flatMap(e=>Dr.map(t=>Ge(e,t)))}function Mr(e){return Qt(e)?(Nl(e,{recursive:!0}),!0):!1}function jl(e,t,r=[]){if(!Qt(e))return!1;let n=Fr(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(ms(e,i,"utf-8"),!0)}function Ul(e){let t=Ge(e,".gitignore");if(!Qt(t))return!1;let r=Fr(t,"utf-8"),n=r.split(`
1460
1460
  `).filter(i=>!i.includes(".generatesaas")).join(`
1461
- `);return n===r?!1:(ms(t,n,"utf-8"),!0)}function fs(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ge(t,ve),n;try{n=JSON.parse(Fr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of $l())Mr(Ge(t,a))&&o.push(a);for(let a of Cl)Mr(Ge(t,a))&&o.push(a);Mr(Ge(t,z))&&o.push(z+"/");for(let a of Ll){let p=Ge(t,a.file);jl(p,a.removals,a.replacements)?s.push(a.file):Qt(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Ul(t)&&s.push(".gitignore");for(let a of o)U.log.info(`Deleted ${a}`);for(let a of s)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var He=new Ml().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.4.5").addHelpText("after",`
1461
+ `);return n===r?!1:(ms(t,n,"utf-8"),!0)}function fs(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ge(t,ve),n;try{n=JSON.parse(Fr(r,"utf-8"))}catch{U.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await U.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(U.isCancel(i)&&(U.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),U.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{U.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of $l())Mr(Ge(t,a))&&o.push(a);for(let a of Cl)Mr(Ge(t,a))&&o.push(a);Mr(Ge(t,z))&&o.push(z+"/");for(let a of Ll){let p=Ge(t,a.file);jl(p,a.removals,a.replacements)?s.push(a.file):Qt(p)&&U.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Ul(t)&&s.push(".gitignore");for(let a of o)U.log.info(`Deleted ${a}`);for(let a of s)U.log.info(`Modified ${a}`);U.log.success("Ejected successfully. This project is now fully standalone.")})}var He=new Ml().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.5.0").addHelpText("after",`
1462
1462
  Examples:
1463
1463
  $ generatesaas init Interactive setup
1464
1464
  $ generatesaas init -n my-app -y Quick setup with defaults
@@ -324,8 +324,10 @@ In Automatic mode, run the entire flow without prompting **except** at the manda
324
324
  found; otherwise ask.
325
325
  - **New files in deleted trees (`newInDeletedTree`):** keep them deleted (never resurrect a tree
326
326
  the user removed); note it in the summary, no prompt needed.
327
- - **Validation (Step 8):** run the type check and the test suite; if the update introduced
327
+ - **Validation (Step 8):** run the FULL ladder - lint, type check, tests, dependency
328
+ parity, the auth probe when auth changed, and the e2e gate; if the update introduced
328
329
  breakage you can fix with confidence, fix it and re-verify; if not, stop and ask.
330
+ Unattended never means ungated: the e2e rung is still required.
329
331
 
330
332
  The Step 2.5 new-options review still runs and still asks per option - Automatic mode never
331
333
  auto-adopts a new feature.
@@ -470,24 +472,52 @@ Similarly, if an auto-applied file changed its exports and a modified file that
470
472
 
471
473
  ### Step 8: Post-Update Validation
472
474
 
473
- After all files are processed:
475
+ After all files are processed, run the validation ladder below - every rung. The static
476
+ rungs cannot see hook-level auth breakage, a missing static asset, or content wiring;
477
+ the e2e suite is the only gate that exercises sign-in, registration, payments and the
478
+ rendered pages. **Do not declare the update complete while any rung is red.**
474
479
 
475
- 1. **Check for obvious issues:**
480
+ 1. **Static gates:**
476
481
  - Scan merged files for syntax errors or broken imports
477
- - If the project has TypeScript, run the type check (`pnpm check-types`)
478
- - **Run the test suite (`pnpm test`) too - do not rely on the type check alone.** Most packages scope `check-types` to `src/**` and exclude `tests/**`, so a type error introduced into a **test file** during a merge will pass `check-types` silently. If any of your merges landed in a `tests/` file, the test suite is the only gate that exercises it. When in doubt, also type-check the specific merged test files directly (e.g. `npx tsc --noEmit <file>` with the package's tsconfig settings).
479
- - Note: auto-applied files may have changed their exports/API in ways that affect **user-created files** (files not part of the template). The classification script only scans template files for cross-dependencies. A type check + test run is the best way to catch breakage in user-created files.
482
+ - Run `pnpm lint`, `pnpm check-types`, and `pnpm test`
483
+ - **Do not rely on the type check alone.** Most packages scope `check-types` to `src/**` and exclude `tests/**`, so a type error introduced into a **test file** during a merge will pass `check-types` silently. If any of your merges landed in a `tests/` file, the test suite is the only gate that exercises it. When in doubt, also type-check the specific merged test files directly (e.g. `npx tsc --noEmit <file>` with the package's tsconfig settings).
484
+ - Note: auto-applied files may have changed their exports/API in ways that affect **user-created files** (files not part of the template). The classification script only scans template files for cross-dependencies. This ladder is the best way to catch breakage in user-created files.
485
+ - A single-locale project updating from an older baseline: prefer taking the upstream web test files - newer templates derive locales and content slugs from the project's config and register locale-dependent cases conditionally, so they pass on any shape.
486
+
487
+ 2. **Dependency parity** (whenever the update or your merges touched a `package.json` or the workspace catalog): after `pnpm install`, compare the installed versions of the vendor-coupled dependencies - `better-auth` and `@better-auth/*`, `ai`, `@mastra/*`, `hono` - against `.generatesaas/staging/pnpm-workspace.yaml` and the staged `package.json`s. **The staged files are the tested-versions record**: they name exactly what this release was built and tested against. If an installed version resolved past the staged one (a range the project still carries, or a held-back manifest), pin it to the staged version and tell the user which packages you pinned and why.
488
+ - **Never run `pnpm -r update <pkg>@<version>` on a catalog-managed dependency** - it rewrites `catalog:` references in `package.json` to literal versions and orphans the catalog. Change the version in `pnpm-workspace.yaml`'s catalog and run `pnpm install` instead.
489
+
490
+ 3. **Auth smoke probe** - required whenever the update changed the `better-auth` version or `packages/auth/src/config.ts` (hooks, plugins, middleware). Hook-layer breakage is invisible to unit tests that call `auth.api.*` directly: a mis-nested hook can make **every** auth route answer `200` with an empty envelope like `{"headers":{}}` while the whole test suite stays green. Probe the handler itself (run with the project's dev env loaded so `DATABASE_URL` resolves; adjust the base path if the project customized it):
491
+
492
+ ```ts
493
+ import { auth } from "@repo/auth";
494
+ // 1) get-session with no cookie: expect HTTP 200 with body exactly "null".
495
+ // An envelope like {"headers":{}} or a 404 means the hook/handler layer is broken.
496
+ const s = await auth.handler(new Request("http://localhost:3000/api/auth/get-session"));
497
+ console.log(s.status, await s.text());
498
+ // 2) wrong-password sign-in: expect 401 with a JSON error code. A 200 here is an outage.
499
+ const r = await auth.handler(new Request("http://localhost:3000/api/auth/sign-in/email", {
500
+ method: "POST",
501
+ headers: { "content-type": "application/json", origin: "http://localhost:3000" },
502
+ body: JSON.stringify({ email: "nobody@example.com", password: "wrong-password-123" }),
503
+ }));
504
+ console.log(r.status, await r.text());
505
+ ```
506
+
507
+ 4. **The e2e gate (required):** start the local services with `pnpm infra` (Docker), then run `pnpm e2e:ci`. The suite boots the real server and exercises sign-in, registration, payments, notifications and the rendered marketing/content pages - it is the rung that catches what every static gate above misses. If Docker or the local services are genuinely unavailable in this environment, the gate moves to CI: push to a **non-deploying** branch, and the update is not complete until that CI e2e run is green. Never skip this rung silently - if it did not run, say so and say where it will.
508
+ - While reviewing e2e results, remember that template specs encode template assumptions (a seeded credits balance, ungated API-key creation, the default locale set). If the project's legitimate customization breaks an assumption, adapt the spec to the project - and record the adapted spec file in `held-back.json` in Step 9 like any other kept-your-version file, so the next update diffs it honestly.
509
+ - If content or marketing pages were added or restored during this update, verify the images they reference (paths under `apps/web/public/images/...`) exist on disk - content pages and their images travel together, and a page without its image serves a 404 that a CDN may cache. If the project sits behind a CDN, purge those image URLs after deploying.
480
510
 
481
- > All changes have been applied. I'll run the type check **and** the test suite to verify nothing is broken - the type check alone skips test files, and some auto-applied files may have changed their API in ways that affect your custom code or tests.
511
+ 5. **Production-parity boot (recommended when the update touched server boot paths, Dockerfiles, or the Node version):** the shipped containers run the Node major named in the Dockerfiles (`node:24` today). If your local Node major differs, boot the built app once under the container's major (nvm/volta) and `curl` an auth route - `/api/auth/get-session` must return `null`, not an error page. A trivial liveness route proves nothing about the request path.
482
512
 
483
- 2. If issues are found, present them:
513
+ 6. If issues are found, present them:
484
514
 
485
515
  > Found {N} issues after the update:
486
516
  > - `{file}:{line}` - {description}
487
517
  >
488
518
  > These appear to be caused by the update. Want me to fix them?
489
519
 
490
- 3. Fix any issues the user approves, then re-verify.
520
+ 7. Fix any issues the user approves, then re-verify the affected rungs.
491
521
 
492
522
  ### Step 9: Complete Update
493
523
 
@@ -497,6 +527,10 @@ After all files are processed:
497
527
  - Modified files where the user chose "Keep my version"
498
528
  - Modified files that were skipped for any reason (couldn't merge, user excluded, etc.)
499
529
  - Auto-apply files that were reverted in the cascade awareness step
530
+ - Template test/spec files you adapted to the project's customizations during validation
531
+ (e.g. an e2e spec whose seeded-balance or gating assumption the project legitimately
532
+ breaks) - the adaptation is a kept-your-version outcome, and recording it keeps the
533
+ next update's diff honest
500
534
 
501
535
  **Do NOT include:**
502
536
  - Files where the user accepted a merge or chose "Use upstream version" (template changes were applied)
@@ -540,6 +574,7 @@ This updates `.generatesaas/manifest.json` to the new version, regenerates file
540
574
  ### Post-update steps
541
575
  - Run `pnpm install` if dependencies changed
542
576
  - Run database migrations if schema was updated
577
+ - If your host auto-deploys on push, follow [Deploy Discipline](#deploy-discipline) below before pushing
543
578
  - {any other steps from the changelog}
544
579
 
545
580
  ### Skipped changes
@@ -548,6 +583,25 @@ This updates `.generatesaas/manifest.json` to the new version, regenerates file
548
583
 
549
584
  ---
550
585
 
586
+ ## Deploy Discipline
587
+
588
+ An update usually ends with a push, and many hosts (Dokploy, Coolify, Vercel, Railway)
589
+ auto-deploy that push. The update is not "done locally" on such a project - the push IS
590
+ the deploy. Rules:
591
+
592
+ 1. **Never push a branch that auto-deploys until the full Step 8 ladder - the e2e gate
593
+ included - is green locally.** Pushing first and validating after turns a red gate
594
+ into a production incident.
595
+ 2. **After pushing, watch the CI run to its conclusion.** A red run on a commit that
596
+ already deployed is an incident to act on now, not a follow-up for later.
597
+ 3. **If a push webhook deploys the project, never trigger a manual deployment alongside
598
+ it.** Two racing deploys can fail with "service already exists" (HTTP 409) and leave
599
+ the service half-recreated. Trigger manually only when the deploy queue has been
600
+ empty for several minutes.
601
+ 4. The structural fix is to deploy from a CI job that runs **after** the test jobs
602
+ succeed, instead of from the push webhook - then a red gate can never reach
603
+ production. See the deployment docs' going-to-production checklist.
604
+
551
605
  ## Merge Strategies
552
606
 
553
607
  Use these strategies when merging modified files. The goal is always: apply upstream improvements without losing user customizations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "generatesaas",
3
- "version": "3.4.5",
3
+ "version": "3.5.0",
4
4
  "type": "module",
5
5
  "description": "CLI for scaffolding and managing GenerateSaaS projects",
6
6
  "license": "UNLICENSED",