generatesaas 1.23.1 → 2.0.1
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 +287 -383
- package/dist/skill/content/SKILL.md +36 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,15 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as ic}from"commander";import*as Ki from"@clack/prompts";import{existsSync as bs,readdirSync as ks,rmSync as ws}from"fs";import{join as Ss,resolve as Es}from"path";import{Option as Z}from"commander";import*as I from"@clack/prompts";import*as vt from"@clack/prompts";import Jt from"picocolors";function Un(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";vt.intro(Jt.bgYellow(Jt.black(t)))}function Mn(){vt.outro(Jt.yellow("Happy building!"))}import*as g from"@clack/prompts";import h from"picocolors";var nt={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},rt={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)"}},bt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},kt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},wt={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},$e={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}},it={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ee={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var re={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},J={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"}]}},ie={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"}]}},ot=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],at=[{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)."}],Vn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function St(e){let t=J[e.databaseProvider].managed,n=ie[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var se={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var Ae=["nextjs","nuxt"],je=["fullstack","separate"],Ue=["stripe","polar","none"],Me=["smtp","ses","resend"],Ve=["postgres","redis","inngest","mailpit"],Be=["claude-code","cursor","codex","gemini-cli","windsurf"],Fe=["user","organization"],ce=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],le=["node","vercel"],pe=["postgres","neon","supabase"],de=["redis","upstash"],Ke=["google","github","facebook","discord","x"];function Et(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ge(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function At(e){return/^[a-z][a-z0-9-]*$/.test(e)}function N(e){return e instanceof Error?e.message:String(e)}function Ie(e){let t=e?.trim();return t?`${Ge(t)} Companion`:"My Companion"}var Bn=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ae,adoptable:!1,impact:"structural"},{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"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:le,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:pe,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:de,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ue,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ce,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Me,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:Fe,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{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"},{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"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/tauri, built with Tauri).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"desktopAi",label:"Desktop AI orchestration",hint:"Adds the desktop AI agents layer (requires the desktop app).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, knowledge base, and BYOK options. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"rag",label:"Server-side knowledge base",hint:"Adds a keyword knowledge base over your `knowledge/` docs.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companion",label:"Companion daemon",hint:"Vendors a brandable device companion your users install to run their own AI subscriptions (and any device-side work you add). You own it: source lives in this repo; one command publishes it to a public GitHub repo YOU own; releases and driver updates are your job; unsigned builds work out of the box (signing is optional and paid).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>Ie(e.projectName),adoptable:!0,impact:"config",requires:e=>e.companion===!0,requiresLabel:"requires the companion"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiByok",label:"AI billing mode (BYOK)",hint:"BYOK: end-users bring their own provider key, no credit metering. Off: operator-keyed, credit-metered platform mode.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{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",requires:e=>e.paymentProvider!==void 0&&e.paymentProvider!=="none",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"},{key:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:Ke,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ve,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Be,adoptable:!1,impact:"config"}];function Hi(e,t){return e[t]!==void 0}function Fn(e){return Bn.filter(t=>t.adoptable&&!Hi(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 Kn(e){let t={};for(let n of Bn)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}var Gn=["companion","mcpServer","rag"];function Wt(e){if(!Gn.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server / --rag require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Hn(e){return Gn.some(n=>e[n]===!0)&&(e.ai=!0),e}function zn(e){let t={};if(e.name!==void 0){if(!At(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.frontend!==void 0){if(!Ae.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ae.join(", ")}`);t.frontend=e.frontend}if(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.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(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.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.desktopAi!==void 0){if(e.desktopAi===!0&&e.desktop!==!0)throw new Error("--desktop-ai requires --desktop to be enabled.");t.desktopAi=e.desktopAi}if(e.ai!==void 0&&(t.ai=e.ai),e.rag!==void 0&&(t.rag=e.rag),e.companion!==void 0&&(t.companion=e.companion),e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiByok!==void 0&&(t.aiByok=e.aiByok),Wt(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.docker!==void 0&&(t.dockerServices=qt(e.docker,Ve,"docker service")),e.aiTools!==void 0&&(t.aiTools=qt(e.aiTools,Be,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=qt(e.socialProviders,Ke,"social provider")),e.currency!==void 0){if(!ce.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ce.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!le.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${le.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!pe.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${pe.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!de.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${de.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var ue={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,desktopAi:!1,ai:!1,rag:!1,companion:!1,mcpServer:!1,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Yn(e){let t=e.projectName??ue.projectName,n=e.projectDir??`./${t}`,r=e.appName??Ge(t),i=e.deploymentTarget??ue.deploymentTarget,o=re[i]?.edgeRuntime??!1,a=e.databaseProvider??(o?"neon":ue.databaseProvider),s=e.cacheProvider??(o?"upstash":ue.cacheProvider),d=e.emailProvider??(o?"resend":ue.emailProvider),m=e.dockerServices??(o?ue.dockerServices.filter(f=>f!=="postgres"&&f!=="redis"):ue.dockerServices),p={...ue,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:a,cacheProvider:s,emailProvider:d,dockerServices:m};p.paymentProvider==="none"&&(p.credits=!1),p.multiTenancy||(p.billingScope="user"),p.ai||(p.aiByok=ue.aiByok),p.companion&&p.companionName===void 0&&(p.companionName=Ie(p.projectName));for(let f of ot){if(p.deploymentTarget!==f.target)continue;let S=p.databaseProvider===f.provider?"database":"cache";if(p.databaseProvider===f.provider||p.cacheProvider===f.provider)throw new Error(`Incompatible: --deploy ${f.target} + --${S} ${f.provider}. ${f.reason}`)}for(let f of at)if(p.architecture===f.architecture&&p.deploymentTarget===f.target)throw new Error(`Incompatible: --architecture ${f.architecture} + --deploy ${f.target}. ${f.reason}`);return p}function qt(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(o=>o.trim()).filter(Boolean),i=r.filter(o=>!t.includes(o));if(i.length>0)throw new Error(`Invalid ${n}(s): ${i.join(", ")}. Valid values: ${t.join(", ")}`);return r}function E(e){g.isCancel(e)&&(g.cancel("Setup cancelled."),process.exit(0))}function Xt(e){let t=[];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}));for(let n of e.socialProviders){let r=se[n];for(let i of r.envVars)t.push({key:i.name,message:`${i.name} (${r.label}, optional):`,secret:i.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Jn(e,t){let n=!1;e&&Wt(e),g.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await g.text({message:"Project name:",placeholder:"my-saas",validate:u=>{if(!u?.trim())return"Project name is required.";if(!At(u))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return E(c),c})(),i=e?.appName??await(async()=>{n=!0;let c=await g.text({message:"App name:",initialValue:Ge(r),validate:u=>{if(!u?.trim())return"App name is required."}});return E(c),c})(),o=e?.projectDir??await(async()=>{n=!0;let c=await g.text({message:"Project location:",initialValue:`./${r}`});return E(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(nt),u=await g.select({message:"Frontend framework:",options:c.map(k=>({value:k,label:nt[k].label,hint:nt[k].hint}))});return E(u),u})();g.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await g.select({message:"Deployment target:",options:le.map(u=>({value:u,label:re[u].label,hint:re[u].hint}))});E(c),s=c}let d=e?.architecture?at.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let m=new Set(at.filter(c=>c.target===s).map(c=>c.architecture)),p=je.filter(c=>!m.has(c)),f=e?.architecture??await(async()=>{if(p.length===1){let u=p[0];return g.log.info(`Auto-selected ${rt[u].label} architecture (only compatible option for ${re[s].label}).`),u}n=!0;let c=await g.select({message:"Architecture:",options:p.map(u=>({value:u,label:rt[u].label,hint:rt[u].hint}))});return E(c),c})(),S=e?.databaseProvider??await(async()=>{n=!0;let c=pe.filter(k=>!ot.some(G=>G.target===s&&G.provider===k));if(c.length===1){let k=c[0];return g.log.info(`Auto-selected ${J[k].label} (only compatible option for ${re[s].label}).`),k}let u=await g.select({message:"Database provider:",options:c.map(k=>({value:k,label:J[k].label,hint:J[k].hint}))});return E(u),u})(),b=e?.cacheProvider??await(async()=>{n=!0;let c=de.filter(k=>!ot.some(G=>G.target===s&&G.provider===k));if(c.length===1){let k=c[0];return g.log.info(`Auto-selected ${ie[k].label} (only compatible option for ${re[s].label}).`),k}let u=await g.select({message:"Cache provider:",options:c.map(k=>({value:k,label:ie[k].label,hint:ie[k].hint}))});return E(u),u})();if(re[s]?.edgeRuntime){let c=Vn.map(u=>` - ${u}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let H=await
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`))}
|
|
11
|
-
|
|
12
|
-
|
|
2
|
+
import{Command as Jc}from"commander";import*as Ti from"@clack/prompts";import{existsSync as sc,readdirSync as cc,rmSync as pc}from"fs";import{join as lc,resolve as dc}from"path";import{Option as X}from"commander";import*as A from"@clack/prompts";import*as Nt from"@clack/prompts";import yn from"picocolors";function dr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(yn.bgYellow(yn.black(t)))}function ur(){Nt.outro(yn.yellow("Happy building!"))}import*as f from"@clack/prompts";import h from"picocolors";var ht={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},yt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},$t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ut={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},qe={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}},wt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var De={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var ie={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}},Y={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"}]}},ae={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"}]}},vt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],kt=[{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)."}],mr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function jt(e){let t=Y[e.databaseProvider].managed,n=ae[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ue={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var Ne=["nextjs","nuxt"],Ye=["fullstack","separate"],We=["stripe","polar","none"],Xe=["smtp","ses","resend"],Ze=["postgres","redis","inngest","mailpit"],Qe=["claude-code","cursor","codex","gemini-cli","windsurf"],et=["user","organization"],me=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],fe=["node","vercel"],ge=["postgres","neon","supabase"],he=["redis","upstash"],tt=["google","github","facebook","discord","x"],$e=["shared","vendored"];function Mt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Vt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function ee(e){let t=e?.trim();return t?`${nt(t)} Companion`:"My Companion"}var Le="https://github.com/Duzbee/OpenCompanion";function se(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function fr(e){return e.desktop===!0&&e.ai===!0}function W(e){if(fr(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return se(e)}function ye(e){return fr(e)?!0:e.companion===!0&&se(e)==="vendored"}function Ft(e){return e.demo===!0&&e.companion===!0?!0:ye(e)}function Ie(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var gr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ne,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ye,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:fe,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ge,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:he,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:me,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:et,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{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"},{key:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{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"},{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"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>W(e),choices:$e,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Le,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>ee(e.projectName),adoptable:!0,impact:"config",requires:e=>ye(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ie(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ie(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{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",requires:e=>Ie(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"},{key:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:tt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,adoptable:!1,impact:"config"}];function Oi(e,t){return e[t]!==void 0}function hr(e){return gr.filter(t=>t.adoptable&&!Oi(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 yr(e){let t={};for(let n of gr)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as vn}from"fs/promises";import{join as wr}from"path";var wn="GENERATESAAS_COMPANION_BRAND_JSON",Bt=["daemon/brand.json","apps/companion/brand.json"];function ce(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function vr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Gt(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}async function Ci(e,t){let n=wr(e,"apps/companion/brand.json"),r;try{r=await vn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=ce(o)}catch{return null}return vr(i,t)?Gt(r,`the template (${n})`):null}async function Di(e,t){for(let n of Bt){let r=wr(e,n),o;try{o=await vn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Gt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=ce(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!vr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Bt.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function Ni(e){for(let t of Bt){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return Gt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Bt.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function kr(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=ce(t),r=await Ci(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Di(o,n);let i=process.env[wn]?.trim();if(i){let a;try{a=await vn(i,"utf8")}catch(s){throw new Error(`Could not read ${wn} (${i}): ${T(s)}.`)}return Gt(a,`${wn} (${i})`)}return await Ni(n)}var br=["companion","mcpServer"];function bn(e){if(!br.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Sr(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ie(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function Sn(e){if(!Sr(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Er(e){return br.some(n=>e[n]===!0)&&(e.ai=!0),e}function Ir(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ie(e)||(e.aiBuiltin=!1),Sr(e)||(e.aiByok=!0)),e}function Ar(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=$i(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&En(e),n}function En(e){return ye(e)&&(e.companionSource=W(e),e.companionName===void 0&&(e.companionName=ee(e.projectName))),e}function $i(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function Pr(e){let t={};if(e.name!==void 0){if(!Vt(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.frontend!==void 0){if(!Ne.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ne.join(", ")}`);t.frontend=e.frontend}if(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.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!$e.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${$e.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=ce(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),bn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, or turn AI off with --no-ai.");if(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.docker!==void 0&&(t.dockerServices=kn(e.docker,Ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=kn(e.aiTools,Qe,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=kn(e.socialProviders,tt,"social provider")),e.currency!==void 0){if(!me.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${me.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!fe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${fe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ge.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ge.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!he.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${he.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var pe={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Rr(e){let t=e.projectName??pe.projectName,n=e.projectDir??`./${t}`,r=e.appName??nt(t),o=e.deploymentTarget??pe.deploymentTarget,i=ie[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":pe.databaseProvider),s=e.cacheProvider??(i?"upstash":pe.cacheProvider),u=e.emailProvider??(i?"resend":pe.emailProvider),g=e.dockerServices??(i?pe.dockerServices.filter(m=>m!=="postgres"&&m!=="redis"):pe.dockerServices),l={...pe,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=pe.aiBuiltin,l.aiByok=pe.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=W(l)),ye(l)&&l.companionName===void 0&&(l.companionName=ee(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=se(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=ee(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Le),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),Sn(l);for(let m of vt){if(l.deploymentTarget!==m.target)continue;let w=l.databaseProvider===m.provider?"database":"cache";if(l.databaseProvider===m.provider||l.cacheProvider===m.provider)throw new Error(`Incompatible: --deploy ${m.target} + --${w} ${m.provider}. ${m.reason}`)}for(let m of kt)if(l.architecture===m.architecture&&l.deploymentTarget===m.target)throw new Error(`Incompatible: --architecture ${m.architecture} + --deploy ${m.target}. ${m.reason}`);return l}function kn(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function S(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function In(e){let t=[];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}));for(let n of e.socialProviders){let r=ue[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function xr(e,t){let n=!1;e&&bn(e),f.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Vt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await f.text({message:"App name:",initialValue:nt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await f.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(ht),d=await f.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:ht[b].label,hint:ht[b].hint}))});return S(d),d})();f.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await f.select({message:"Deployment target:",options:fe.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint}))});S(c),s=c}let u=e?.architecture?kt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(kt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ye.filter(c=>!g.has(c)),m=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return f.log.info(`Auto-selected ${yt[d].label} architecture (only compatible option for ${ie[s].label}).`),d}n=!0;let c=await f.select({message:"Architecture:",options:l.map(d=>({value:d,label:yt[d].label,hint:yt[d].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=ge.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${Y[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Database provider:",options:c.map(b=>({value:b,label:Y[b].label,hint:Y[b].hint}))});return S(d),d})(),v=e?.cacheProvider??await(async()=>{n=!0;let c=he.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${ae[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Cache provider:",options:c.map(b=>({value:b,label:ae[b].label,hint:ae[b].hint}))});return S(d),d})();if(ie[s]?.edgeRuntime){let c=mr.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);f.note(c,"Unavailable on edge runtime")}f.log.info(h.bold("Features"));let R=e?.paymentProvider??await(async()=>{n=!0;let c=await f.select({message:"Payment provider:",options:We.map(d=>({value:d,label:$t[d].label,hint:$t[d].hint}))});return S(c),c})(),q=e?.defaultCurrency??await(async()=>{if(R==="none")return"USD";n=!0;let c=await f.select({message:"Default currency:",options:me.map(d=>({value:d,label:d,hint:De[d].name}))});return S(c),c})(),be=e?.emailProvider??await(async()=>{n=!0;let c=await f.select({message:"Email provider:",options:Xe.map(d=>({value:d,label:Lt[d].label,hint:Lt[d].hint}))});return S(c),c})(),Q=e?.multiTenancy??await(async()=>{n=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),Se=Q?e?.billingScope??"user":"user";if(Q&&e?.billingScope===void 0){n=!0;let c=await f.select({message:"Billing scope:",options:et.map(d=>({value:d,label:Ut[d].label,hint:Ut[d].hint}))});S(c),Se=c}let Je=e?.blog??await(async()=>{n=!0;let c=await f.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),Ee=e?.emailTracking??await(async()=>{n=!0;let c=await f.confirm({message:"Enable email analytics? (open/click tracking + admin analytics page)",initialValue:!0});return S(c),c})(),E=e?.docs??await(async()=>{n=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),$=t?.desktopAllowed!==!1,L=e?.desktop??($?await(async()=>{n=!0;let c=await f.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 and bundles its own companion daemon.",initialValue:!1});return S(c),c})():(f.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Oe=L?e?.desktopAutoRelease??await(async()=>{n=!0;let c=await f.select({message:"Desktop release trigger:",options:[{value:!1,label:"Manual only",hint:"run from the Actions tab (saves CI minutes)"},{value:!0,label:"Automatic",hint:"release on every CI success on main"}],initialValue:!1});return S(c),c})():!1,_=e?.ai??await(async()=>{n=!0;let c=await f.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion + MCP server)",initialValue:!1});return S(c),c})(),k=_?e?.companion??await(async()=>{n=!0;let c=await f.confirm({message:"Add the companion daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex / OpenCode 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})():!1,B=L&&_,oe=B?W({desktop:L,ai:_,companion:k,companionSource:e?.companionSource,companionName:e?.companionName}):k?e?.companionSource??await(async()=>{n=!0;let c=await f.select({message:"Companion source:",options:[{value:"shared",label:"Shared companion",hint:"point at an existing companion repo (OpenCompanion by default) - nothing to publish or maintain"},{value:"vendored",label:"Vendored companion",hint:"own a branded daemon: source in this repo, published to your own GitHub repo"}],initialValue:"shared"});return S(c),c})():void 0;B&&f.log.info(h.dim("Companion source: your desktop app bundles its own daemon, so it is vendored into this repo. Nothing to publish - it ships inside the app."));let dn=oe!=="shared"?void 0:e?.companionRepoUrl??await(async()=>{n=!0;let c=await f.text({message:"Companion repo URL (GitHub):",initialValue:Le,validate:d=>{if(!d?.trim())return"A companion repo URL is required for a shared companion.";try{ce(d)}catch(b){return T(b)}}});return S(c),ce(c).canonicalUrl})(),ar=oe!=="shared"?void 0:e?.companionLocalPath??await(async()=>{n=!0;let c=await f.text({message:"Path to your local checkout of this companion (leave empty otherwise):",placeholder:"only if you develop the companion alongside this project",defaultValue:""});return S(c),c.trim()})(),Ot=oe!=="vendored"?void 0:e?.companionName??await(async()=>{n=!0;let c=await f.text({message:B&&!k?"Companion name (your app's bundled daemon - names its binary, service and data folder):":"Companion name (what your users install):",initialValue:ee(r),validate:d=>{if(!d?.trim())return"Companion name is required."}});return S(c),c})(),sr=_?e?.mcpServer??await(async()=>{n=!0;let c=await f.confirm({message:"Add the outward MCP server? Lets external agents (Claude Code, Codex, Hermes, OpenClaw) control the app on a user's behalf over an authenticated MCP endpoint.",initialValue:!1});return S(c),c})():!1,un=R==="none"?!1:_?e?.aiBuiltin??await(async()=>{n=!0;let c=await f.confirm({message:"Built-in AI? (models under your app's name via OpenRouter, billed from user credits)",initialValue:!0});return S(c),c})():!0,mn=_?e?.aiByok??await(async()=>{n=!0;let c=await f.confirm({message:"Allow users to bring their own API keys? (their runs never use credits)",initialValue:!0});return S(c),c})():!0;Sn({ai:_,aiBuiltin:un,aiByok:mn,companion:k,desktop:L,paymentProvider:R});let cr=e?.revenueSharing??await(async()=>{n=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),pr=R==="none"?!1:e?.credits??await(async()=>{n=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),Ct=e?.socialProviders??await(async()=>{n=!0;let c=tt.map(b=>({value:b,label:ue[b].label,hint:`requires ${ue[b].envVars.map(K=>K.name).join(" / ")}`})),d=await f.multiselect({message:"Which social login providers should the sign-in screen show?",options:c,initialValues:[],required:!1});return S(d),d})();f.log.info(h.bold("Tooling"));let fn=e?.dockerServices??await(async()=>{n=!0;let c=[...Ze].filter(H=>H!=="mailpit");be==="smtp"&&c.push("mailpit");let d=c.map(H=>({value:H,label:qe[H].label,hint:qe[H].hint})),b=d.map(H=>H.value).filter(H=>!(H==="postgres"&&(w==="neon"||w==="supabase")||H==="redis"&&v==="upstash")),K=await f.multiselect({message:"Which services should we set up in Docker for you?",options:d,initialValues:b,required:!1});return S(K),K})(),gn=e?.aiTools??await(async()=>{n=!0;let c=Qe.map(b=>({value:b,label:wt[b].label})),d=await f.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return S(d),d})(),hn=e?.demo,Dt=In({databaseProvider:w,cacheProvider:v,paymentProvider:R,emailProvider:be,socialProviders:Ct,demo:hn}),gt={};if(Dt.length>0&&n){f.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Dt)if(n=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}}if(n){let c=[` Name: ${h.cyan(r)}`,` App name: ${h.cyan(o)}`,` Location: ${h.cyan(i)}`,` Frontend: ${h.cyan(ht[a].label)}`,` Architecture: ${h.cyan(yt[m].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${h.cyan(ie[s]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Y[w].label)}`,` Cache: ${h.cyan(ae[v].label)}`,fn.length>0?` Docker: ${h.cyan(fn.map(Ce=>qe[Ce].label).join(", "))}`:` Docker: ${h.dim("none")}`].filter(Boolean).join(`
|
|
5
|
+
`),b=[R!=="none"?` Payment: ${h.cyan($t[R].label)} (${q})`:` Payment: ${h.dim("none")}`,` Credits: ${pr?h.cyan("Yes"):h.dim("No")}`,` AI features: ${_?h.cyan("Yes"):h.dim("No")}`,..._?[` AI sources: ${h.cyan([un?"Built-in (credits)":null,mn?"User keys":null].filter(Boolean).join(" + ")||"none")}`,` Companion: ${k?h.cyan("Yes"):h.dim("No")}`,...k?[` Comp. source: ${h.cyan(oe==="shared"?"Shared":"Vendored")}`,oe==="shared"?` Comp. repo: ${h.cyan(dn??"")}`:` Comp. name: ${h.cyan(Ot??"")}`]:[],` MCP server: ${sr?h.cyan("Yes"):h.dim("No")}`]:[],` Email: ${h.cyan(Lt[be].label)}`,` Email stats: ${Ee?h.cyan("Yes"):h.dim("No")}`,` Multi-tenancy: ${Q?h.cyan("Yes")+` (billing: ${Ut[Se].label})`:h.dim("No")}`,` Blog: ${Je?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${E?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` Releases: ${h.cyan(Oe?"Automatic on CI":"Manual only")}`]:[],...B&&!k?[` Desktop AI: ${h.cyan("Yes")} (bundles ${Ot??""})`]:[],` Rev. sharing: ${cr?h.cyan("Yes"):h.dim("No")}`,Ct.length>0?` Social login: ${h.cyan(Ct.map(Ce=>ue[Ce].label).join(", "))}`:` Social login: ${h.dim("none")}`,gn.length>0?` AI tools: ${h.cyan(gn.map(Ce=>wt[Ce].label).join(", "))}`:` AI tools: ${h.dim("none")}`].join(`
|
|
6
|
+
`),K=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),b];if(Dt.length>0){let Ce=Dt.map(lr=>{let _i=gt[lr.key]?h.green("provided"):h.dim("skipped");return` ${lr.key}: ${_i}`}).join(`
|
|
7
|
+
`);K.push("",h.bold("Credentials"),Ce)}f.note(K.join(`
|
|
8
|
+
`),"Summary");let H=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(H)||!H)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:o,projectDir:i,frontend:a,architecture:m,deploymentTarget:s,databaseProvider:w,cacheProvider:v,paymentProvider:R,emailProvider:be,multiTenancy:Q,billingScope:Se,blog:Je,emailTracking:Ee,docs:E,desktop:L,desktopAutoRelease:Oe,ai:_,companion:k,...Ot!==void 0?{companionName:Ot}:{},...oe!==void 0?{companionSource:oe}:{},...dn!==void 0?{companionRepoUrl:dn}:{},...ar!==void 0?{companionLocalPath:ar}:{},mcpServer:sr,aiBuiltin:un,aiByok:mn,revenueSharing:cr,credits:pr,dockerServices:fn,aiTools:gn,socialProviders:Ct,defaultCurrency:q,...Object.keys(gt).length>0?{credentials:gt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...hn!==void 0?{demo:hn}:{}}}import{createReadStream as Lr,existsSync as Ji}from"fs";import{mkdir as qi}from"fs/promises";import{join as Yi}from"path";import{Readable as Wi}from"stream";import{pipeline as On}from"stream/promises";import{extract as Xi}from"tar";import{join as Ue}from"path";import{homedir as Li}from"os";var bt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",Ae=Ue(z,"manifest.json"),Tr=Ue(z,"hashes.json"),Kt=Ue(z,"template-hashes.json"),Ht=Ue(z,"template"),_r=Ue(z,"staging"),Or=Ue(z,"staging.json"),we=Ue(Li(),".generatesaas");var V=class extends Error{constructor(n,r,o){super(r);this.status=n;this.body=o}status;body;name="ApiError"};function ve(e){return{apiKey:e,baseUrl:bt}}async function Pe(e,t,n){let r=`${e.baseUrl}${t}`,o=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.0.1"}});if(!o.ok){let i,a;try{a=await o.json(),i=a.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new V(o.status,i,a)}return o}import{existsSync as Ui,readFileSync as ji,writeFileSync as Mi,mkdirSync as Vi}from"fs";import{dirname as Fi}from"path";import*as Re from"@clack/prompts";function St(){if(!Ui(we))return null;try{let e=JSON.parse(ji(we,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Re.log.warning(`Found old GitHub token in ${we}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function je(e){Vi(Fi(we),{recursive:!0}),Mi(we,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function rt(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=St();if(n)return n;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return Et()}async function Et(){let e=await Re.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Re.isCancel(e)&&(Re.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Bi}from"fs/promises";async function xe(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Bi(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await Pe(e,"/versions")).json()}async function An(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Pe(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof V&&n.status===404)return null;throw n}}async function Cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await Pe(e,`/skill/${encodeURIComponent(t)}`)).json()}function zt(e){if(!(e instanceof V)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}function Dr(e){return{frontend:e.frontend,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,credits:e.credits,revenueSharing:e.revenueSharing,socialProviders:e.socialProviders,aiTools:e.aiTools,currency:e.defaultCurrency}}async function Pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Pe(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Nr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Pe(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Rn(e,t){let n=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Verification service returned ${n.status}`);return await n.json()}async function $r(e,t,n){let r=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});if(!r.ok){let o=await r.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var xn=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),Tn=new Set(["pnpm-lock.yaml"]);function ot(e){if(_n(e))return!0;for(let t of e.split("/"))if(Tn.has(t))return!0;return!1}var Gi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","README.md","TODO.md","OVERVIEW.md"]),Ki=["scripts/docs-lint.ts"],Hi=["scripts/companion-export/"],zi=["docs/superpowers","packages/cli","packages/cli-api","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function _n(e){let t=e.split("/");for(let n of t)if(xn.has(n))return!0;if(Ki.includes(e))return!1;for(let n of Hi)if(e.startsWith(n)||`${e}/`===n)return!1;if(Gi.has(t[0]))return!0;for(let n of zi)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function Jt(e,t,n){await qi(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let s=Yi(r,`v${t}.tar.gz`);if(!Ji(s))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${s} does not exist.`);await On(Lr(s),Cn(n));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await On(Lr(o),Cn(n));return}let i=await Pe(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let a=Wi.fromWeb(i.body);await On(a,Cn(n))}function Cn(e){return Xi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!_n(n):!0},sync:!1})}import{readdir as sa,readFile as At,rm as Nn,writeFile as Pt}from"fs/promises";import{join as ke}from"path";import{readFile as It,rm as Ur}from"fs/promises";import{join as Te}from"path";import{mkdir as Zi,readdir as Qi,rm as ea,rmdir as ta,writeFile as na}from"fs/promises";import{dirname as qt,join as ra,relative as oa,sep as ia}from"path";function Me(e){return e.split(ia).join("/")}async function Yt(e){await Zi(e,{recursive:!0})}async function p(e,t){await Yt(qt(e)),await na(e,t,"utf-8")}async function Dn(e,t){await ea(e,{force:!0});let n=qt(e);for(;n!==t&&n!==qt(n);){try{await ta(n)}catch{return}n=qt(n)}}async function Ve(e,t,n){let r=[],o=await Qi(e,{withFileTypes:!0});for(let i of o){let a=ra(e,i.name),s=Me(oa(t,a));n(s)||(i.isDirectory()?r.push(...await Ve(a,t,n)):i.isFile()&&r.push(a))}return r}function aa(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function C(e,t,n="ai",r="stripDesktopAi"){let o=aa(n);if(e.match(o)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${n}-start`)||i.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`)}async function I(e,t,n,r,o){let i=await It(e,"utf-8"),a=i.indexOf(t);if(a===-1)throw new Error(`${o}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,a+t.length)!==-1)throw new Error(`${o}: the ${r} seam appears more than once (boilerplate drift).`);await p(e,i.slice(0,a)+n+i.slice(a+t.length))}async function Wt(e,t,n,r){let o=/\n([\t ]+)"/.exec(await It(e,"utf-8"))?.[1];if(o!==n){let i=a=>a===" "?"tab":`${a.length}-space`;throw new Error(`${r}: expected ${e} to be ${i(n)}-indented, but it is ${o===void 0?"not indented":i(o)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await p(e,`${JSON.stringify(t,null,n)}
|
|
13
|
+
`)}function Xt(e,t,n,r){if(!(t in e))throw new Error(`${r}: expected ${n} (boilerplate drift).`);delete e[t]}function it(e){return e.frontend==="nextjs"?"next":"nuxt"}async function jr(e,t,n,r,o,i){let a=Te(e,"docs",t);await Ur(Te(a,`${n}.mdx`)),await I(Te(a,"meta.json"),` "${n}",
|
|
14
|
+
`,"",`${t} meta.json ${n} nav entry`,o),await Mr(a,t,r,o),i!==void 0&&await Vr(a,t,i,o)}async function Mr(e,t,n,r){let o=Te(e,"ai.mdx"),a=(await It(o,"utf-8")).split(`
|
|
15
|
+
`).find(s=>s.includes(`href="${n}"`));if(a===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${n} (boilerplate drift).`);await I(o,`${a}
|
|
16
|
+
`,"",`${t} ai.mdx ${n} card`,r)}async function Vr(e,t,n,r){let o=Te(e,"ai.mdx"),i=`| **${n}** |`,s=(await It(o,"utf-8")).split(`
|
|
17
|
+
`).find(u=>u.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await I(o,`${s}
|
|
18
|
+
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function Fr(e,t,n,r,o,i){let a=Te(e,"docs",t);await Ur(Te(a,n),{recursive:!0}),await I(Te(a,"meta.json"),` "${n}",
|
|
19
|
+
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await Mr(a,t,s,o);i!==void 0&&await Vr(a,t,i,o)}async function Zt(e){let t=`import { config } from "@repo/config";
|
|
20
|
+
`,n=await It(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),o=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await p(e,r)}var ca=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Gr(e){await Promise.all(ca.map(t=>Nn(ke(e,t),{recursive:!0,force:!0})))}var pa=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function Kr(e){let t="removeDesktopDemoScreen";await Nn(ke(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of pa){let r=ke(e,n);await Pt(r,C(await At(r,"utf-8"),n,"demo",t))}}var la="packages/config/src/blog.ts";async function Hr(e){let t=ke(e,la),n=await At(t,"utf-8"),r=Br(Br(n,"blogCategories",t),"blogAuthors",t);await Pt(t,r)}function Br(e,t,n){let r=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!r.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${n}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(r,"$1[];")}async function zr(e){let t=ke(e,"packages/i18n/translations"),n;try{n=await sa(t)}catch{return}for(let r of n){let o=ke(t,r,"web.json"),i;try{i=await At(o,"utf-8")}catch{continue}let a=JSON.parse(i);!a.blog||a.blog.categories===void 0||(a.blog.categories={},await Pt(o,JSON.stringify(a,null," ")+`
|
|
21
|
+
`))}}var da="packages/config/src/ai/tasks.ts";async function Jr(e){let t=ke(e,da),n=await At(t,"utf-8"),r=n.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(r===n)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.`);await Pt(t,r)}async function qr(e,t){t.includes("claude-code")||await Nn(ke(e,".claude"),{recursive:!0,force:!0})}async function Yr(e,t){let n=ke(e,".claude","settings.json"),r;try{r=await At(n,"utf8")}catch{return}let o=JSON.parse(r);delete o.alwaysThinkingEnabled,delete o.enableAllProjectMcpServers,o.env&&(delete o.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(o.env).length===0&&delete o.env),o.permissions?.allow&&(o.permissions.allow=o.permissions.allow.filter(i=>ua(i,t))),await Pt(n,JSON.stringify(o,null," ")+`
|
|
22
|
+
`)}function ua(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Wr}from"path";var ma={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},fa={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},ga={redis:"Redis",upstash:"Upstash Redis"},ha={node:"Node.js / Docker",vercel:"Vercel"},ya={stripe:"Stripe",polar:"Polar"};function wa(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",a=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",s=i?`Mounted inside \`${r}\`. 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.",u=ga[e.cacheProvider],g=ha[e.deploymentTarget],l=e.paymentProvider==="none"?"":`
|
|
23
|
+
- **Payments:** ${ya[e.paymentProvider]}`,m=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",w="";e.companion&&(se(e)==="vendored"?w=`
|
|
24
|
+
- \`apps/companion\` - the source of **${e.companionName??ee(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:e.companionLocalPath?w=`
|
|
25
|
+
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\`. A local checkout lives at \`${e.companionLocalPath}\` - edit and commit device-side behavior THERE, not in this repo (clone from the repo URL if the checkout is missing).`:w=`
|
|
26
|
+
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let v=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",R=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
|
|
13
27
|
|
|
14
28
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
15
29
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -37,11 +51,11 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
37
51
|
|
|
38
52
|
- **Frontend:** ${n} ${a}
|
|
39
53
|
- **API:** Hono, RPC-typed. ${s}
|
|
40
|
-
- **Database:** Drizzle ORM + ${
|
|
41
|
-
- **Cache + jobs:** ${
|
|
42
|
-
- **Auth:** Better Auth${
|
|
43
|
-
- **Email:** ${
|
|
44
|
-
- **Deploy:** ${
|
|
54
|
+
- **Database:** Drizzle ORM + ${ma[e.databaseProvider]}
|
|
55
|
+
- **Cache + jobs:** ${u} + Inngest
|
|
56
|
+
- **Auth:** Better Auth${l}
|
|
57
|
+
- **Email:** ${fa[e.emailProvider]}
|
|
58
|
+
- **Deploy:** ${g}
|
|
45
59
|
|
|
46
60
|
## Where things live (extend these - don't reinvent)
|
|
47
61
|
|
|
@@ -51,12 +65,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
51
65
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
52
66
|
- \`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\`.
|
|
53
67
|
- \`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.
|
|
54
|
-
- \`${r}\` - the ${n} app (${
|
|
55
|
-
- \`docs/${t?"nuxt":"next"}/\` - 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/\`${
|
|
56
|
-
|
|
57
|
-
## Knowledge
|
|
58
|
-
|
|
59
|
-
\`knowledge/\` is the product knowledge that grounds the AI: read-only markdown entries, confidential, never user-facing - injected into the model's context so it answers from your facts. When you add or maintain an entry, FOLLOW THE RULES in \`knowledge/AGENTS.md\` (one concept per entry, frontmatter, \`[[wikilinks]]\`) and run \`pnpm knowledge:lint\` to validate. \`pnpm knowledge:build\` seeds the web knowledge base (gated by \`config.rag.enabled\`); the desktop app self-indexes its bundled copy. See \`docs/${t?"nuxt":"next"}/knowledge.mdx\`.
|
|
68
|
+
- \`${r}\` - the ${n} app (${o}).${w}
|
|
69
|
+
- \`docs/${t?"nuxt":"next"}/\` - 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/\`${m}.
|
|
60
70
|
|
|
61
71
|
## Code style
|
|
62
72
|
|
|
@@ -73,8 +83,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
73
83
|
|
|
74
84
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
75
85
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
76
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
77
|
-
- ${
|
|
86
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${v} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
87
|
+
- ${R}
|
|
78
88
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
79
89
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
80
90
|
|
|
@@ -85,14 +95,14 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
85
95
|
## This project
|
|
86
96
|
|
|
87
97
|
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\`.
|
|
88
|
-
`}async function
|
|
89
|
-
`)}import{join as
|
|
98
|
+
`}async function Xr(e){await p(Wr(e.projectDir,"AGENTS.md"),wa(e)),await p(Wr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
99
|
+
`)}import{join as va}from"path";var ka={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ba(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",o=n?"apps/web-nuxt":"apps/web-next",i=ka[e.databaseProvider],a=jt(e),s=e.architecture==="fullstack"?`${r} app at \`${o}/\` 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.`:`${r} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,u=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
90
100
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
91
101
|
- API: http://localhost:3010
|
|
92
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
93
|
-
`:"",
|
|
102
|
+
- Inngest dev server: http://127.0.0.1:8288`,g=a?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
103
|
+
`:"",l=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
|
|
94
104
|
|
|
95
|
-
This 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).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,
|
|
105
|
+
This 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).${a?"\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).":""}`,m=e.aiTools.length>0?"To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: `update my GenerateSaaS project`.":"To pull the latest boilerplate changes into this project, install an AI coding agent (Claude Code / Cursor / Codex / Gemini CLI / Windsurf) and ask: `update my GenerateSaaS project`. The skill bundle that drives the update lives under each tool's skill root.";return`# ${t}
|
|
96
106
|
|
|
97
107
|
${s}
|
|
98
108
|
|
|
@@ -101,7 +111,7 @@ ${s}
|
|
|
101
111
|
- **Frontend:** ${r}
|
|
102
112
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
103
113
|
- **Auth:** Better Auth
|
|
104
|
-
- **ORM / DB:** Drizzle + ${
|
|
114
|
+
- **ORM / DB:** Drizzle + ${i}
|
|
105
115
|
- **Background jobs:** Inngest
|
|
106
116
|
- **i18n:** ${n?"@nuxtjs/i18n":"next-intl"}
|
|
107
117
|
|
|
@@ -112,11 +122,11 @@ pnpm install
|
|
|
112
122
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
113
123
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
114
124
|
# reference. All apps load the single root \`.env\`.
|
|
115
|
-
${
|
|
125
|
+
${g}pnpm db:setup # first run: create the database schema (idempotent)
|
|
116
126
|
pnpm dev
|
|
117
127
|
\`\`\`
|
|
118
128
|
|
|
119
|
-
${
|
|
129
|
+
${u}
|
|
120
130
|
|
|
121
131
|
## Build your SaaS
|
|
122
132
|
|
|
@@ -136,7 +146,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
|
|
|
136
146
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
137
147
|
\`\`\`
|
|
138
148
|
|
|
139
|
-
${
|
|
149
|
+
${l}
|
|
140
150
|
|
|
141
151
|
## Removing the GenerateSaaS license
|
|
142
152
|
|
|
@@ -148,16 +158,21 @@ pnpm dlx generatesaas eject
|
|
|
148
158
|
|
|
149
159
|
## Updates
|
|
150
160
|
|
|
151
|
-
${
|
|
152
|
-
`}async function
|
|
153
|
-
`)}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
161
|
+
${m}
|
|
162
|
+
`}async function Zr(e){await p(va(e.projectDir,"README.md"),ba(e))}import{access as Ea,readFile as Ia}from"fs/promises";import{join as at}from"path";import{join as Sa}from"path";function $n(e,t){let n=Mt(e,"companion"),r=t?new URL(t).hostname.split(".").reverse().join("."):"com",o=n.toUpperCase().replace(/-/g,"_");return{name:e,binary:n,scope:`@${n}`,serviceLabel:`${r}.${n}`,appDirName:n,envPrefix:/^[0-9]/.test(o)?`_${o}`:o,docsUrl:"",repoUrl:"",installBase:""}}async function Qr(e){if(!ye(e)||e.demo||W(e)==="shared")return;if(!e.companionName)throw new Error("generateCompanionBrand: this project ships a companion daemon but options.companionName is missing.");let t=$n(e.companionName,e.baseUrl);await p(Sa(e.projectDir,"apps/companion/brand.json"),JSON.stringify(t,null,2)+`
|
|
163
|
+
`)}async function Aa(e,t,n){let r=at(e,"apps/electron/dev-app-update.yml");try{await Ea(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
164
|
+
url: ${t}
|
|
165
|
+
updaterCacheDirName: ${n}
|
|
166
|
+
`)}function Pa(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Ra(e,t){let n=Mt(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function xa(e){if(!e.companion&&!ye(e))return'{ enabled: false, clientId: "companion" }';let t;if(e.demo)t=JSON.parse(await Ia(at(e.projectDir,"apps/companion/brand.json"),"utf8"));else if(W(e)==="shared"){let r=await kr(e),o=ce(e.companionRepoUrl??"").canonicalUrl;t={name:r.name,binary:r.binary,envPrefix:r.envPrefix,repoUrl:o,installBase:`${o}/releases/latest/download`}}else{if(!e.companionName)throw new Error("generateConfig: this project ships a companion daemon but options.companionName is missing.");t=$n(e.companionName,e.baseUrl)}let n={name:t.name,binary:t.binary,envPrefix:t.envPrefix,repoUrl:t.repoUrl,installBase:t.installBase};return["{",` enabled: ${e.companion},`,' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(n.name)},`,` binary: ${JSON.stringify(n.binary)},`,` envPrefix: ${JSON.stringify(n.envPrefix)},`,` repoUrl: ${JSON.stringify(n.repoUrl)},`,` installBase: ${JSON.stringify(n.installBase)}`," }"," }"].join(`
|
|
167
|
+
`)}async function eo(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=Pa(o),a=e.demo?"false":"true",s=e.demo?`{
|
|
168
|
+
enableInDev: true,
|
|
169
|
+
chatwoot: {
|
|
170
|
+
baseUrl: "https://support.alexchelan.com",
|
|
171
|
+
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
172
|
+
}
|
|
173
|
+
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=Ra(t,i),l=`https://cdn.${i}/desktop`,m=await xa(e),w=`{ enabled: ${e.mcpServer} }`,v=`import type { AppConfig } from "@repo/config/types";
|
|
160
174
|
import { desktopConfig } from "./desktop.mjs";
|
|
175
|
+
import { supportConfig } from "./support.mjs";
|
|
161
176
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
162
177
|
|
|
163
178
|
const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
@@ -165,7 +180,7 @@ const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim
|
|
|
165
180
|
export const config: AppConfig = {
|
|
166
181
|
siteName: "${t}",
|
|
167
182
|
fullSiteName: "${t}",
|
|
168
|
-
domain: "${
|
|
183
|
+
domain: "${o}",
|
|
169
184
|
baseUrl: process.env.BASE_URL ?? "${r}",
|
|
170
185
|
indexable: ${a},
|
|
171
186
|
logo: {
|
|
@@ -192,20 +207,24 @@ export const config: AppConfig = {
|
|
|
192
207
|
limitPerSecond: 3,
|
|
193
208
|
senders: {
|
|
194
209
|
transactional: {
|
|
195
|
-
email: "noreply@${
|
|
210
|
+
email: "noreply@${i}",
|
|
196
211
|
senderName: "${t}"
|
|
197
212
|
},
|
|
198
213
|
marketing: {
|
|
199
|
-
email: "hello@${
|
|
214
|
+
email: "hello@${i}",
|
|
200
215
|
senderName: "${t}",
|
|
201
216
|
signatureName: "Alex"
|
|
202
217
|
},
|
|
203
218
|
support: {
|
|
204
|
-
email: "support@${
|
|
219
|
+
email: "support@${i}",
|
|
205
220
|
senderName: "${t} Support"
|
|
206
221
|
}
|
|
207
222
|
},
|
|
208
|
-
inactiveEmailSchedule: [7, 30, 90]
|
|
223
|
+
inactiveEmailSchedule: [7, 30, 90],
|
|
224
|
+
tracking: {
|
|
225
|
+
enabled: ${e.emailTracking},
|
|
226
|
+
retentionDays: 90
|
|
227
|
+
}
|
|
209
228
|
},
|
|
210
229
|
storage: {
|
|
211
230
|
enabled: true,
|
|
@@ -225,7 +244,7 @@ export const config: AppConfig = {
|
|
|
225
244
|
prefix: "key_"
|
|
226
245
|
},
|
|
227
246
|
apiDocs: true,
|
|
228
|
-
performanceMonitor: { enabled: ${
|
|
247
|
+
performanceMonitor: { enabled: ${u} },
|
|
229
248
|
notifications: {
|
|
230
249
|
enabled: true,
|
|
231
250
|
maxPerUser: 100,
|
|
@@ -243,7 +262,8 @@ export const config: AppConfig = {
|
|
|
243
262
|
enabled: true,
|
|
244
263
|
provider: "turnstile",
|
|
245
264
|
siteKey: "0x4AAAAAACJo9y9FxH8lqkGu"
|
|
246
|
-
}`:"{ enabled: false }"}
|
|
265
|
+
}`:"{ enabled: false }"},
|
|
266
|
+
support: supportConfig,
|
|
247
267
|
currency: ${e.demo?`{
|
|
248
268
|
// Demo mirrors the boilerplate's showcase config so geo\u2192currency
|
|
249
269
|
// switching can be demonstrated. Real users get a single-currency
|
|
@@ -263,7 +283,7 @@ export const config: AppConfig = {
|
|
|
263
283
|
}`:`{
|
|
264
284
|
base: "${e.defaultCurrency}",
|
|
265
285
|
list: [
|
|
266
|
-
{ symbol: "${
|
|
286
|
+
{ symbol: "${De[e.defaultCurrency].symbol}", name: "${De[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${De[e.defaultCurrency].place}", space: ${De[e.defaultCurrency].space} }
|
|
267
287
|
],
|
|
268
288
|
countryMap: {
|
|
269
289
|
default: "${e.defaultCurrency}"
|
|
@@ -287,33 +307,33 @@ export const config: AppConfig = {
|
|
|
287
307
|
},
|
|
288
308
|
ai: {
|
|
289
309
|
enabled: ${e.ai},
|
|
290
|
-
// AI
|
|
291
|
-
//
|
|
292
|
-
|
|
310
|
+
// Built-in AI: your app offers models under its OWN name, billed from user credits.
|
|
311
|
+
// Powered by OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup.
|
|
312
|
+
builtin: ${e.aiBuiltin},
|
|
313
|
+
// Let users connect their own provider API keys; runs on their key never use credits.
|
|
293
314
|
byok: ${e.aiByok},
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
// NOT maintained by the boilerplate.
|
|
298
|
-
"claude-opus-4-8": {
|
|
299
|
-
provider: "anthropic",
|
|
300
|
-
modelId: "claude-opus-4-8",
|
|
301
|
-
inputPerMTok: 5,
|
|
302
|
-
outputPerMTok: 25
|
|
303
|
-
}
|
|
304
|
-
},
|
|
305
|
-
credits: { creditsPerUsd: 100, margin: 1, fallbackRatePerMTok: { input: 5, output: 25 } },
|
|
315
|
+
// What every user starts on (their own choice, once made, always wins). Plain
|
|
316
|
+
// OpenRouter model ids.
|
|
317
|
+
defaults: { model: "anthropic/claude-opus-4.8" },
|
|
306
318
|
// Let end-users author their own AI schedules. Set to false to ship only the
|
|
307
319
|
// create-disabled view (existing schedules still list/run/edit/delete).
|
|
308
|
-
userSchedules: true
|
|
320
|
+
userSchedules: true,
|
|
321
|
+
// Server-side chat thread limits: at most \`cap\` stored threads per user (chat history lives in
|
|
322
|
+
// Mastra Memory threads; the server evicts the oldest-by-activity beyond the cap).
|
|
323
|
+
chats: {
|
|
324
|
+
cap: 20
|
|
325
|
+
},
|
|
326
|
+
// \`/chat\` page presentation. \`suggestions\` are prompt-starter chips shown on the empty chat;
|
|
327
|
+
// empty by default (starters are product copy you write for your users).
|
|
328
|
+
chat: {
|
|
329
|
+
suggestions: []
|
|
330
|
+
}
|
|
309
331
|
},
|
|
310
332
|
desktop: desktopConfig,
|
|
311
|
-
// Server-side keyword knowledge base over your knowledge/ docs. Off by default.
|
|
312
|
-
rag: ${p},
|
|
313
333
|
// Companion: your vendored companion daemon (apps/companion) that your users install to run their own subscription CLIs. Off by default.
|
|
314
|
-
companion: ${
|
|
334
|
+
companion: ${m},
|
|
315
335
|
// Outward MCP server exposing the capability layer to external agents. Off by default.
|
|
316
|
-
mcpServer: ${
|
|
336
|
+
mcpServer: ${w},
|
|
317
337
|
seo: {
|
|
318
338
|
description: "Production-ready SaaS application",
|
|
319
339
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -326,6 +346,12 @@ export const config: AppConfig = {
|
|
|
326
346
|
pricing: "/pricing",
|
|
327
347
|
onboarding: "/onboarding",
|
|
328
348
|
settings: "/settings/profile",
|
|
349
|
+
chat: "/chat",
|
|
350
|
+
schedules: "/schedules",
|
|
351
|
+
settingsModels: "/settings/models",
|
|
352
|
+
settingsIntegrations: "/settings/integrations",
|
|
353
|
+
settingsCompanions: "/settings/companions",
|
|
354
|
+
settingsMcp: "/settings/mcp",
|
|
329
355
|
notifications: "/notifications",
|
|
330
356
|
admin: "/admin/users"
|
|
331
357
|
}
|
|
@@ -343,35 +369,36 @@ export * from "./companion";
|
|
|
343
369
|
export * from "./footer";
|
|
344
370
|
export * from "./i18n";
|
|
345
371
|
export * from "./landing";
|
|
372
|
+
export * from "./nav-active";
|
|
346
373
|
export * from "./pricing";
|
|
347
374
|
export * from "./roles";
|
|
348
375
|
export * from "./section-tabs";
|
|
349
376
|
export * from "./tenancy";
|
|
350
|
-
`,
|
|
351
|
-
// TypeScript config index reads it directly: the
|
|
352
|
-
//
|
|
353
|
-
//
|
|
354
|
-
//
|
|
355
|
-
// index re-exports this as config.desktop.
|
|
377
|
+
`,R=at(e.projectDir,"packages/config/src/index.ts");await p(R,v),await p(at(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
378
|
+
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
379
|
+
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
380
|
+
// values once to rebrand - they are the same in dev and production, so they live in
|
|
381
|
+
// committed config, not env. The config index re-exports this as config.desktop.
|
|
356
382
|
|
|
357
383
|
export const desktopConfig = {
|
|
358
384
|
enabled: ${e.desktop},
|
|
359
|
-
appId: "${
|
|
360
|
-
productName: "${
|
|
361
|
-
protocol: "${
|
|
385
|
+
appId: "${g.appId}",
|
|
386
|
+
productName: "${g.productName}",
|
|
387
|
+
protocol: "${g.protocol}",
|
|
362
388
|
baseUrl: "${r}",
|
|
363
389
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
364
390
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
365
391
|
// it freely; it is a plain folder name, not a path.
|
|
366
392
|
dataFolder: "data",
|
|
367
|
-
// Public base URL the release workflow uploads to;
|
|
368
|
-
// \`<url>/latest.
|
|
369
|
-
|
|
393
|
+
// Public base URL the release workflow uploads to; electron-updater polls
|
|
394
|
+
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
395
|
+
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
396
|
+
autoUpdate: { url: "${l}" },
|
|
370
397
|
agents: {
|
|
371
|
-
// Feature toggles only. Agents
|
|
372
|
-
// through the @repo/agent-
|
|
373
|
-
// markdown prompt files you tune.
|
|
374
|
-
enabled: ${e.
|
|
398
|
+
// Feature toggles only. Agents run in the app's main process (companion supervision +
|
|
399
|
+
// the daemon transport bridge), driven through the @repo/agent-core seam - typed
|
|
400
|
+
// TypeScript wiring next to the markdown prompt files you tune.
|
|
401
|
+
enabled: ${e.desktop&&e.ai},
|
|
375
402
|
modelRegistry: { enabled: true },
|
|
376
403
|
// Provider ids that ship in this app (catalog ids like "anthropic", "openai").
|
|
377
404
|
// Omitted here, which ships them ALL; add \`providers: ["anthropic", ...]\` to trim
|
|
@@ -386,11 +413,16 @@ export const desktopConfig = {
|
|
|
386
413
|
userSchedules: true,
|
|
387
414
|
// Cap how many chat conversations are kept per agent on the user's machine;
|
|
388
415
|
// creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
|
|
389
|
-
maxChatsPerAgent: 20
|
|
416
|
+
maxChatsPerAgent: 20,
|
|
417
|
+
// Forbid the bundled companion daemon from connecting to your backend (the buyer
|
|
418
|
+
// connection lock). Default false: the app is local-first and connecting is an
|
|
419
|
+
// OPTIONAL, explicit user action. Set true for a structurally private product - the
|
|
420
|
+
// connect surface never renders AND the daemon refuses pairing.
|
|
421
|
+
connectionLock: false
|
|
390
422
|
}
|
|
391
423
|
};
|
|
392
|
-
`),await
|
|
393
|
-
// TypeScript config index reads it directly (the
|
|
424
|
+
`),await p(at(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
|
|
425
|
+
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
394
426
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
395
427
|
|
|
396
428
|
export const tenancyConfig = ${e.multiTenancy?`{
|
|
@@ -398,8 +430,14 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
398
430
|
organizationLimit: 5,
|
|
399
431
|
billingScope: "${e.billingScope}"
|
|
400
432
|
}`:"{ multiTenant: false }"};
|
|
401
|
-
`),
|
|
402
|
-
|
|
433
|
+
`),await p(at(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
|
|
434
|
+
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
435
|
+
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
436
|
+
// index re-exports this as config.support.
|
|
437
|
+
|
|
438
|
+
export const supportConfig = ${s};
|
|
439
|
+
`),e.desktop&&await Aa(e.projectDir,l,`${g.protocol}-updater`)}import{join as Ta}from"path";function _a(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function Ln(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(`
|
|
440
|
+
`)}async function to(e){let t=Ta(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let v=`import type { PricingConfig } from "@repo/config/types";
|
|
403
441
|
|
|
404
442
|
export const pricingConfig: PricingConfig = {
|
|
405
443
|
defaultPlan: "free",
|
|
@@ -428,7 +466,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
428
466
|
credits: { enabled: false },
|
|
429
467
|
products: { enabled: false, items: [] }
|
|
430
468
|
};
|
|
431
|
-
`;await
|
|
469
|
+
`;await p(t,v);return}let r=e.paymentProvider,o=_a(r),i=e.credits,a=!!e.ai,s=Ln({credits:5,rateLimit:100,withCredits:i,...a&&{maxSchedules:3}}),u=Ln({credits:10,rateLimit:1e3,withCredits:i,...a&&{maxSchedules:10}}),g=Ln({credits:50,rateLimit:5e3,withCredits:i}),l=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
470
|
+
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
471
|
+
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
472
|
+
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
473
|
+
`;i&&n!=="USD"&&console.warn(`
|
|
474
|
+
!! ${n} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
475
|
+
!! plan prices and credit purchases are denominated in ${n}. At the shipped economics 1 credit
|
|
476
|
+
!! carries ~0.42 USD of AI cost - verify every ${n} price still covers it (see the comment on the
|
|
477
|
+
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
478
|
+
`);let m=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
479
|
+
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
480
|
+
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
481
|
+
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
482
|
+
// full utilization runs you at a loss.
|
|
483
|
+
${l} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",w=`import type { PricingConfig } from "@repo/config/types";
|
|
432
484
|
|
|
433
485
|
export const pricingConfig: PricingConfig = {
|
|
434
486
|
defaultPlan: "free",
|
|
@@ -452,7 +504,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
452
504
|
amounts: { ${n}: 0 }
|
|
453
505
|
}
|
|
454
506
|
],
|
|
455
|
-
${
|
|
507
|
+
${s}
|
|
456
508
|
},
|
|
457
509
|
{
|
|
458
510
|
id: "starter",
|
|
@@ -467,18 +519,18 @@ ${a}
|
|
|
467
519
|
],
|
|
468
520
|
prices: [
|
|
469
521
|
{
|
|
470
|
-
${
|
|
522
|
+
${o}
|
|
471
523
|
interval: "month",
|
|
472
524
|
amounts: { ${n}: 9 }
|
|
473
525
|
},
|
|
474
526
|
{
|
|
475
|
-
${
|
|
527
|
+
${o}
|
|
476
528
|
interval: "year",
|
|
477
529
|
amounts: { ${n}: 90 },
|
|
478
530
|
anchorAmounts: { ${n}: 109 }
|
|
479
531
|
}
|
|
480
532
|
],
|
|
481
|
-
${
|
|
533
|
+
${u}
|
|
482
534
|
},
|
|
483
535
|
{
|
|
484
536
|
id: "pro",
|
|
@@ -496,33 +548,33 @@ ${s}
|
|
|
496
548
|
],
|
|
497
549
|
prices: [
|
|
498
550
|
{
|
|
499
|
-
${
|
|
551
|
+
${o}
|
|
500
552
|
interval: "month",
|
|
501
553
|
amounts: { ${n}: 29 },
|
|
502
554
|
anchorAmounts: { ${n}: 39 },
|
|
503
555
|
featured: true
|
|
504
556
|
},
|
|
505
557
|
{
|
|
506
|
-
${
|
|
558
|
+
${o}
|
|
507
559
|
interval: "year",
|
|
508
560
|
amounts: { ${n}: 290 },
|
|
509
561
|
anchorAmounts: { ${n}: 349 }
|
|
510
562
|
}
|
|
511
563
|
],
|
|
512
|
-
${
|
|
564
|
+
${g}
|
|
513
565
|
}
|
|
514
566
|
],
|
|
515
|
-
${
|
|
567
|
+
${m},
|
|
516
568
|
products: {
|
|
517
569
|
enabled: false,
|
|
518
570
|
items: []
|
|
519
571
|
}
|
|
520
572
|
};
|
|
521
|
-
`;await
|
|
522
|
-
`)}function
|
|
523
|
-
`)}async function
|
|
524
|
-
`+
|
|
525
|
-
`+
|
|
573
|
+
`;await p(t,w)}var Oa={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"}]};function Ca(e){let t=ue[e];return t.envVars.map((n,r)=>({key:n.name,...r===0?{comment:`# TODO: Add your ${t.label} OAuth credentials`}:{}}))}var Da={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 st(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function ct(e,t){for(let n of e)n.comment&&t.push(n.comment),n.defaultValue!==void 0?t.push(`${n.key}=${n.defaultValue}`):t.push(`#${n.key}=`)}function Un(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function ro(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Na(e){let{architecture:t,deploymentTarget:n}=e;return t==="fullstack"?n==="vercel"?{frontend:"https://your-app.vercel.app",backend:"https://your-app.vercel.app"}:n==="node"?{frontend:"https://your-app.example.com",backend:"https://your-app.example.com"}:null:{frontend:"https://your-app.example.com",backend:"https://your-app.example.com/api"}}function Qt(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function no(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:o}=ro(e),i=[];e.architecture==="separate"?i.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${o}`):i.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${o}`),i.push("","# Database"),ct(st(Y[e.databaseProvider].envVars,n),i),i.push("","# Cache"),ct(st(ae[e.cacheProvider].envVars,n),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Qt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Qt(i,"CONTENT_API_KEY",Un(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Qt(i,"INNGEST_EVENT_KEY",Un(32),t),Qt(i,"INNGEST_SIGNING_KEY",Un(32),t),i.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(i.push("","# API Port (standalone backend)","API_PORT=3010"),i.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 a=Oa[e.emailProvider];if(a&&(i.push("","# Email"),ct(st(a,n),i)),e.paymentProvider!=="none"){let s=Da[e.paymentProvider];s&&(i.push("","# Payment"),ct(st(s,n),i))}if(e.socialProviders.length>0){i.push("","# Social auth");for(let s of e.socialProviders)ct(st(Ca(s),n),i)}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),ct(st([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),i)),i.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="),i.push("","# AI base - provider API keys (optional)","# Enable config.ai in packages/config and set the key for your chosen provider.","# OPENROUTER_API_KEY above also works as an AI provider key.","#ANTHROPIC_API_KEY=","#OPENAI_API_KEY="),i.push(""),i.join(`
|
|
574
|
+
`)}function $a(e){let{apiUrl:t}=ro(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],o=Na(e);return o&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${o.backend}`),r.push(""),r.join(`
|
|
575
|
+
`)}async function oo(e){let t=$a(e);await p(`${e.projectDir}/.env`,t+`
|
|
576
|
+
`+no(e,"env")),await p(`${e.projectDir}/.env.example`,t+`
|
|
577
|
+
`+no(e,"example"))}import{join as La}from"path";async function io(e){let t=[...e.dockerServices];if(Y[e.databaseProvider].managed&&(t=t.filter(i=>i!=="postgres")),ae[e.cacheProvider].managed&&(t=t.filter(i=>i!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
526
578
|
image: postgres:18-alpine
|
|
527
579
|
ports:
|
|
528
580
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -558,16 +610,16 @@ ${o?" credits: { enabled: true }":" credits: { enabled: false }"},
|
|
|
558
610
|
image: inngest/inngest:v1.17.4
|
|
559
611
|
ports:
|
|
560
612
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
561
|
-
command: inngest dev`);let
|
|
613
|
+
command: inngest dev`);let o=`services:
|
|
562
614
|
${n.join(`
|
|
563
615
|
|
|
564
616
|
`)}
|
|
565
|
-
`;return r.length>0&&(
|
|
617
|
+
`;return r.length>0&&(o+=`
|
|
566
618
|
volumes:
|
|
567
619
|
${r.join(`
|
|
568
620
|
`)}
|
|
569
|
-
`),await
|
|
570
|
-
`)}import{join as
|
|
621
|
+
`),await p(La(e.projectDir,"infra/docker-compose.yml"),o),!0}import{join as Ua}from"path";function ja(e){let t=[];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"}});let n=e.frontend==="nextjs"?"Next.js":"Nuxt";if(t.push({type:"node-terminal",request:"launch",name:n,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend==="nextjs"?"next":"nuxt"}`,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 Ma(e){let t=e.frontend==="nextjs"?"Next.js":"Nuxt",n=[];return e.architecture==="separate"?n.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):n.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),n}async function ao(e){let t={version:"0.2.0",configurations:ja(e),compounds:Ma(e)};await p(Ua(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
622
|
+
`)}import{join as Va}from"path";async function so(e){if(e.architecture!=="separate")return;await p(Va(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
571
623
|
import app from "@repo/api";
|
|
572
624
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
573
625
|
|
|
@@ -598,12 +650,12 @@ bootstrap().catch((error) => {
|
|
|
598
650
|
logger.error("[Backend] Fatal error", error);
|
|
599
651
|
process.exit(1);
|
|
600
652
|
});
|
|
601
|
-
`)}import{readFile as
|
|
602
|
-
export const pool = db.$client;`,
|
|
653
|
+
`)}import{readFile as Fa}from"fs/promises";import{join as Ba}from"path";var jn='import { drizzle } from "drizzle-orm/node-postgres";',Mn=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
654
|
+
export const pool = db.$client;`,Ga={postgres:{importLine:jn,instantiation:Mn},neon:{importLine:`import { neon } from "@neondatabase/serverless";
|
|
603
655
|
import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
|
|
604
656
|
export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
605
657
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
606
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
658
|
+
export const db = drizzle(client, { schema });`}};async function co(e){let t=Ba(e.projectDir,"packages/database/src/index.ts"),n=await Fa(t,"utf-8");if(!n.includes(jn)||!n.includes(Mn))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 r=Ga[e.databaseProvider],o=n.replace(jn,r.importLine).replace(Mn,r.instantiation);await p(t,o)}import{join as en}from"path";async function po(e){switch(e.cacheProvider){case"redis":await Ka(e),await Ha(e);break;case"upstash":await za(e),await Ja(e);break}}async function Ka(e){await p(en(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
607
659
|
import { Redis } from "ioredis";
|
|
608
660
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
609
661
|
import { env } from "./env";
|
|
@@ -732,7 +784,7 @@ export async function closeRedis() {
|
|
|
732
784
|
closed = true;
|
|
733
785
|
}
|
|
734
786
|
}
|
|
735
|
-
`)}async function
|
|
787
|
+
`)}async function Ha(e){await p(en(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
736
788
|
import { redis } from "./redis";
|
|
737
789
|
|
|
738
790
|
export class MutexTimeoutError extends Error {
|
|
@@ -769,7 +821,7 @@ export async function withMutex<T>(
|
|
|
769
821
|
await mutex.release();
|
|
770
822
|
}
|
|
771
823
|
}
|
|
772
|
-
`)}async function
|
|
824
|
+
`)}async function za(e){await p(en(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
773
825
|
import type { Store } from "hono-rate-limiter";
|
|
774
826
|
import { env } from "./env";
|
|
775
827
|
|
|
@@ -887,7 +939,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
887
939
|
|
|
888
940
|
/** No persistent connection to close with Upstash REST. */
|
|
889
941
|
export async function closeRedis(): Promise<void> {}
|
|
890
|
-
`)}async function
|
|
942
|
+
`)}async function Ja(e){await p(en(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
891
943
|
import { redis } from "./redis";
|
|
892
944
|
|
|
893
945
|
export class MutexTimeoutError extends Error {
|
|
@@ -932,7 +984,7 @@ export async function withMutex<T>(
|
|
|
932
984
|
await lock.release();
|
|
933
985
|
}
|
|
934
986
|
}
|
|
935
|
-
`)}async function
|
|
987
|
+
`)}async function lo(e){await p(`${e.projectDir}/packages/runtime/src/env.ts`,qa(e))}function qa(e){return`import { z } from "zod";
|
|
936
988
|
|
|
937
989
|
const EnvSchema = z.object({
|
|
938
990
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -943,6 +995,7 @@ const EnvSchema = z.object({
|
|
|
943
995
|
TRUSTED_ORIGINS: z.string().optional(),
|
|
944
996
|
AUTH_COOKIE_DOMAIN: z.string().optional(),
|
|
945
997
|
|
|
998
|
+
DATABASE_URL: z.url(),
|
|
946
999
|
${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
947
1000
|
UPSTASH_REDIS_REST_TOKEN: z.string(),`:" REDIS_URL: z.string(),"}
|
|
948
1001
|
|
|
@@ -1026,7 +1079,9 @@ ${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
|
1026
1079
|
|
|
1027
1080
|
ANTHROPIC_API_KEY: z.string().optional(),
|
|
1028
1081
|
OPENAI_API_KEY: z.string().optional(),
|
|
1029
|
-
OPENROUTER_API_KEY: z.string().optional()
|
|
1082
|
+
OPENROUTER_API_KEY: z.string().optional(),
|
|
1083
|
+
|
|
1084
|
+
MASTRA_TELEMETRY_DISABLED: z.string().optional()
|
|
1030
1085
|
});
|
|
1031
1086
|
|
|
1032
1087
|
export const env = (() => {
|
|
@@ -1053,13 +1108,13 @@ export const env = (() => {
|
|
|
1053
1108
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1054
1109
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1055
1110
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1056
|
-
`}import{readFile as
|
|
1057
|
-
`)}function
|
|
1058
|
-
`)}var
|
|
1059
|
-
`))}}import{readFile as
|
|
1060
|
-
`);let
|
|
1111
|
+
`}import{readFile as Ya}from"fs/promises";import{join as le}from"path";var tn={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function lt(e){let t=await Ya(e,"utf-8");return JSON.parse(t)}async function dt(e,t){await p(e,JSON.stringify(t,null," ")+`
|
|
1112
|
+
`)}function Rt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function pt(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function uo(e){await Wa(e),await Xa(e),await Za(e),await Qa(e),e.frontend==="nextjs"?await ts(e):await es(e)}async function Wa(e){let t=le(e.projectDir,"packages/api/package.json"),n=await lt(t);Rt(n,["sharp","@types/sharp"]),await dt(t,n)}async function Xa(e){let t=le(e.projectDir,"packages/runtime/package.json"),n=await lt(t);e.cacheProvider==="upstash"&&(Rt(n,["ioredis","rate-limit-redis","redis-semaphore"]),pt(n,"@upstash/redis",tn["@upstash/redis"]),pt(n,"@upstash/lock",tn["@upstash/lock"])),await dt(t,n)}async function Za(e){let t=le(e.projectDir,"packages/database/package.json"),n=await lt(t);e.databaseProvider==="neon"?(Rt(n,["pg","@types/pg"]),pt(n,"@neondatabase/serverless",tn["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Rt(n,["pg","@types/pg"]),pt(n,"postgres",tn.postgres)),await dt(t,n)}async function Qa(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/backend/package.json"),n=await lt(t);e.deploymentTarget!=="node"&&Rt(n,["@hono/node-server"]),await dt(t,n)}async function es(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-nuxt");await Dn(le(t,"server/api/[...paths].ts"),t);let n=le(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}async function ts(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-next");await Dn(le(t,"app/api/[[...rest]]/route.ts"),t);let n=le(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}import{readFile as fo}from"fs/promises";import{join as go}from"path";async function ho(e){let t=go(e.projectDir,"turbo.json"),n;try{n=await fo(t,"utf-8")}catch{return}let r=JSON.parse(n),o=r.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",a=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),s=!1;if(Array.isArray(o.env)){let u=o.env.filter(g=>g!==i);u.length!==o.env.length&&(o.env=u,s=!0)}if(Array.isArray(o.outputs)){let u=o.outputs.filter(g=>!a.has(g));u.length!==o.outputs.length&&(o.outputs=u,s=!0)}s&&await p(t,JSON.stringify(r,null," ")+`
|
|
1113
|
+
`)}var ns=["base.json","node.json","next.json"],mo="GenerateSaaS ";async function yo(e){if(!e.demo)for(let t of ns){let n=go(e.projectDir,"tooling/typescript",t),r;try{r=await fo(n,"utf-8")}catch{continue}let o=JSON.parse(r);typeof o.display!="string"||!o.display.startsWith(mo)||(o.display=o.display.slice(mo.length),await p(n,JSON.stringify(o,null," ")+`
|
|
1114
|
+
`))}}import{readFile as rs,rm as os}from"fs/promises";import{existsSync as wo}from"fs";import{join as vo}from"path";async function ko(e){if(e.frontend==="nuxt")return;let t=vo(e.projectDir,"packages/i18n/package.json");if(!wo(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await rs(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),o=!1;if(n.exports)for(let a of["./module","./nuxt"])a in n.exports&&(delete n.exports[a],o=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],o=!0),o&&await p(t,JSON.stringify(n,null," ")+`
|
|
1115
|
+
`);let i=vo(e.projectDir,"packages/i18n/nuxt");if(r&&!wo(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await os(i,{recursive:!0,force:!0})}import{readFile as So,rm as is}from"fs/promises";import{join as nn}from"path";async function Eo(e){e.cacheProvider==="upstash"&&await Promise.all([bo(nn(e.projectDir,"packages/runtime/tests/setup.ts")),bo(nn(e.projectDir,"packages/mail/tests/setup.ts")),as(e.projectDir),is(nn(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function bo(e){let t;try{t=await So(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let n=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1061
1116
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1062
|
-
`);
|
|
1117
|
+
`);n!==t&&await p(e,n)}async function as(e){let t=nn(e,"packages/api/tests/setup.ts"),n;try{n=await So(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let r=n;r=r.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1063
1118
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1064
1119
|
`),r=r.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1065
1120
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1080,253 +1135,100 @@ vi.mock("@upstash/lock", () => {
|
|
|
1080
1135
|
return { Lock };
|
|
1081
1136
|
});
|
|
1082
1137
|
|
|
1083
|
-
$1`),r!==n&&await
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1138
|
+
$1`),r!==n&&await p(t,r)}import{readdir as Hn,readFile as M,rm as U}from"fs/promises";import{join as y}from"path";import{readFile as Io,readdir as ss,rm as _e}from"fs/promises";import{join as F}from"path";async function Vn(e){if(e.mcpServer)return;let t=e.projectDir,n="stripMcpServer";await _e(F(t,"packages/api/src/routes/internal/ai/mcp.ts")),await _e(F(t,"packages/api/tests/routes/mcp.test.ts")),await _e(F(t,"packages/auth/src/mcp.ts"));let r=e.frontend==="nextjs",o=F(t,r?"apps/web-next/app/.well-known":"apps/web-nuxt/server/routes/.well-known");await _e(F(o,"oauth-authorization-server"),{recursive:!0}),await _e(F(o,"oauth-protected-resource"),{recursive:!0}),r||(await _e(F(o,"oauth-authorization-server.ts")),await _e(F(o,"oauth-protected-resource.ts"))),(await ss(o)).length===0&&await _e(o,{recursive:!0});let i=F(t,"packages/api/src/routes/internal/index.ts");await I(i,`import mcpRoutes from "./ai/mcp";
|
|
1139
|
+
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await Zt(i);let a=F(t,"packages/api/src/index.ts");await I(a,`import { mcpDiscoveryRoutes } from "./routes/internal/ai/mcp";
|
|
1140
|
+
`,"","api index mcp discovery import",n),await I(a,`
|
|
1141
|
+
// The outward MCP server's OAuth discovery documents, mounted at the APP ROOT (not under the API
|
|
1142
|
+
// base path): an MCP agent resolves \`/.well-known/oauth-*\` against the site origin (RFC 8414 /
|
|
1143
|
+
// RFC 9728). A standalone backend serves them at its origin directly, and each web frontend
|
|
1144
|
+
// forwards its root \`/.well-known/oauth-*\` paths to this app. Gated like the \`/mcp\` endpoint
|
|
1145
|
+
// itself, so the routes are absent entirely when the feature is off.
|
|
1146
|
+
if (config.mcpServer?.enabled) {
|
|
1147
|
+
app.route("/", mcpDiscoveryRoutes);
|
|
1148
|
+
}
|
|
1149
|
+
`,"","api index mcp discovery mount",n);let s=F(t,"packages/auth/src/config.ts");await I(s,` magicLink,
|
|
1093
1150
|
mcp,
|
|
1094
1151
|
organization,`,` magicLink,
|
|
1095
|
-
organization,`,"auth config mcp plugin import",n),await
|
|
1152
|
+
organization,`,"auth config mcp plugin import",n),await I(s,` // Outward MCP server: turns Better Auth into an OAuth 2.1 provider so an
|
|
1096
1153
|
// external agent (Hermes/OpenClaw) can authenticate and drive the app's
|
|
1097
1154
|
// capability layer over MCP. Brings the oauthApplication/oauthAccessToken/
|
|
1098
1155
|
// oauthConsent tables (run \`pnpm auth:generate\` after toggling).
|
|
1099
1156
|
...(config.mcpServer?.enabled
|
|
1100
1157
|
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1101
1158
|
: []),
|
|
1102
|
-
`,"","auth config mcp plugin block",n);let
|
|
1103
|
-
`);let
|
|
1104
|
-
`);let
|
|
1105
|
-
|
|
1106
|
-
`,"","settings-store.ts relay import",t),await x(i," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>@<modelId>` is also accepted, so a default/fallback model that points\n * at a paired CLI persists (the run path resolves it, and the daemon handles an offline device).\n * Without this, the `@`-separated key is neither a registry key nor a `provider::modelId` key, so\n * it would silently clear to `null` on save and vanish on reload.\n","","settings-store.ts COMPANION docstring bullet",t),await x(i," *\n * When `opts.allowCompanion` is `false`, a companion key is REJECTED even when the companion is\n * enabled - used by the builder-task surfaces, whose runs are background/cloud-only and can never\n * dispatch to a device-bound CLI.\n","","settings-store.ts opts.allowCompanion docstring paragraph",t),await x(i," * @param opts - `allowCompanion` (default `true`) controls companion-key acceptance.\n","","settings-store.ts @param opts",t),await x(i,`export function validModelKey(
|
|
1107
|
-
key: string | null | undefined,
|
|
1108
|
-
opts: { allowCompanion?: boolean } = {}
|
|
1109
|
-
): string | null {
|
|
1110
|
-
`,`export function validModelKey(key: string | null | undefined): string | null {
|
|
1111
|
-
`,"settings-store.ts validModelKey signature",t),await x(i,` if (
|
|
1112
|
-
opts.allowCompanion !== false &&
|
|
1113
|
-
config.companion?.enabled === true &&
|
|
1114
|
-
parseCompanionKey(key) !== null
|
|
1115
|
-
) {
|
|
1116
|
-
return key;
|
|
1117
|
-
}
|
|
1118
|
-
`,"","settings-store.ts companion-key branch",t);let o=mt(e,"packages/api/src/ai/task-run.ts");await x(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1119
|
-
`,"","task-run.ts relay import",t),await x(o,`/** Whether a chain link is usable for a task run: present and not a companion (device) key. */
|
|
1120
|
-
`,`/** Whether a chain link is usable for a task run: a present, non-empty key. */
|
|
1121
|
-
`,"task-run.ts usableTaskModelKey docstring",t),await x(o,` return typeof key === "string" && key.length > 0 && parseCompanionKey(key) === null;
|
|
1122
|
-
`,` return typeof key === "string" && key.length > 0;
|
|
1123
|
-
`,"task-run.ts usableTaskModelKey body",t),await x(o,` * override, then the builder's \`defaults.web.model\`, then the acting user's account default -
|
|
1124
|
-
* skipping companion (device-bound) links, which are valid for chat but never for a background
|
|
1125
|
-
* task - and delegating the final resolution to {@link resolveChatRun}, which owns BYOK/platform
|
|
1126
|
-
`," * override, then the builder's `defaults.web.model`, then the acting user's account default,\n * delegating the final resolution to {@link resolveChatRun}, which owns BYOK/platform\n","task-run.ts resolveTaskRun docstring model chain",t);let a=mt(e,"packages/api/src/routes/internal/ai/tasks-router.ts");await x(a,` modelKey: validModelKey(override?.modelKey ?? null, { allowCompanion: false }),
|
|
1127
|
-
`,` modelKey: validModelKey(override?.modelKey ?? null),
|
|
1128
|
-
`,"tasks-router.ts listTaskOverrides validModelKey",t),await x(a,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey, { allowCompanion: false }) === null) {
|
|
1129
|
-
`,` if (typeof body.modelKey === "string" && validModelKey(body.modelKey) === null) {
|
|
1130
|
-
`,"tasks-router.ts putTask validModelKey",t)}var va=["companion:export","companion:verify","companion:publish"];async function yn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await ke(we(t,"apps/companion"),{recursive:!0}),await ke(we(t,"scripts/companion-export"),{recursive:!0}),await ba(t),await ke(we(t,"packages/api/src/relay"),{recursive:!0}),await ke(we(t,"packages/api/tests/relay"),{recursive:!0}),await ke(we(t,"packages/api/src/routes/internal/companion.ts")),await ke(we(t,"packages/api/src/routes/internal/companion-transport.ts")),await ke(we(t,"packages/api/tests/routes/companion.test.ts")),await ke(we(t,"packages/api/tests/routes/companion-transport.test.ts")),await Fr(t,n);let r=Ut(e);await ut(t,r,"companion",`/${r}/companion`,n,"Companions"),await ut(t,r,"companion-publish",`/${r}/companion-publish`,n)}async function ba(e){await vn(e,va)}var ka=new Set(["ci.yml","tauri-release.yml"]),wa=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:units","playground:test:build","playground:test:companion"];async function Kr(e){let t=y(e.projectDir,".github/workflows"),n=await bn(t).catch(()=>[]);for(let r of n)ka.has(r)||await _(y(t,r),{recursive:!0,force:!0})}async function vn(e,t){let n=y(e,"package.json"),r=JSON.parse(await j(n,"utf-8"));if(!r.scripts)return!1;let i=!1;for(let o of t)o in r.scripts&&(delete r.scripts[o],i=!0);return i&&await l(n,JSON.stringify(r,null," ")+`
|
|
1131
|
-
`),i}async function Gr(e){let t=[...wa];St(e)||t.push("infra","infra:stop"),await vn(e.projectDir,t)}async function Hr(e){let t=y(e.projectDir,"package.json"),n=await j(t,"utf-8"),r=JSON.parse(n);!r.scripts||!("dev"in r.scripts)||(r.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(r,null," ")+`
|
|
1132
|
-
`))}async function zr(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await _(y(e.projectDir,t),{recursive:!0,force:!0})}async function Yr(e){e.docs||await _(y(e.projectDir,"apps/docs"),{recursive:!0})}async function Jr(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await _(y(e.projectDir,t),{recursive:!0,force:!0}),await _(y(e.projectDir,"docs/index.mdx")),!e.desktop)await _(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!e.desktopAi){await _(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await j(n,"utf-8"));r.pages=r.pages.filter(i=>i!=="ai"),await l(n,`${JSON.stringify(r,null,2)}
|
|
1133
|
-
`)}}async function qr(e){if(e.desktop)return;await _(y(e.projectDir,"apps/tauri"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let n of await bn(t,{withFileTypes:!0}))n.isDirectory()&&await _(y(t,n.name,"desktop.json"),{force:!0});await _(y(e.projectDir,".github/workflows/tauri-release.yml"))}async function Wr(e){let t=e.desktop&&e.desktopAi,n=t||e.companion;t||await _(y(e.projectDir,"packages/agent-runtime"),{recursive:!0}),n||await _(y(e.projectDir,"packages/agent-core"),{recursive:!0})}function C(e,t,n,r){let i=e.indexOf(t);if(i===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,i+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,i)+n+e.slice(i+t.length)}async function Xr(e){if(!e.desktop||e.desktopAi)return;let t=e.projectDir;await _(y(t,"apps/tauri/sidecar"),{recursive:!0}),await _(y(t,"apps/tauri/tsconfig.sidecar.json")),await _(y(t,"apps/tauri/tsup.sidecar.config.ts")),await _(y(t,"apps/tauri/tests/sidecar"),{recursive:!0}),await _(y(t,"apps/tauri/src-tauri/src/daemon.rs")),await _(y(t,"apps/tauri/scripts/stage-sidecar.mjs")),await _(y(t,"apps/tauri/scripts/sign-nested.mjs")),await _(y(t,"apps/tauri/resources/ai-skills"),{recursive:!0}),await _(y(t,"apps/tauri/src-tauri/resources"),{recursive:!0,force:!0});for(let a of["apps/tauri/src/screens/agents","apps/tauri/src/screens/integrations","apps/tauri/src/screens/ai","apps/tauri/src/screens/schedules.tsx","apps/tauri/src/hooks/use-ai.ts","apps/tauri/src/hooks/use-ai-chat.ts","apps/tauri/src/hooks/use-ai-resources.ts","apps/tauri/src/hooks/use-ai-scope.ts","apps/tauri/src/hooks/use-ai-terminal.ts","apps/tauri/src/hooks/use-xterm.ts","apps/tauri/src/hooks/use-async-resource.ts","apps/tauri/src/lib/ai.ts","apps/tauri/src/lib/ai-tab-state.ts","apps/tauri/src/lib/chat-prefs.ts","apps/tauri/src/lib/side-panel-state.ts","apps/tauri/src/lib/task-settings-sync.ts","apps/tauri/src/lib/bridge/ai.ts","apps/tauri/src/lib/bridge/events.ts","apps/tauri/src/lib/bridge/http.ts","apps/tauri/src/lib/bridge/wire-types.ts","apps/tauri/src/lib/bridge/control-info.ts","apps/tauri/src/lib/bridge/status.ts","apps/tauri/src/lib/bridge/types.ts","apps/tauri/src/lib/bridge/deps.ts","apps/tauri/src/components/side-panel-dock.tsx","apps/tauri/src/components/side-panel.tsx","apps/tauri/src/config/side-panels.tsx"])await _(y(t,a),{recursive:!0});for(let a of["apps/tauri/tests/ai-import-boundary.test.ts","apps/tauri/tests/bridge/ai-surface.test.ts","apps/tauri/tests/bridge/control-info.test.ts","apps/tauri/tests/bridge/events.test.ts","apps/tauri/tests/bridge/http.test.ts","apps/tauri/tests/bridge/reconnect.test.ts","apps/tauri/tests/renderer/lib/ai.test.ts","apps/tauri/tests/renderer/lib/ai-tab-state.test.ts","apps/tauri/tests/renderer/lib/chat-prefs.test.ts","apps/tauri/tests/renderer/lib/side-panel-state.test.ts","apps/tauri/tests/renderer/lib/task-settings-sync.test.ts","apps/tauri/tests/renderer/terminal-tools.test.ts","apps/tauri/tests/renderer/use-model-picker.test.ts"])await _(y(t,a));let n=y(t,"apps/tauri/package.json"),r=JSON.parse(await j(n,"utf-8")),i=["@repo/ai","@repo/agent-runtime","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit","ws","@hono/node-server"];for(let a of i){if(!r.dependencies||!(a in r.dependencies))throw new Error(`stripDesktopAi: expected ${a} in apps/tauri dependencies (boilerplate drift).`);delete r.dependencies[a]}for(let a of["@types/ws","tsup"]){if(!r.devDependencies||!(a in r.devDependencies))throw new Error(`stripDesktopAi: expected ${a} in apps/tauri devDependencies (boilerplate drift).`);delete r.devDependencies[a]}if(!r.scripts||!("sidecar:stage"in r.scripts))throw new Error("stripDesktopAi: expected the sidecar:stage script in apps/tauri package.json (boilerplate drift).");if(delete r.scripts["sidecar:stage"],r.scripts["check-types"]!=="tsc -p tsconfig.json --noEmit && tsc -p tsconfig.sidecar.json --noEmit")throw new Error("stripDesktopAi: expected the two-tsconfig check-types script in apps/tauri package.json (boilerplate drift).");r.scripts["check-types"]="tsc -p tsconfig.json --noEmit",await l(n,JSON.stringify(r,null,2)+`
|
|
1134
|
-
`),await _a(t);let o=y(t,"packages/i18n/translations");for(let a of await bn(o,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=y(o,a.name,"desktop.json"),d=await j(s,"utf-8").catch(()=>null);if(d===null)continue;let m=JSON.parse(d),p=!1;for(let f of["agents","ai_hub","schedules","integrations"])f in m&&(delete m[f],p=!0);p&&await l(s,JSON.stringify(m,null," ")+`
|
|
1135
|
-
`)}}var Sa=`/**
|
|
1136
|
-
* Assembles a full bridge over the injected {@link BridgeDeps} seams. Wires the control-info source,
|
|
1137
|
-
* the engine HTTP transport, the shared status store, the event hub, the host auth-token sync, the
|
|
1138
|
-
* native surface (registering the reconnect auth resync via the hub), and the ai surface (folding in
|
|
1139
|
-
* the native workspace picker). The four \`@tauri-apps\` primitives are injected so a bridge can be built
|
|
1140
|
-
* against fake transports in tests; this factory imports the real plugin functions directly, which the
|
|
1141
|
-
* shell webview satisfies.
|
|
1142
|
-
*
|
|
1143
|
-
* @param deps - The \`fetch\`, \`WebSocket\`, \`invoke\`, and \`listen\` seams.
|
|
1144
|
-
* @returns The assembled bridge and its status store.
|
|
1145
|
-
*/
|
|
1146
|
-
export function createBridge(deps: BridgeDeps): { bridge: Bridge; status: StatusStore } {
|
|
1147
|
-
const clientId = crypto.randomUUID()
|
|
1148
|
-
const source = createControlSource(deps)
|
|
1149
|
-
const http = createEngineHttp({ source, fetchFn: deps.fetchFn, clientId })
|
|
1150
|
-
const status = createStatusStore()
|
|
1151
|
-
const events = createEngineEvents({
|
|
1152
|
-
source,
|
|
1153
|
-
http,
|
|
1154
|
-
WebSocketCtor: deps.WebSocketCtor,
|
|
1155
|
-
clientId,
|
|
1156
|
-
status
|
|
1157
|
-
})
|
|
1158
|
-
const hostAuthSync = createHostAuthSync({ source, fetchFn: deps.fetchFn, clientId })
|
|
1159
|
-
const { native, pickWorkspace } = createNativeBridge({
|
|
1160
|
-
invoke: deps.invoke,
|
|
1161
|
-
listen: deps.listen,
|
|
1162
|
-
openUrl,
|
|
1163
|
-
isPermissionGranted,
|
|
1164
|
-
requestPermission,
|
|
1165
|
-
sendNotification: (options) => sendNotification(options),
|
|
1166
|
-
checkUpdate: () => check(),
|
|
1167
|
-
relaunch,
|
|
1168
|
-
openDialog: (options) => open(options),
|
|
1169
|
-
hostAuthSync,
|
|
1170
|
-
registerAuthResync: events.syncAuthToken,
|
|
1171
|
-
isDev: import.meta.env.DEV
|
|
1172
|
-
})
|
|
1173
|
-
const ai = createAiBridge({ http, events, pickWorkspace })
|
|
1174
|
-
return { bridge: { ...native, ai }, status }
|
|
1175
|
-
}`,Ea=`/**
|
|
1176
|
-
* Assembles the native bridge over the injected Tauri command/event seams. The \`invoke\` and \`listen\`
|
|
1177
|
-
* primitives are injected so a bridge can be built against fakes in tests; this factory imports the
|
|
1178
|
-
* real plugin functions (opener / notification / updater / process / dialog) directly, which the
|
|
1179
|
-
* shell webview satisfies.
|
|
1180
|
-
*
|
|
1181
|
-
* @param deps - The \`invoke\` and \`listen\` seams.
|
|
1182
|
-
* @returns The assembled native bridge.
|
|
1183
|
-
*/
|
|
1184
|
-
export function createBridge(deps: {
|
|
1185
|
-
invoke: <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>
|
|
1186
|
-
listen: (event: string, handler: (event: { payload: unknown }) => void) => Promise<() => void>
|
|
1187
|
-
}): { bridge: Bridge } {
|
|
1188
|
-
const { native } = createNativeBridge({
|
|
1189
|
-
invoke: deps.invoke,
|
|
1190
|
-
listen: deps.listen,
|
|
1191
|
-
openUrl,
|
|
1192
|
-
isPermissionGranted,
|
|
1193
|
-
requestPermission,
|
|
1194
|
-
sendNotification: (options) => sendNotification(options),
|
|
1195
|
-
checkUpdate: () => check(),
|
|
1196
|
-
relaunch,
|
|
1197
|
-
openDialog: (options) => open(options),
|
|
1198
|
-
isDev: import.meta.env.DEV
|
|
1199
|
-
})
|
|
1200
|
-
return { bridge: native }
|
|
1201
|
-
}`,Aa=`/** The four production seams: \`globalThis\` fetch/WebSocket + the real Tauri command/event primitives. */
|
|
1202
|
-
function productionDeps(): BridgeDeps {
|
|
1203
|
-
return {
|
|
1204
|
-
fetchFn: (input, init) => fetch(input, init),
|
|
1205
|
-
WebSocketCtor: WebSocket,
|
|
1206
|
-
invoke,
|
|
1207
|
-
listen: (event, handler) => tauriListen(event, handler)
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1159
|
+
`,"","auth config mcp plugin block",n);let u=F(t,"packages/auth/package.json"),g=JSON.parse(await Io(u,"utf-8"));if(!g.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);Xt(g.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await p(u,JSON.stringify(g,null," ")+`
|
|
1160
|
+
`);let l=F(t,"packages/api/package.json"),m=JSON.parse(await Io(l,"utf-8"));if(!m.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);Xt(m.dependencies,"@mastra/mcp","@mastra/mcp in packages/api dependencies",n),Xt(m.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await p(l,JSON.stringify(m,null," ")+`
|
|
1161
|
+
`);let w=it(e);if(await jr(t,w,"companion-agent-mcp",`/${w}/companion-agent-mcp`,n,"MCP"),await I(F(t,`docs/${w}/configuration.mdx`),`| \`mcpServer.enabled\` | \`false\` (requires \`ai\`) | Outward MCP server URL + the **MCP** settings tab - see [external agent (MCP)](/${w}/companion-agent-mcp) |
|
|
1162
|
+
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let v=F(t,`docs/${w}/companion/index.mdx`);await I(v,`It is the user-owned counterpart to the [external agent (MCP)](/${w}/companion-agent-mcp): the MCP server lets a third-party agent reach into your app, while the companion daemon runs on the user's own hardware and reaches out to your app over authenticated HTTP.
|
|
1210
1163
|
|
|
1211
|
-
|
|
1164
|
+
`,"","companion index.mdx MCP counterpart paragraph",n),await I(v,` <Card title="External Agent (MCP)" href="/${w}/companion-agent-mcp" description="The other side - expose your app's capabilities to an external always-on agent over MCP." />
|
|
1165
|
+
`,"","companion index.mdx MCP card",n)}}import{readFile as Po,rm as O}from"fs/promises";import{join as x}from"path";import{readFile as rn}from"fs/promises";import{join as xt}from"path";async function Ao(e,t){let n=xt(e,"packages/api/src/routes/internal/index.ts");await p(n,C(await rn(n,"utf-8"),"internal router","companion",t)),await Zt(n);let r=xt(e,"packages/api/src/ai/schedule-runner.ts");await p(r,C(await rn(r,"utf-8"),"schedule-runner.ts","companion",t));for(let a of["packages/api/src/routes/internal/notifications.ts","packages/api/src/routes/internal/ai/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 s=xt(e,a);await p(s,C(await rn(s,"utf-8"),a,"companion",t))}let o=xt(e,"packages/api/src/ai/settings-store.ts");await I(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1212
1166
|
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
}
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
|
|
1246
|
-
let instance: { bridge: Bridge } | null = null
|
|
1247
|
-
|
|
1248
|
-
/** Builds the production bridge exactly once, on first use (never at module load). */
|
|
1249
|
-
function productionInstance(): { bridge: Bridge } {
|
|
1250
|
-
if (!instance) instance = createBridge(productionDeps())
|
|
1251
|
-
return instance
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
/**
|
|
1255
|
-
* Forwards every property access to a lazily-built target, so importing this module triggers no
|
|
1256
|
-
* \`invoke\` / \`listen\` work. The first property access builds and memoizes the instance; every later
|
|
1257
|
-
* access returns the same member (stable identities).
|
|
1258
|
-
*/
|
|
1259
|
-
function lazyForward<T extends object>(build: () => T): T {
|
|
1260
|
-
return new Proxy(Object.create(null) as T, {
|
|
1261
|
-
get: (_target, prop) => (build() as Record<PropertyKey, unknown>)[prop]
|
|
1262
|
-
})
|
|
1263
|
-
}
|
|
1264
|
-
|
|
1265
|
-
/** The production bridge singleton, lazily built on first property access. */
|
|
1266
|
-
export const bridge: Bridge = lazyForward(() => productionInstance().bridge)`,Pa=`/// The control-server coordinates the renderer needs: the loopback URL (absent until the
|
|
1267
|
-
/// sidecar reports ready) and the bearer token (always present, minted at shell startup).
|
|
1268
|
-
#[derive(serde::Serialize)]
|
|
1269
|
-
struct ControlInfo {
|
|
1270
|
-
url: Option<String>,
|
|
1271
|
-
token: String,
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
/// Returns the current control-server URL and bearer. Callable before the sidecar is ready
|
|
1275
|
-
/// (\`url\` is \`None\` until then; \`token\` is always the minted control token).
|
|
1276
|
-
#[tauri::command]
|
|
1277
|
-
fn get_control_info(state: tauri::State<'_, daemon::DaemonHandle>) -> ControlInfo {
|
|
1278
|
-
let guard = state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
1279
|
-
ControlInfo {
|
|
1280
|
-
url: guard.url.clone(),
|
|
1281
|
-
token: guard.control_token.clone(),
|
|
1282
|
-
}
|
|
1283
|
-
}
|
|
1284
|
-
|
|
1285
|
-
`,Ta="//! Long-lived secret storage for the shell's two secrets: the app bearer token\n//! (set on sign-in, cleared on sign-out) and the engine's AES-256-GCM master key\n//! (created once on first run). Both ride the stdin handshake to the sidecar;\n//! neither is ever passed on argv or in the environment.\n//!\n//! Packaged (release) builds store both in the OS credential store (macOS\n//! Keychain, Windows Credential Manager, Linux Secret Service) under the app\n//! identifier as the service name (`tauri.conf.json`'s `identifier`, which the\n//! CLI and `sync-identity.mjs` rewrite on a rebrand, so rebranded apps never\n//! share entries), users `auth-token` and `engine-master-key`.",Ra="//! Long-lived secret storage for the app bearer token (set on sign-in, cleared\n//! on sign-out). It is never passed on argv or in the environment.\n//!\n//! Packaged (release) builds store it in the OS credential store (macOS\n//! Keychain, Windows Credential Manager, Linux Secret Service) under the app\n//! identifier as the service name (`tauri.conf.json`'s `identifier`, which the\n//! CLI and `sync-identity.mjs` rewrite on a rebrand, so rebranded apps never\n//! share entries), user `auth-token`.";async function _a(e){let t=y(e,"apps/tauri/src/components/shell.tsx");await l(t,F(await j(t,"utf-8"),"components/shell.tsx"));let n=y(e,"apps/tauri/src/components/sidebar/app-sidebar.tsx"),r=F(await j(n,"utf-8"),"components/sidebar/app-sidebar.tsx");r=C(r,"import { useCallback, useMemo, useSyncExternalStore } from 'react'","import { useCallback, useMemo } from 'react'","app-sidebar useSyncExternalStore import"),await l(n,r);let i=y(e,"apps/tauri/src/config/sidebar.ts"),o=F(await j(i,"utf-8"),"config/sidebar.ts");o=C(o,`import {
|
|
1167
|
+
`,"","settings-store.ts relay import",t),await I(o," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>[@<modelId>]` persists as-is (the run path resolves it, and the\n * daemon handles an offline device).\n","","settings-store.ts COMPANION docstring bullet",t),await I(o,` if (config.companion?.enabled === true && parseCompanionKey(key) !== null) {
|
|
1168
|
+
return key;
|
|
1169
|
+
}
|
|
1170
|
+
`,"","settings-store.ts companion-key branch",t);let i=xt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,C(await rn(i,"utf-8"),"settings-store.test.ts","companion",t))}var cs=["companion:export","companion:verify","companion:publish"];async function Fn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await O(x(t,"packages/api/src/relay"),{recursive:!0}),await O(x(t,"packages/api/src/companion"),{recursive:!0}),await O(x(t,"packages/api/src/ai/companion-model.ts")),await O(x(t,"packages/api/tests/relay"),{recursive:!0}),await O(x(t,"packages/api/tests/companion"),{recursive:!0}),await O(x(t,"packages/api/src/routes/internal/companion.ts")),await O(x(t,"packages/api/src/routes/internal/companion-transport.ts")),await O(x(t,"packages/api/tests/routes/companion.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-harness.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await O(x(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await O(x(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await O(x(t,"packages/api/tests/ai/companion-model.test.ts")),await O(x(t,"packages/api/tests/ai/companion-chat.test.ts")),await O(x(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await O(x(t,"packages/api/tests/helpers/redis-mock.ts"));let r=x(t,"packages/api/package.json"),o=JSON.parse(await Po(r,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${n}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Wt(r,o," ",n),await Ao(t,n);let i=it(e);await Fr(t,i,"companion",[`/${i}/companion`,`/${i}/companion/publishing`],n,"Companions"),await I(x(t,`docs/${i}/ai.mdx`),`Runs on a paired [companion](/${i}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",n),await I(x(t,`docs/${i}/configuration.mdx`),`| \`companion.enabled\` | \`false\` (requires \`ai\`) | Companion daemon pairing + the **Companions** settings tab - see [companion](/${i}/companion) |
|
|
1171
|
+
`,"","configuration.mdx companion config-table row",n)}async function Bn(e){if(Ft(e))return;let t=e.projectDir;await O(x(t,"apps/companion"),{recursive:!0}),await O(x(t,"scripts/companion-export"),{recursive:!0}),await ps(t)}async function Gn(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="stripDesktopCompanionDoc";await O(x(t,"docs/desktop/companion.mdx"));let r=x(t,"docs/desktop/meta.json"),o=JSON.parse(await Po(r,"utf-8"));if(!o.pages.includes("companion"))throw new Error(`${n}: expected the desktop meta.json companion nav entry, but it was missing (boilerplate drift).`);o.pages=o.pages.filter(i=>i!=="companion"),await p(r,`${JSON.stringify(o,null,2)}
|
|
1172
|
+
`),await I(x(t,"docs/desktop/index.mdx"),` <Card href="/desktop/companion" title="Companion setup" description="The companion ships inside the app and runs as a local daemon, consent-first - no separate install, and pairing is optional." />
|
|
1173
|
+
`,"","desktop index companion card",n)}async function ps(e){await Kn(e,cs)}var ls=new Set(["ci.yml","desktop-release.yml"]),ds={nextjs:["apps/web-next/app/[locale]/(marketing)/download","apps/web-next/tests/routes/download-page.test.tsx"],nuxt:["apps/web-nuxt/app/pages/download.vue","apps/web-nuxt/app/middleware/desktop.ts","apps/web-nuxt/server/api/desktop-releases.get.ts","apps/web-nuxt/tests/pages/download.test.ts"]},us=["@repo/ai","@repo/agent-core","@repo/agent-core-types","ai","@ai-sdk/react","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit"],ms=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","playground:test:companion","ai:parity"];async function Ro(e){let t=y(e.projectDir,".github/workflows"),n=await Hn(t).catch(()=>[]);for(let r of n)ls.has(r)||await U(y(t,r),{recursive:!0,force:!0})}async function Kn(e,t){let n=y(e,"package.json"),r=JSON.parse(await M(n,"utf-8"));if(!r.scripts)return!1;let o=!1;for(let i of t)i in r.scripts&&(delete r.scripts[i],o=!0);return o&&await p(n,JSON.stringify(r,null," ")+`
|
|
1174
|
+
`),o}async function xo(e){let t=[...ms];jt(e)||t.push("infra","infra:stop"),await Kn(e.projectDir,t)}async function To(e){let t=y(e.projectDir,"package.json"),n=await M(t,"utf-8"),r=JSON.parse(n);!r.scripts||!("dev"in r.scripts)||(r.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await p(t,JSON.stringify(r,null," ")+`
|
|
1175
|
+
`))}async function _o(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await U(y(e.projectDir,t),{recursive:!0,force:!0})}async function Oo(e){e.docs||await U(y(e.projectDir,"apps/docs"),{recursive:!0})}async function Co(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await U(y(e.projectDir,t),{recursive:!0,force:!0}),await U(y(e.projectDir,"docs/index.mdx")),!e.desktop)await U(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!(e.desktop&&e.ai)){await U(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await M(n,"utf-8"));r.pages=r.pages.filter(o=>o!=="ai"),await p(n,`${JSON.stringify(r,null,2)}
|
|
1176
|
+
`)}await fs(e)}async function fs(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=it(e),o=y(t,`docs/${r}/configuration.mdx`),i=e.desktop&&e.ai;e.desktop||(await I(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await I(o,"<Callout>\n**Shipping the [desktop app](/desktop)?** It needs no entry in `TRUSTED_ORIGINS`: its main process makes every backend call - dev and packaged alike - with no `Origin` header, so the backend treats it as a native client and never CORS-checks it. `TRUSTED_ORIGINS` governs your web frontends.\n</Callout>\n\n","","configuration.mdx desktop TRUSTED_ORIGINS callout",n),await I(y(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",n)),i||(await I(o,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch) - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),e.companion&&(await I(y(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
1177
|
+
|
|
1178
|
+
If your product also ships the [desktop app](/desktop), it runs the companion for each user as a local daemon on their own machine - consent-first, with no terminal, no pairing, and no code to copy. It attaches to any daemon already serving the machine - including the user's own always-on service - and starts its own only when none is running, so one daemon serves both the app and any paired backend. It supervises that daemon while the app is open and, on quit, stops only the one it started - never the user's service. See [Companion setup](/desktop/companion).
|
|
1179
|
+
|
|
1180
|
+
`,"","companion index.mdx desktop-setup section",n),await I(y(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
|
|
1181
|
+
|
|
1182
|
+
If your product ships the [desktop app](/desktop), its **Terminal** side-panel tab is this same session, in an embedded terminal: the app spawns the daemon's \`terminal\` command in a real pty, and its folder picker **grants** the folder it picked (the durable, per-app grant above) before the session opens. See [Terminal and side panel](/desktop/ai/terminal).
|
|
1183
|
+
|
|
1184
|
+
`,"","companion terminal.mdx desktop-panel section",n))),e.desktop&&!e.ai&&await I(y(t,"docs/desktop/index.mdx"),` <Card href="/desktop/ai" title="AI agents" description="Turn the user's own AI subscription or API key into a workspace-scoped agent." />
|
|
1185
|
+
`,"","desktop index.mdx AI card",n)}async function Do(e){if(e.desktop)return;await U(y(e.projectDir,"apps/electron"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let o of await Hn(t,{withFileTypes:!0}))o.isDirectory()&&await U(y(t,o.name,"desktop.json"),{force:!0});await U(y(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of ds[e.frontend])await U(y(e.projectDir,o),{recursive:!0});await U(y(e.projectDir,"packages/utils/src/desktop-download.ts")),await U(y(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=y(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await M(n,"utf-8"));if(!r.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete r.exports["./desktop-download"],await Wt(n,r," ","stripDesktopApp")}async function No(e){Ft(e)||await U(y(e.projectDir,"packages/agent-core"),{recursive:!0})}function Tt(e,t,n,r){let o=e.indexOf(t);if(o===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,o+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,o)+n+e.slice(o+t.length)}async function $o(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="apps/electron";for(let a of[`${n}/src/renderer/screens/agents`,`${n}/src/renderer/screens/chat.tsx`,`${n}/src/renderer/screens/schedules.tsx`,`${n}/src/renderer/screens/settings/models.tsx`,`${n}/src/renderer/screens/settings/tasks.tsx`,`${n}/src/renderer/screens/settings/mcp.tsx`,`${n}/src/renderer/screens/settings/integrations.tsx`,`${n}/src/renderer/screens/settings/integration-add-dialog.tsx`,`${n}/src/renderer/screens/settings/integration-types.ts`,`${n}/src/renderer/screens/settings/settings-tabs.tsx`,`${n}/src/renderer/screens/settings/settings-tab-ids.ts`,`${n}/src/renderer/screens/settings/connected-cache.ts`,`${n}/src/renderer/components/section-tabs.tsx`,`${n}/src/renderer/hooks/use-ai-terminal.ts`,`${n}/src/renderer/hooks/use-xterm.ts`,`${n}/src/renderer/hooks/use-automation-lifecycle.ts`,`${n}/src/renderer/lib/companion`,`${n}/src/renderer/hooks/use-chat-controller.ts`,`${n}/src/renderer/hooks/use-local-run.ts`,`${n}/src/renderer/hooks/use-local-model-options.ts`,`${n}/src/renderer/lib/drive-chat-store.ts`,`${n}/src/renderer/lib/local-drive.ts`,`${n}/src/renderer/hooks/use-mounted.ts`,`${n}/src/renderer/lib/ai`,`${n}/src/renderer/lib/side-panel-state.ts`,`${n}/src/renderer/components/side-panel-dock.tsx`,`${n}/src/renderer/components/side-panel.tsx`,`${n}/src/renderer/config/side-panels.tsx`,`${n}/src/renderer/components/command-palette/command-palette-ai-commands.tsx`])await U(y(t,a),{recursive:!0});for(let a of[`${n}/src/preload/api-contract.ts`,`${n}/src/main/drive-transport.ts`,`${n}/src/main/companion.ts`,`${n}/src/main/companion-state.ts`,`${n}/src/main/companion-parsers.ts`,`${n}/src/main/companion-paths.ts`,`${n}/src/main/companion-drive.ts`,`${n}/src/main/companion-staging.ts`,`${n}/src/main/companion-stderr-tail.ts`,`${n}/src/main/companion-commands-pure.ts`,`${n}/src/main/companion-shared.ts`,`${n}/src/main/companion-commands.ts`,`${n}/src/main/terminal.ts`,`${n}/src/main/terminal-state.ts`])await U(y(t,a));await U(y(t,`${n}/scripts/stage-companion.mjs`));for(let a of[`${n}/tests/ai-import-boundary.test.ts`,`${n}/tests/renderer/settings-tab-ids.test.ts`,`${n}/tests/renderer/connected-cache.test.ts`,`${n}/tests/renderer/router-redirects.test.ts`,`${n}/tests/renderer/lib/side-panel-state.test.ts`,`${n}/tests/renderer/schedules-view.test.ts`,`${n}/tests/renderer/automation-status.test.ts`,`${n}/tests/renderer/consent-dialog.test.ts`,`${n}/tests/renderer/background-mode.test.ts`,`${n}/tests/renderer/connection-state.test.ts`,`${n}/tests/renderer/models-empty-view.test.ts`,`${n}/tests/renderer/models-default-reset.test.ts`,`${n}/tests/renderer/cli-catalog.test.ts`,`${n}/tests/renderer/connect-flow.test.ts`,`${n}/tests/renderer/terminal-settings-view.test.ts`,`${n}/tests/renderer/mcp-section-i18n.test.ts`,`${n}/tests/renderer/reload-on-companion-ready.test.ts`,`${n}/tests/renderer/schedule-merge.test.ts`,`${n}/tests/renderer/terminal-tools.test.ts`,`${n}/tests/renderer/terminal-hint-interpolation.test.ts`,`${n}/tests/renderer/lib/companion/consent.test.ts`,`${n}/tests/renderer/lib/companion/ensure.test.ts`,`${n}/tests/renderer/lib/companion/pairing.test.ts`,`${n}/tests/renderer/lib/companion/ensure-unpublished-brand.test.ts`,`${n}/tests/renderer/lib/companion/terminal.test.ts`,`${n}/tests/renderer/lib/companion/terminal-unpublished-brand.test.ts`,`${n}/tests/task-overrides.test.ts`,`${n}/tests/local-drive.test.ts`,`${n}/tests/drive-chat-store.test.ts`,`${n}/tests/use-local-run.test.ts`,`${n}/tests/use-local-model-options.test.ts`,`${n}/tests/renderer/chat-controller-local-seed.test.ts`,`${n}/tests/main/companion-state.test.ts`,`${n}/tests/main/companion-commands.test.ts`,`${n}/tests/main/companion-supervisor.test.ts`,`${n}/tests/main/companion-restage.test.ts`,`${n}/tests/main/companion-teardown.process.test.ts`,`${n}/tests/stage-companion.test.ts`,`${n}/tests/main/drive-preload-stream.test.ts`,`${n}/tests/main/drive-transport.test.ts`,`${n}/tests/main/ipc.test.ts`,`${n}/tests/main/terminal-cli-allowlist.test.ts`,`${n}/tests/main/terminal-manager.process.test.ts`,`${n}/tests/main/terminal-state.test.ts`,`${n}/tests/main/terminal-teardown.process.test.ts`,`${n}/tests/renderer/api-consumer-fixture.ts`])await U(y(t,a));let r=y(t,`${n}/package.json`),o=JSON.parse(await M(r,"utf-8"));for(let a of us){if(!o.dependencies||!(a in o.dependencies))throw new Error(`stripDesktopAi: expected ${a} in ${n} dependencies (boilerplate drift).`);delete o.dependencies[a]}if(!o.scripts||!("rebuild:electron"in o.scripts))throw new Error(`stripDesktopAi: expected the rebuild:electron script in ${n} package.json (boilerplate drift).`);delete o.scripts["rebuild:electron"],gs(o,"stage:companion",n),await p(r,JSON.stringify(o,null,2)+`
|
|
1186
|
+
`),await hs(t,n);let i=y(t,"packages/i18n/translations");for(let a of await Hn(i,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=y(i,a.name,"desktop.json"),u=await M(s,"utf-8").catch(()=>null);if(u===null)continue;let g=JSON.parse(u),l=!1;for(let m of["agents","ai_hub","schedules","integrations"])m in g&&(delete g[m],l=!0);l&&await p(s,JSON.stringify(g,null," ")+`
|
|
1187
|
+
`)}}function gs(e,t,n){if(!e.scripts||!(t in e.scripts))throw new Error(`stripDesktopAi: expected the ${t} script in ${n} package.json (boilerplate drift).`);delete e.scripts[t];let r=`pnpm run ${t} && `;for(let o of["build:unpack","build:win","build:mac","build:linux","release"]){let i=e.scripts[o];if(i===void 0||!i.startsWith(r))throw new Error(`stripDesktopAi: expected ${o} to begin with "${r}" in ${n} package.json (boilerplate drift).`);e.scripts[o]=i.slice(r.length)}}async function hs(e,t){let n=y(e,`${t}/src/renderer/components/shell.tsx`);await p(n,C(await M(n,"utf-8"),"components/shell.tsx"));let r=y(e,`${t}/src/renderer/components/auth-gate.tsx`);await p(r,C(await M(r,"utf-8"),"components/auth-gate.tsx")),await I(r,` // The chat shell owns the ONE chat controller above the router, so a run keeps streaming as the user
|
|
1188
|
+
// moves between the \`/chat\` screen and the side-panel chat tab. Stripped to a bare RouterProvider when
|
|
1189
|
+
// the agents feature is off.
|
|
1190
|
+
return (
|
|
1191
|
+
<ChatShellProvider>
|
|
1192
|
+
<RouterProvider router={router} />
|
|
1193
|
+
</ChatShellProvider>
|
|
1194
|
+
)
|
|
1195
|
+
`,` return <RouterProvider router={router} />
|
|
1196
|
+
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=y(e,`${t}/src/renderer/config/sidebar.ts`),i=C(await M(o,"utf-8"),"config/sidebar.ts");i=Tt(i,`import {
|
|
1286
1197
|
BuildingsIcon,
|
|
1198
|
+
ChatCircleIcon,
|
|
1199
|
+
ClockCountdownIcon,
|
|
1287
1200
|
GearIcon,
|
|
1288
1201
|
HouseIcon,
|
|
1289
|
-
RobotIcon,
|
|
1290
1202
|
UserCircleIcon
|
|
1291
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await
|
|
1292
|
-
`,"","router clientConfig import"),
|
|
1203
|
+
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=y(e,`${t}/src/renderer/lib/config.ts`),s=C(await M(a,"utf-8"),"lib/config.ts");s=s.replace(/,(\n\} as const)/,"$1"),await p(a,s);let u=y(e,`${t}/src/renderer/lib/sidebar-flags.ts`);await p(u,C(await M(u,"utf-8"),"lib/sidebar-flags.ts"));let g=y(e,`${t}/src/renderer/router.tsx`),l=C(await M(g,"utf-8"),"router.tsx");l=Tt(l,`import { clientConfig } from '@/lib/config'
|
|
1204
|
+
`,"","router clientConfig import"),l=Tt(l,` createRouter,
|
|
1293
1205
|
redirect
|
|
1294
1206
|
} from '@tanstack/react-router'`,` createRouter
|
|
1295
|
-
} from '@tanstack/react-router'`,"router redirect import specifier"),
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
`,"","lib.rs handle binding"),R=C(R,` if let Err(err) = daemon::init(&handle) {
|
|
1309
|
-
eprintln!("[shell] sidecar init failed: {err}");
|
|
1310
|
-
}
|
|
1311
|
-
`,"","lib.rs daemon::init call"),R=C(R," let dl_handle = handle.clone();"," let dl_handle = app.handle().clone();","lib.rs macos deep-link handle"),R=C(R,` .run(|app_handle, event| {
|
|
1312
|
-
if let tauri::RunEvent::Exit = event {
|
|
1313
|
-
daemon::shutdown(app_handle);
|
|
1314
|
-
}
|
|
1315
|
-
});`," .run(|_app_handle, _event| {});","lib.rs daemon::shutdown exit hook"),await l(V,R);let te=y(e,"apps/tauri/src-tauri/src/keyring_store.rs"),B=await j(te,"utf-8");B=C(B,Ta,Ra,"keyring_store module doc"),B=F(B,"src-tauri/src/keyring_store.rs"),await l(te,B);let v=y(e,"apps/tauri/src-tauri/capabilities/default.json"),P=JSON.parse(await j(v,"utf-8")),O=P.permissions.length;if(P.permissions=P.permissions.filter(w=>w!=="dialog:default"),P.permissions.length===O)throw new Error("stripDesktopAi: expected the dialog:default capability in capabilities/default.json (boilerplate drift).");await l(v,JSON.stringify(P,null,2)+`
|
|
1316
|
-
`);let Y=y(e,"apps/tauri/src-tauri/tauri.conf.json"),T=JSON.parse(await j(Y,"utf-8"));if(!T.bundle)throw new Error("stripDesktopAi: expected a bundle block in tauri.conf.json (boilerplate drift).");if(Ze(T.bundle,"externalBin","the tauri.conf bundle.externalBin key","stripDesktopAi"),Ze(T.bundle,"resources","the tauri.conf bundle.resources key","stripDesktopAi"),!T.build||T.build.beforeDevCommand!=="pnpm sidecar:stage && pnpm dev:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeDevCommand in tauri.conf.json (boilerplate drift).");if(T.build.beforeBuildCommand!=="pnpm sidecar:stage && pnpm build:vite")throw new Error("stripDesktopAi: expected the sidecar-staged beforeBuildCommand in tauri.conf.json (boilerplate drift).");T.build.beforeDevCommand="node scripts/sync-identity.mjs && pnpm dev:vite",T.build.beforeBuildCommand="node scripts/sync-identity.mjs && pnpm build:vite",await l(Y,JSON.stringify(T,null,2)+`
|
|
1317
|
-
`)}import{readFile as Oa}from"fs/promises";import{join as xa}from"path";var Zr=`on:
|
|
1207
|
+
} from '@tanstack/react-router'`,"router redirect import specifier"),l=Tt(l,`import { ChatScreen } from '@/screens/chat'
|
|
1208
|
+
import { SchedulesScreen } from '@/screens/schedules'
|
|
1209
|
+
import { ModelsSettingsScreen } from '@/screens/settings/models'
|
|
1210
|
+
import { TasksSettingsScreen } from '@/screens/settings/tasks'
|
|
1211
|
+
import { McpSettingsScreen } from '@/screens/settings/mcp'
|
|
1212
|
+
import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
1213
|
+
`,"","router AI screen imports"),l=Tt(l,` ...(clientConfig.agentsEnabled ? aiRoutes : []),
|
|
1214
|
+
`,"","router ai route spread"),await p(g,l);let m=y(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(m,C(await M(m,"utf-8"),"screens/settings/index.tsx"));let w=y(e,`${t}/src/main/ipc.ts`);await p(w,C(await M(w,"utf-8"),"src/main/ipc.ts"));let v=y(e,`${t}/src/main/index.ts`);await p(v,C(await M(v,"utf-8"),"src/main/index.ts"));let R=y(e,`${t}/src/preload/index.ts`);await p(R,C(await M(R,"utf-8"),"src/preload/index.ts"));let q=y(e,`${t}/electron-builder.mjs`);await p(q,C(await M(q,"utf-8"),"electron-builder.mjs"))}import{readFile as ys}from"fs/promises";import{join as ws}from"path";var Lo=`on:
|
|
1215
|
+
workflow_run:
|
|
1216
|
+
workflows: ["Tag Release"]
|
|
1217
|
+
branches: [main]
|
|
1218
|
+
types: [completed]
|
|
1219
|
+
workflow_dispatch:`,vs=`on:
|
|
1318
1220
|
workflow_run:
|
|
1319
1221
|
workflows: ["CI"]
|
|
1320
1222
|
branches: [main]
|
|
1321
1223
|
types: [completed]
|
|
1322
|
-
workflow_dispatch:`,
|
|
1224
|
+
workflow_dispatch:`,ks=`on:
|
|
1323
1225
|
# Automatic release on CI success is disabled for this project to conserve
|
|
1324
1226
|
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1325
1227
|
# workflow_run:
|
|
1326
1228
|
# workflows: ["CI"]
|
|
1327
1229
|
# branches: [main]
|
|
1328
1230
|
# types: [completed]
|
|
1329
|
-
workflow_dispatch:`;async function
|
|
1231
|
+
workflow_dispatch:`;async function Uo(e){if(!e.desktop)return;let t=ws(e.projectDir,".github/workflows/desktop-release.yml"),n=await ys(t,"utf8");if(!n.includes(Lo))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.`);let r=e.desktopAutoRelease?vs:ks;await p(t,n.replace(Lo,r))}import{join as bs}from"path";async function jo(e){let t=Ss(e);await p(bs(e.projectDir,".github/workflows/ci.yml"),t)}function Ss(e){let t=Y[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
|
|
1330
1232
|
postgres:
|
|
1331
1233
|
image: postgres:18-alpine
|
|
1332
1234
|
env:
|
|
@@ -1340,14 +1242,14 @@ export interface Bridge extends NativeBridgeParts {
|
|
|
1340
1242
|
--health-interval 10s
|
|
1341
1243
|
--health-timeout 5s
|
|
1342
1244
|
--health-retries 5
|
|
1343
|
-
`,
|
|
1245
|
+
`,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",a=n?`
|
|
1344
1246
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1345
1247
|
UPSTASH_REDIS_REST_TOKEN: test-token`:"",s=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1346
1248
|
STRIPE_SECRET_KEY: test
|
|
1347
1249
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1348
1250
|
POLAR_ACCESS_TOKEN: test
|
|
1349
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1350
|
-
${
|
|
1251
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})(),u=e.socialProviders.map(m=>ue[m].envVars.map(w=>`
|
|
1252
|
+
${w.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1351
1253
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1352
1254
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1353
1255
|
|
|
@@ -1371,8 +1273,8 @@ jobs:
|
|
|
1371
1273
|
name: Checks
|
|
1372
1274
|
runs-on: ubuntu-latest
|
|
1373
1275
|
timeout-minutes: 20
|
|
1374
|
-
${
|
|
1375
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${a}${s}${
|
|
1276
|
+
${o} env:
|
|
1277
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${a}${s}${u}
|
|
1376
1278
|
STORAGE_REGION: test
|
|
1377
1279
|
STORAGE_ENDPOINT: http://test
|
|
1378
1280
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1393,49 +1295,51 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1393
1295
|
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1394
1296
|
|
|
1395
1297
|
- name: Write root env
|
|
1396
|
-
run: echo "DATABASE_URL=${
|
|
1298
|
+
run: echo "DATABASE_URL=${i}" > .env
|
|
1397
1299
|
|
|
1398
1300
|
- run: pnpm test
|
|
1399
|
-
`}import{readFile as
|
|
1400
|
-
`))}async function
|
|
1401
|
-
`))}async function
|
|
1301
|
+
`}import{readFile as Mo}from"fs/promises";import{existsSync as Es}from"fs";import{join as zn}from"path";var Vo="@repo/database";function Is(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function As(e,t){switch(e){case"fullstack":return t==="nextjs"?"web-next":"web-nuxt";case"separate":return"backend";default:{let n=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(n)}"`)}}}async function Ps(e,t,n){let r=await Mo(e,"utf-8"),o=JSON.parse(r),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(Vo)||(o.scripts={...o.scripts,[t]:`${n} && ${i}`},await p(e,JSON.stringify(o,null," ")+`
|
|
1302
|
+
`))}async function Rs(e,t){let n=Es(e)?JSON.parse(await Mo(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(Vo)||(n.buildCommand=`${t} && ${r}`,await p(e,JSON.stringify(n,null," ")+`
|
|
1303
|
+
`))}async function Fo(e){let t=Is(e.demo===!0),n=As(e.architecture,e.frontend),r=zn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await Ps(zn(r,"package.json"),"start",t);return;case"vercel":await Rs(zn(r,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as xs}from"fs/promises";import{existsSync as Ts}from"fs";import{join as on}from"path";var _s=["stripe","polar"];async function Bo(e){let t=on(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1402
1304
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1403
1305
|
export { ops } from "./${n}/index";
|
|
1404
|
-
`;await
|
|
1405
|
-
`).filter(a=>!
|
|
1406
|
-
`)}import{readdir as
|
|
1407
|
-
`).filter(
|
|
1408
|
-
`).length&&await
|
|
1409
|
-
`))}async function
|
|
1410
|
-
`),await
|
|
1411
|
-
`)}import{relative as
|
|
1412
|
-
`);
|
|
1413
|
-
${
|
|
1414
|
-
`),
|
|
1415
|
-
`),
|
|
1416
|
-
`),
|
|
1417
|
-
`),await
|
|
1418
|
-
`),
|
|
1419
|
-
`);let
|
|
1420
|
-
`)}if(
|
|
1421
|
-
`),
|
|
1422
|
-
`),
|
|
1423
|
-
|
|
1424
|
-
${
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
`),
|
|
1429
|
-
`).
|
|
1306
|
+
`;await p(on(t,"providers/index.ts"),r),await p(on(t,"index.ts"),await Os(t,n))}async function Os(e,t){let n=on(e,"index.ts");if(!Ts(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await xs(n,"utf-8"),o=_s.filter(a=>a!==t);return r.split(`
|
|
1307
|
+
`).filter(a=>!o.some(s=>a.includes(`./providers/${s}/`))).join(`
|
|
1308
|
+
`)}import{readdir as Cs,readFile as Ds}from"fs/promises";import{join as Go}from"path";async function Ko(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=Go(e.projectDir,"packages/i18n/translations"),o;try{o=await Cs(r)}catch{return}for(let i of o){let a=Go(r,i,"web.json"),s;try{s=await Ds(a,"utf-8")}catch{continue}let u=s.replaceAll("GenerateSaaS",n);u!==s&&await p(a,u)}}import{readFile as Ns}from"fs/promises";import{join as Ho}from"path";var $s=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Ls=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Jo(e){let n=e.frontend==="nuxt"?Ls:$s;await zo(Ho(e.projectDir,".gitignore"),n),await zo(Ho(e.projectDir,".dockerignore"),n)}async function zo(e,t){let n;try{n=await Ns(e,"utf-8")}catch{return}let r=new Set(t),o=n.split(`
|
|
1309
|
+
`).filter(i=>!r.has(i.trim()));o.length!==n.split(`
|
|
1310
|
+
`).length&&await p(e,o.join(`
|
|
1311
|
+
`))}async function an(e){let t=e.projectDir;e.demo||(await Gr(t),await Hr(t),await zr(t),await Jr(t),e.desktop&&await Kr(t)),await qr(t,e.aiTools),await Yr(t,e.frontend),await Xr(e),await Zr(e),await eo(e),await Qr(e),e.demo||await to(e),await oo(e);let n=await io(e);return await ao(e),await so(e),await co(e),await po(e),await lo(e),await uo(e),await ho(e),await yo(e),await ko(e),await Eo(e),await Ro(e),await jo(e),await xo(e),await To(e),await _o(e),await Oo(e),await Co(e),await Do(e),await $o(e),await No(e),await Uo(e),await Vn(e),await Fn(e),await Bn(e),await Gn(e),await Fo(e),await Bo(e),await Ko(e),await Jo(e),{dockerComposeGenerated:n}}import{basename as Yo,join as Wo,relative as js}from"path";import{createHash as qo}from"crypto";import{readFile as Us}from"fs/promises";async function sn(e){let t=await Us(e);return qo("sha256").update(t).digest("hex")}function Jn(e){return qo("sha256").update(e).digest("hex")}var Ms=new Set(["data",z]);function Vs(e){let t=e.split("/");for(let n of t)if(xn.has(n)||Tn.has(n)||Ms.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Xo(e,t){return{projectName:e.projectName??Yo(t),appName:e.appName??e.projectName??Yo(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,billingScope:e.billingScope??"user",blog:e.blog??!1,emailTracking:e.emailTracking??!0,docs:e.docs??!1,desktop:e.desktop??!1,desktopAutoRelease:e.desktopAutoRelease??!0,ai:e.ai??!1,companion:e.companion??!1,companionSource:W(e),companionRepoUrl:e.companionRepoUrl??Le,companionLocalPath:e.companionLocalPath??"",companionName:e.companionName??ee(e.projectName),mcpServer:e.mcpServer??!1,aiBuiltin:Ie(e)&&(e.aiBuiltin??!0),aiByok:e.aiByok??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,dockerServices:e.dockerServices??[],aiTools:e.aiTools??[],socialProviders:e.socialProviders??[],defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Fs(e,t){return{version:e.version,initialVersion:e.version,repo:"Duzbee/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,desktopAutoRelease:e.desktopAutoRelease,ai:e.ai,companion:e.companion,mcpServer:e.mcpServer,...e.companionName?{companionName:e.companionName}:{},...e.companionSource?{companionSource:e.companionSource}:{},...e.companionRepoUrl?{companionRepoUrl:e.companionRepoUrl}:{},...e.companionLocalPath!==void 0?{companionLocalPath:e.companionLocalPath}:{},aiBuiltin:e.aiBuiltin,aiByok:e.aiByok,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,dockerServices:e.dockerServices,socialProviders:e.socialProviders,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,aiTools:e.aiTools,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Zo(e,t){let r=(await Ve(e.projectDir,e.projectDir,Vs)).sort(),o=await Promise.all(r.map(async s=>[Me(js(e.projectDir,s)),await sn(s)])),i=Object.fromEntries(o),a=Fs(e,t);await p(Wo(e.projectDir,Ae),JSON.stringify(a,null," ")+`
|
|
1312
|
+
`),await p(Wo(e.projectDir,Tr),JSON.stringify(i,null," ")+`
|
|
1313
|
+
`)}import{relative as Bs}from"path";async function Fe(e){let n=(await Ve(e,e,ot)).sort(),r=await Promise.all(n.map(async o=>[Me(Bs(e,o)),await sn(o)]));return Object.fromEntries(r)}import{copyFile as Gs,mkdir as Ks,rm as Hs}from"fs/promises";import{dirname as zs,join as Qo,relative as Js}from"path";import{existsSync as qs}from"fs";async function qn(e,t){qs(t)&&await Hs(t,{recursive:!0,force:!0});let n=await Ve(e,e,ot);for(let r of n){let o=Me(Js(e,r)),i=Qo(t,o);await Ks(zs(i),{recursive:!0}),await Gs(r,i)}}async function ei(e,t){await qn(e,Qo(t,Ht))}import{existsSync as Ys}from"fs";import{readFile as ti,readdir as Ws}from"fs/promises";import{join as de,dirname as Xs,resolve as Zs,sep as Qs}from"path";import{fileURLToPath as ec}from"url";var _t={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},wm=Object.values(_t),Yn="generatesaas-update",ni=Xs(ec(import.meta.url));function tc(){let e=de(ni,"skill","content");return Ys(e)?e:de(ni,"content")}function Wn(e){return!e||e.length===0?[]:e.map(t=>_t[t])}async function Xn(e,t,n,r){let o=Wn(r);for(let i of o){let a=de(e,i,Yn),s=de(a,"scripts"),u=de(a,"references");await Yt(s),await Yt(u),await p(de(a,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",i)),await p(de(u,".gitkeep"),"");for(let[g,l]of Object.entries(n)){let m=Zs(s,g);m.startsWith(s+Qs)&&await p(m,l)}}}async function ri(e,t){let n=tc(),r=await ti(de(n,"SKILL.md"),"utf-8"),o=de(n,"scripts"),i=await Ws(o),a={};for(let s of i)s!==".gitkeep"&&(a[s]=await ti(de(o,s),"utf-8"));await Xn(e,r,a,t)}import{execFile as nc,execFileSync as rc}from"child_process";import{access as oi,readFile as oc}from"fs/promises";import{join as Zn}from"path";import*as j from"@clack/prompts";function Ge(e){try{let t=process.platform==="win32"?"where":"which";return rc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Be(e,t,n,r=3e5){return new Promise((o,i)=>{nc(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(a,s,u)=>{if(a){let g=String(s||"").trim(),m=[String(u||"").trim(),g].filter(Boolean).join(`
|
|
1314
|
+
`);i(new Error(m?`${a.message}
|
|
1315
|
+
${m}`:a.message))}else o()})})}async function ii(e){if(!Ge("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Be("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${n}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ai(e){if(!Ge("pnpm"))return j.log.warn("pnpm not found. Skipping dependency installation."),j.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=j.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Be("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`pnpm install failed: ${r}`),j.log.warn("You can run it manually later."),!1}}async function si(e){if(!Ge("pnpm"))return!1;let t=j.spinner();t.start("Generating baseline database migration...");try{return await Be("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`Could not generate baseline migration: ${r}`),j.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ci(e){try{return await oi(Zn(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ge("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await Be("git",["init"],e),await Be("git",["add","-A"],e),await Be("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),j.log.warn("You can run git init manually later."),!1}}async function pi(e){if(!Ge("pnpm"))return!1;try{await oi(Zn(e,".git"))}catch{return!1}try{let t=JSON.parse(await oc(Zn(e,"package.json"),"utf-8")),n=!!t.devDependencies?.["simple-git-hooks"],r=!!t["simple-git-hooks"];if(!n||!r)return!1}catch{return!1}try{return await Be("pnpm",["exec","simple-git-hooks"],e),!0}catch{return j.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as ut from"@clack/prompts";import te from"picocolors";function li(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&ut.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];if(n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.dockerComposeGenerated){let i=e.dockerServices.map(a=>qe[a].label).join(", ");n.push(`pnpm infra ${te.dim(`# ${i}`)}`)}if(n.push(`pnpm dev ${te.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(te.dim("Fill in remaining TODO values in .env"))),ut.note(n.join(`
|
|
1316
|
+
`),te.yellow("Start Development")),t.dockerComposeGenerated){let i=[];i.push(`App ${te.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${te.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&i.push(`Mailpit ${te.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&i.push(`Inngest ${te.cyan("http://localhost:8288")}`),ut.note(i.join(`
|
|
1317
|
+
`),te.yellow("Dev Tools"))}let r=[],o=ic(e);o.length>0&&r.push(`Set in production: ${te.dim(o.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(ac(e)),ut.note(r.join(`
|
|
1318
|
+
`),te.yellow("Deployment"))}function ic(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET"];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 ac(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 mt(e){let n=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function Ke(e,t){let n=mt(e),r=mt(t);if(!n||!r)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function cn(e,t){return e.versions.find(n=>n.version===t)?.cli}function di(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:mt(e)===null}function pn(e,t,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,e.latest);return!r||mt(r)===null?{ok:!0}:Ke(n,r)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${n}) is too old for template v${e.latest}, which needs CLI v${r} 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,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,t);return!r||mt(r)===null?{ok:!0}:Ke(n,r)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${r} exactly (the CLI whose generators produced that release). Run npx generatesaas@${r} init.`}}import uc from"picocolors";var mc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function fc(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),n=[...new Uint8Array(t).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}function mi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new X("--frontend <type>","frontend framework").choices([...Ne])).addOption(new X("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new X("--payment <provider>","payment provider").choices([...We])).addOption(new X("--email <provider>","email provider").choices([...Xe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new X("--billing-scope <scope>","billing scope (requires --org)").choices([...et])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").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("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - a daemon your users install to run their own AI subscriptions for this app (shared repo or vendored)").option("--no-companion","exclude the backend companion feature").addOption(new X("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...$e])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").option("--companion-local-path <path>","path to your local checkout of the shared companion (optional, for developing it alongside)").option("--mcp-server","include the outward MCP server (the /mcp route + Better Auth mcp() provider)").option("--no-mcp-server","exclude the outward MCP server").option("--ai-builtin","built-in AI: models under your app's name via OpenRouter, billed from credits (default)").option("--no-ai-builtin","no built-in AI").option("--ai-byok","let end-users connect their own provider API keys (default)").option("--no-ai-byok","no user-supplied API keys").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)").option("--docker <services>","comma-separated: postgres,redis,inngest,mailpit").option("--ai-tools <tools>","comma-separated: claude-code,cursor,codex,gemini-cli,windsurf").option("--social-providers <providers>","comma-separated: google,github,facebook,discord,x").addOption(new X("--currency <code>","default currency for billing").choices([...me])).addOption(new X("--deploy <target>","deployment target").choices([...fe])).addOption(new X("--database <provider>","database provider").choices([...ge])).addOption(new X("--cache <provider>","cache provider").choices([...he])).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new X("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new X("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await gc(t?{...n,apiKey:t}:n)})}async function gc(e){let t=performance.now();dr("2.0.1");let n;try{n=Pr(e)}catch(E){A.cancel(T(E)),process.exit(1)}let r=A.spinner(),o;try{o=await rt({apiKey:e.apiKey,prompt:!e.yes})}catch(E){A.cancel(T(E)),process.exit(1)}e.demo&&Jn(o)!==mc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=ve(o),a,s=async()=>{a=await xe(i);let E=pn(a,"init");if(!E.ok)throw new Error(E.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0}};r.start("Verifying access...");let u,g,l=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch(E){if(r.stop("Access verification failed."),E instanceof V&&E.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await Et(),i=ve(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch($){r.stop("Access verification failed."),A.cancel($ instanceof V&&$.status===401?"Invalid API key.":T($)),process.exit(1)}}else A.cancel(T(E)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let m;e.yes?m=Rr(l?n:{...n,desktop:!1}):m=await xr(n,{desktopAllowed:l});let w;r.start("Activating license...");try{let E=e.demo&&m.baseUrl?await fc(m.baseUrl):crypto.randomUUID(),$=()=>({frontend:m.frontend,version:g,installId:E,projectName:m.projectName,options:Dr(m)}),L;try{L=await Pn(i,$())}catch(Oe){let _=zt(Oe);if(!_?.lastAllowedVersion||!a)throw Oe;r.stop("License activation failed.");let k=ui(a,_.lastAllowedVersion);if(k.ok||(A.cancel(`${_.message} ${k.message}`),process.exit(1)),e.yes){let oe=cn(a,_.lastAllowedVersion);A.cancel(`${_.message} Re-run ${oe?`npx generatesaas@${oe} init`:"init"} without --yes to continue with v${_.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await A.confirm({message:`Your update window has ended. Continue with v${_.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(B)||!B)&&(A.cancel("Setup cancelled."),process.exit(0)),g=_.lastAllowedVersion,r.start(`Activating license for v${g}...`),L=await Pn(i,$())}w={token:L.token,keyHash:Jn(o),installId:L.installId??E},r.stop("License activated.")}catch(E){r.stop("License activation failed."),A.cancel(T(E)),process.exit(1)}let v=dc(m.projectDir);if(sc(v)&&cc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let $=await A.select({message:`Directory ${v} 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"}]});(A.isCancel($)||$==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),$==="overwrite"&&pc(v,{recursive:!0,force:!0})}let R={...m,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await Jt(i,g,v),r.stop("Template downloaded.")}catch(E){r.stop("Download failed."),A.cancel(T(E)),process.exit(1)}let q;r.start("Generating project files...");try{if({dockerComposeGenerated:q}=await an(R),!e.demo){let E=await Fe(v);await p(lc(v,Kt),JSON.stringify(E,null," ")+`
|
|
1319
|
+
`),await ei(v,v)}await ri(v,R.aiTools),await Zo(R,w),r.stop("Project files generated.")}catch(E){r.stop("Generation failed."),A.cancel(T(E)),process.exit(1)}!await ii(v)&&R.demo===!0&&(A.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let Q=await ai(v);Q&&R.demo!==!0&&e.dbMigration!==!1&&await si(v),await ci(v),Q&&await pi(v);let Se=Ge("docker"),Ee=In(R).map(E=>E.key).filter(E=>!R.credentials?.[E]);li(R,{pnpmInstalled:Q,dockerComposeGenerated:q,dockerAvailable:Se,skippedCredentials:Ee}),ur(),A.log.info(uc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as tr}from"fs";import{readFile as nr}from"fs/promises";import{join as ft,resolve as Ec}from"path";import*as P from"@clack/prompts";import J from"picocolors";import{mkdtemp as hc,rm as yc}from"fs/promises";import{tmpdir as wc}from"os";import{join as vc}from"path";async function Qn(e,t,n,r){let o=await hc(vc(wc(),"generatesaas-stage-"));try{await Jt(e,t,o),await an({...n,projectDir:o}),await qn(o,r)}finally{await yc(o,{recursive:!0,force:!0})}}import{readFile as kc,rm as bc}from"fs/promises";import{join as er}from"path";var fi=er(z,"companion-release.json"),Sc=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function gi(e){let t;try{t=await kc(er(e,fi),"utf-8")}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT")return null;throw r}let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"version"in n&&typeof n.version=="string"&&n.version.length>0?{version:n.version}:null}async function hi(e){try{return await bc(er(e,fi)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function yi(e){return e.some(t=>Sc.some(n=>t.startsWith(n)))}function vi(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,n)=>{let r=t==="auto"?"auto":void 0,o=Ec(n.cwd??process.cwd()),i=ft(o,Ae),a;try{a=JSON.parse(await nr(i,"utf-8"))}catch{P.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await rt()}catch(l){P.cancel(T(l)),process.exit(1)}let u=ve(s),g=P.spinner();try{g.start("Verifying access...");let l;try{l=await xe(u)}catch(k){throw k instanceof V&&k.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):k}let m=pn(l,"update");if(!m.ok)throw new Error(m.message);g.stop("Access verified."),je(s),g.start("Fetching latest skill files...");let w=await Cr(u,l.latest);await Xn(o,w.skillMd,w.scripts,a.aiTools);let v=Wn(a.aiTools);if(g.stop("Skills updated."),P.log.success(`Skill files installed to ${J.cyan(v.length.toString())} locations.`),a.version===l.latest){P.log.info(`Already on the latest version (${a.version}).`);return}let R=JSON.stringify(a);Er(a),Ir(a),await Ic(a,Ar(a),r);let q=hr(a),be=yr(a),Q=JSON.stringify(be)!==R;if(a=be,a.licenseToken)try{let k=await Nr(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=k.token,k.licenseKeyHash&&(a.licenseKeyHash=k.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1320
|
+
`),Q=!1,P.log.success("License refreshed.")}catch(k){let B=zt(k);B&&(P.cancel(B.message),process.exit(1)),P.log.warn("License refresh skipped.")}Q&&await p(i,JSON.stringify(a,null," ")+`
|
|
1321
|
+
`);let Se=Xo(a,o),Je=ft(o,_r);g.start(`Staging v${l.latest} (shaped for your config)...`),await Qn(u,l.latest,Se,Je),g.stop("Template staged.");let{text:Ee,title:E}=await Pc(u,l,a.version);Ee&&P.note(Ee,E);let $=ft(o,Kt),L=ft(o,Ht),Oe=!tr(L),_=!tr($);if(Oe){if(g.start("Building baseline template (one-time migration)..."),await Qn(u,a.version,Se,L),_){let k=await Fe(L);await p($,JSON.stringify(k,null," ")+`
|
|
1322
|
+
`)}if(g.stop("Baseline template stored."),!_){let k=await xc($,L);k>0&&P.log.warn(`Rebuilt baseline differs from the original for ${k} 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(_){g.start("Computing baseline template hashes...");let k=await Fe(L);await p($,JSON.stringify(k,null," ")+`
|
|
1323
|
+
`),g.stop("Baseline hashes computed.")}if(await p(ft(o,Or),JSON.stringify({currentVersion:a.version,targetVersion:l.latest,changelog:Ee,stagedAt:new Date().toISOString(),...q.length>0?{newOptions:q}:{},...r?{mode:r}:{}},null," ")+`
|
|
1324
|
+
`),P.log.info(`Update staged: ${J.cyan(a.version)} \u2192 ${J.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let k=a.aiTools[0],B=wt[k].label;P.log.info(`Open your project in ${J.cyan(B)} and ask: ${J.cyan("'update my GenerateSaaS project'")}`)}else P.log.info(`Ask your AI coding assistant to ${J.cyan("'update my GenerateSaaS project'")}.`);if(a.companion===!0)try{if(se(a)==="vendored"){let k=await gi(o);if(k){let B=await Rc($,Je);yi(B)&&P.log.warn(`Companion: vendored daemon changed since your published v${k.version} - run pnpm companion:publish (your users auto-update once tagged)`)}}else await hi(o)&&P.log.info("Companion: removed the stale vendored publish state (.generatesaas/companion-release.json) - this project points at a shared companion.")}catch(k){P.log.warn(`Companion re-release check skipped: ${T(k)}`)}a.desktop===!0&&tr(ft(o,"apps/tauri"))&&P.log.warn(`Desktop: the app moved to an Electron shell (${J.cyan("apps/electron")}). Your project still has the old Tauri shell (${J.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${J.cyan("/desktop/updates")}.`)}catch(l){g.stop("Failed."),P.cancel(`Update failed: ${T(l)}`),process.exit(1)}})}async function Ic(e,t,n){if(t.kind==="none")return;if(t.kind==="daemon-materialized"){P.log.info(`Desktop: your app now bundles its own companion daemon. This update adds its source to your repo (${J.cyan("apps/companion")}, branded ${J.cyan(e.companionName??"")}) and about 106MB to each packaged build. Nothing to publish - it ships inside the app.`);return}let r=Ac[t.kind];n==="auto"&&(P.cancel(`${r.message}
|
|
1325
|
+
|
|
1326
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${J.cyan("generatesaas update")} without ${J.cyan("auto")} and answer it.`),process.exit(1));let o=await P.select({message:r.message,options:r.options});P.isCancel(o)&&(P.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),En(e)}function wi(e){e.desktop=!1,e.desktopAutoRelease=!1}var Ac={"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 adds the companion daemon's source to your repo (apps/companion, ~106MB per packaged build) and 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, no bundled daemon"}]},"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 and bundles a companion daemon. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack, the Terminal, and the bundled companion daemon (apps/companion, ~106MB per packaged build)"},{value:{apply:e=>{e.ai=!1,e.companion=!1,e.mcpServer=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion and the MCP server - they both require AI"},{value:{apply:wi},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]},"shared-source-contradiction":{message:"Your desktop app bundles a companion daemon, but your project points its web install flow at a shared companion. A bundled app needs its own daemon. How should this resolve?",options:[{value:{apply:e=>{e.companionSource="vendored"}},label:"Vendor your own companion",hint:"its source moves into your repo (apps/companion) and your web install UI switches to it - your users install yours, not the shared one"},{value:{apply:wi},label:"Drop the desktop app",hint:"your website keeps its AI surface and its shared companion exactly as they are today"}]}};async function Pc(e,t,n){let r=t.latest,o=t.versions.filter(a=>Ke(a.version,n)>0&&Ke(a.version,r)<=0).sort((a,s)=>Ke(a.version,s.version));if(o.length<=1)return{text:await An(e,r),title:`Changelog v${r}`};let i=[];for(let a of o){let s=null;try{s=await An(e,a.version)}catch{s=null}let u=a.date?` (${a.date.slice(0,10)})`:"",g=a.breaking?" [BREAKING]":"";i.push(`# v${a.version}${u}${g}
|
|
1327
|
+
|
|
1328
|
+
${s??"_No changelog available for this release._"}`)}return{text:i.join(`
|
|
1329
|
+
|
|
1330
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function Rc(e,t){let n=JSON.parse(await nr(e,"utf-8")),r=await Fe(t),o=[];for(let[i,a]of Object.entries(r))n[i]!==a&&o.push(i);for(let i of Object.keys(n))i in r||o.push(i);return o}async function xc(e,t){let n=JSON.parse(await nr(e,"utf-8")),r=await Fe(t),o=0;for(let[i,a]of Object.entries(n))ot(i)||r[i]!==a&&o++;for(let i of Object.keys(r))i in n||o++;return o}import*as Z from"@clack/prompts";import ne from"picocolors";import{readFile as Tc}from"fs/promises";import{join as _c,resolve as Oc}from"path";function ki(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let n=Oc(t.cwd??process.cwd()),r=_c(n,Ae),o;try{o=JSON.parse(await Tc(r,"utf-8"))}catch{Z.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${ne.cyan(o.version)}`,`Frontend: ${ne.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${ne.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${ne.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${ne.cyan(o.cacheProvider)}`:null,o.aiTools&&o.aiTools.length>0?`AI tools: ${ne.cyan(o.aiTools.join(", "))}`:null].filter(Boolean).join(`
|
|
1331
|
+
`);Z.note(i,ne.bold("Project Status"));let a=Z.spinner();a.start("Checking for updates...");try{let s=await rt(),u=ve(s),l=(await xe(u)).latest;o.version===l?(a.stop("Up to date."),Z.log.success(`Already on the latest version (${ne.green(l)})`)):(a.stop("Update available."),Z.log.warning(`Update available: ${ne.yellow(o.version)} \u2192 ${ne.green(l)}`),Z.log.info(`Open this project in your AI coding agent and ask it to ${ne.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(s){a.stop("Check failed."),s instanceof V&&s.status===401?Z.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):Z.log.warning(`Could not check for updates: ${T(s)}`)}})}import{readFile as Cc}from"fs/promises";import*as N from"@clack/prompts";import D from"picocolors";function Dc(){return process.env.GENERATESAAS_API_KEY??St()}function Nc(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 $c(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Lc(e){switch(e.verdict){case"licensed":return N.log.success(`${D.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return N.log.success(`${D.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 N.log.error(`${D.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 N.log.error(`${D.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${D.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return N.log.error(`${D.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return N.log.warn(`${D.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function bi(e,t){let n=process.env.GENERATESAAS_API_URL??bt,r=Dc();e.start("Cross-referencing license records...");try{let o=r?Nc(await $r(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):$c(await Rn(n,{token:t.token,domain:t.domain}));return e.stop(`${D.green("Checked")} - records cross-referenced`),Lc(o)}catch(o){return e.stop(`${D.yellow("Skipped")} - ${T(o)}`),null}}function Uc(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let n=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(n)}function rr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Si(e){N.note([`License ID: ${D.cyan(String(e.lid??"unknown"))}`,`Version: ${D.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${rr(e.pat)}`,`Last updated: ${rr(e.uat)}`,`Expires: ${rr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1332
|
+
`),D.yellow("License Details"))}function jc(e){let n=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(n.endsWith("/api"))return[`${n}/license`];try{if(new URL(n).pathname!=="/")return[`${n}/license`]}catch{return[`${n}/license`]}return[`${n}/api/license`,`${n}/license`]}async function Ei(e){let t=N.spinner(),n=null,r="no candidates";for(let a of jc(e)){t.start(`Checking ${a}...`);try{let s=await fetch(a);if(!s.ok){r=`${a} returned ${s.status}`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}let u=(await s.text()).trim();if(!u||u.split(".").length!==3){r=`${a} did not return a JWT`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}n=u,t.stop(`${D.green("Found")} - license endpoint responded`);break}catch(s){r=`${a}: ${T(s)}`,t.stop(`${D.yellow("Unreachable")} - ${r}`)}}if(n===null){N.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let a=Ii(e);return a?await bi(t,{domain:a})??!1:!1}let o;try{o=Uc(n)}catch{return N.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let a=process.env.GENERATESAAS_API_URL??bt,s=await Rn(a,{token:n});if(s.valid)t.stop(`${D.green("Valid")} - signature verified`);else return t.stop(`${D.red("Invalid")} - ${s.reason}`),!1}catch{return t.stop(`${D.yellow("Skipped")} - could not reach verification service`),N.log.warn("Signature not verified. Displaying unverified claims:"),Si(o),!1}return Si(o),await bi(t,{token:n,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:Ii(e)})??!0}function Ii(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Ai(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,n)=>{if(!t&&!n.file&&(N.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let o=(await Cc(n.file,"utf-8")).split(`
|
|
1333
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(N.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await Ei(a)&&i++,N.log.info("");N.log.success(`${i}/${o.length} sites verified.`)}else await Ei(t)||process.exit(1)})}import{existsSync as Mc,rmSync as Vc}from"fs";import*as re from"@clack/prompts";function Pi(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Mc(we)?(Vc(we),re.log.success("API key removed.")):re.log.info("No API key configured.");return}let n=St();n?re.log.info(`Current API key: ****${n.slice(-4)}`):re.log.info("No API key configured.");let r=await Et(),o=ve(r),i=re.spinner();i.start("Verifying API key...");try{await xe(o),i.stop("API key verified."),je(r),re.log.success("API key saved.")}catch(a){i.stop("Verification failed."),a instanceof V&&a.status===401?re.cancel("Invalid API key."):re.cancel(T(a)),process.exit(1)}})}import{existsSync as ln,rmSync as Fc,readFileSync as ir,writeFileSync as Ri}from"fs";import{join as He}from"path";import*as G from"@clack/prompts";var Bc=["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"],Gc=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1430
1334
|
`,` licenseHeartbeatFunction,
|
|
1431
1335
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1432
1336
|
`,` .route("/license", licenseRoutes)
|
|
1433
|
-
`]}];function
|
|
1434
|
-
`).filter(
|
|
1435
|
-
`);return r===n?!1:(
|
|
1337
|
+
`]}];function Kc(e){return(e&&e.length>0?e.map(n=>_t[n]):Object.values(_t)).map(n=>He(n,Yn))}function or(e){return ln(e)?(Fc(e,{recursive:!0}),!0):!1}function Hc(e,t){if(!ln(e))return!1;let n=ir(e,"utf-8"),r=n;for(let o of t)r=r.replace(o,"");return r===n?!1:(Ri(e,r,"utf-8"),!0)}function zc(e){let t=He(e,".gitignore");if(!ln(t))return!1;let n=ir(t,"utf-8"),r=n.split(`
|
|
1338
|
+
`).filter(o=>!o.includes(".generatesaas")).join(`
|
|
1339
|
+
`);return r===n?!1:(Ri(t,r,"utf-8"),!0)}function xi(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=He(t,Ae),r;try{r=JSON.parse(ir(n,"utf-8"))}catch{G.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await G.text({message:'Type "eject" to confirm (this cannot be undone):',validate:s=>{if(s!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(G.isCancel(o)&&(G.cancel("Eject cancelled."),process.exit(0)),r.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.licenseToken}`},body:JSON.stringify({event:"eject",version:r.version,frontend:r.frontend}),signal:AbortSignal.timeout(5e3)}),G.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{G.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],a=[];for(let s of Kc(r.aiTools))or(He(t,s))&&i.push(s);for(let s of Bc)or(He(t,s))&&i.push(s);or(He(t,z))&&i.push(z+"/");for(let s of Gc){let u=He(t,s.file);Hc(u,s.removals)?a.push(s.file):ln(u)&&G.log.warn(`Could not auto-modify ${s.file} - manually remove license/heartbeat references.`)}zc(t)&&a.push(".gitignore");for(let s of i)G.log.info(`Deleted ${s}`);for(let s of a)G.log.info(`Modified ${s}`);G.log.success("Ejected successfully. This project is now fully standalone.")})}var ze=new Jc().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.0.1").addHelpText("after",`
|
|
1436
1340
|
Examples:
|
|
1437
1341
|
$ generatesaas init Interactive setup
|
|
1438
1342
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1439
1343
|
$ generatesaas status Check for updates
|
|
1440
1344
|
$ generatesaas auth Set or update API key
|
|
1441
|
-
`);
|
|
1345
|
+
`);mi(ze);vi(ze);ki(ze);Ai(ze);Pi(ze);xi(ze);ze.parseAsync().catch(e=>{Ti.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|