generatesaas 3.1.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,113 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as kl}from"commander";import*as os from"@clack/prompts";import{existsSync as Nc,readdirSync as Cc,rmSync as $c}from"fs";import{join as Lc,resolve as jc}from"path";import{Option as ne}from"commander";import*as b from"@clack/prompts";import*as Rt from"@clack/prompts";import er from"picocolors";function Ur(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Rt.intro(er.bgYellow(er.black(t)))}function Fr(){Rt.outro(er.yellow("Happy building!"))}import*as u from"@clack/prompts";import h from"picocolors";var at={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},Pt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},At={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},It={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Vr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ie={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var G={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Te={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},_e={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},He=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],Ye=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],cs=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ie(e){return cs.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var se={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},Oe=Object.keys(se);function tr(e){let t=[];for(let r of He)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of Ye)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Br=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function We(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var qe=["fullstack","separate"],ze=["stripe","polar","none"],Je=["smtp","ses","resend"];var Kr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],B=["sentry","posthog"];function Gr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Tt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function _t(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Hr=["runner"];function rr(e){if(!Hr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function ct(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function Yr(e){return Hr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Wr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function qr(e){let t=ls(e,e.desktopAi);return delete e.desktopAi,t}function ls(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function zr(e){let t={};if(e.name!==void 0){if(!_t(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),rr(t),ct(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ae.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ae.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ce.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ce.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Oe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Oe.join(", ")}`);let r=se[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var Xe={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Jr(e){let t=e.projectName??Xe.projectName,r=e.projectDir??`./${t}`,n=e.appName??Tt(t),i=e.deploymentTarget??Xe.deploymentTarget,o=G[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":Xe.databaseProvider),a=e.cacheProvider??(o?"upstash":Xe.cacheProvider),p=e.emailProvider??(o?"resend":Xe.emailProvider),m={...Xe,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};m.paymentProvider==="none"&&(m.credits=!1);for(let g of He){if(m.deploymentTarget!==g.target)continue;let k=m.databaseProvider===g.provider?"database":"cache";if(m.databaseProvider===g.provider||m.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ye)if(m.architecture===g.architecture&&m.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ie(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return ct(m),m}function S(e){u.isCancel(e)&&(u.cancel("Setup cancelled."),process.exit(0))}function nr(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Xr(e,t){let r=!1;e&&rr(e),e&&ct(e),u.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!_t(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Tt(n),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return S(c),c==="."?process.cwd():c})();u.log.info(h.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[...Oe.map(d=>({value:d,label:se[d].label,hint:se[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(S(c),c!=="custom"){let d=se[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,u.log.info(`${se[c].label}: ${se[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});S(c),a=c}let p=e?.architecture?Ye.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let m=ie({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ye.filter(c=>c.target===a).map(c=>c.architecture)),k=qe.filter(c=>!g.has(c)),A=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return u.log.info(`Auto-selected ${at[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:k.map(d=>({value:d,label:at[d].label,hint:at[d].hint}))});return S(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ce.filter(T=>!He.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return S(d),d})(),$=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=le.filter(T=>!He.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${_e[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:_e[T].label,hint:_e[T].hint}))});return S(d),d})();if(G[a]?.edgeRuntime){let c=Br.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),d=[` Deploy target: ${h.cyan(
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`).
|
|
13
|
-
`)}
|
|
14
|
-
`).
|
|
15
|
-
|
|
16
|
-
`).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await Y(n,`${s}
|
|
17
|
-
`,"",`ai.mdx ${t} hub-table row`,r)}async function pn(e,t,r,n,i){let o=ut(e,"docs/(platform)");await Ds(ut(o,t),{recursive:!0}),await Y(ut(o,"meta.json"),` "${t}",
|
|
18
|
-
`,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await Cs(o,s,n);i!==void 0&&await $s(o,i,n)}function Ls(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
|
|
19
|
-
`;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
|
|
20
|
-
`&&(t+=`
|
|
21
|
-
`),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
|
|
22
|
-
`&&(t+=`
|
|
23
|
-
`),r++;r++;continue}t+=n,r++}return t}async function dn(e){let t=`import { config } from "@repo/config";
|
|
24
|
-
`,r=await mt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Ls(n);/\bconfig\b/.test(i)||await l(e,n)}var js=["apps/web/public/images/blog"];async function fn(e){let t=Q(e,"packages/content"),r=[];try{r=(await mn(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...js.map(n=>fr(Q(e,n),{recursive:!0,force:!0})),...r.map(n=>fr(Q(t,n,"blog"),{recursive:!0,force:!0}))])}var Ms=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function hn(e){let t="removeDesktopDemoScreen";await fr(Q(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Ms){let n=Q(e,r);await ht(n,Z(await ft(n,"utf-8"),r,"demo",t))}}var Us="packages/config/src/blog.ts";async function gn(e){let t=Q(e,Us),r=await ft(t,"utf-8"),n=un(un(r,"blogCategories",t),"blogAuthors",t);await ht(t,n)}function un(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function yn(e){let t=Q(e,"packages/i18n/translations"),r;try{r=await mn(t)}catch{return}for(let n of r){let i=Q(t,n,"web.json"),o;try{o=await ft(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await ht(i,JSON.stringify(s,null," ")+`
|
|
25
|
-
`))}}var Fs="packages/config/src/ai/tasks.ts",Vs="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Bs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function vn(e){let t=Q(e,Fs),r=await ft(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Vs,Bs);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await ht(t,i)}async function bn(e){let t=Q(e,".claude","settings.json"),r;try{r=await ft(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Ks)),await ht(t,JSON.stringify(n,null," ")+`
|
|
26
|
-
`)}function Ks(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as wn}from"path";var Gs={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Hs={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Ys={redis:"Redis",upstash:"Upstash Redis"},Ws={node:"Node.js / Docker",vercel:"Vercel"},jt="apps/web",kn="Next.js 16",qs="`app/` routes, `components/`, `lib/`",zs={stripe:"Stripe",polar:"Polar"};function Js(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${jt}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=Ys[e.cacheProvider],o=Ws[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
|
|
27
|
-
- **Payments:** ${zs[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",m=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${jt}/i18n/request.ts\`.`;return`# AGENTS.md
|
|
28
|
-
|
|
29
|
-
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
30
|
-
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
31
|
-
much standing context makes the agent rigid and stops it checking the real code.
|
|
32
|
-
|
|
33
|
-
## Before you build anything (read this first)
|
|
34
|
-
|
|
35
|
-
This boilerplate already ships ~30 features, every one config-gated and wired end to
|
|
36
|
-
end. Before writing a new file, route, table, or component, assume it ALREADY EXISTS
|
|
37
|
-
and go find it:
|
|
38
|
-
|
|
39
|
-
1. \`docs/(platform)/index.mdx\` - the catalog of every shipped feature and its config flag.
|
|
40
|
-
2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
|
|
41
|
-
3. Search \`packages/\` and \`${jt}/\` for the name before creating anything.
|
|
42
|
-
|
|
43
|
-
Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
|
|
44
|
-
billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
|
|
45
|
-
storage & uploads, admin panel, user settings, audit logs, API keys, onboarding,
|
|
46
|
-
waitlist, blog, banners, i18n, theming, dashboard shell, marketing site, background jobs.
|
|
47
|
-
|
|
48
|
-
New code is the last resort, not the first. Duplicating an existing feature, config
|
|
49
|
-
flag, route, or translation is the most common and most costly mistake in this repo.
|
|
50
|
-
|
|
51
|
-
## Stack
|
|
52
|
-
|
|
53
|
-
- **Frontend:** ${kn} ${r}
|
|
54
|
-
- **API:** Hono, RPC-typed. ${n}
|
|
55
|
-
- **Database:** Drizzle ORM + ${Gs[e.databaseProvider]}
|
|
56
|
-
- **Cache + jobs:** ${i} + Inngest
|
|
57
|
-
- **Auth:** Better Auth${s}
|
|
58
|
-
- **Email:** ${Hs[e.emailProvider]}
|
|
59
|
-
- **Deploy:** ${o}
|
|
60
|
-
|
|
61
|
-
## Where things live (extend these - don't reinvent)
|
|
62
|
-
|
|
63
|
-
- \`packages/config/src\` - feature flags, routes, site/pricing config. **Check the flag before building or rendering a toggleable feature.**
|
|
64
|
-
- \`packages/api/src\` - Hono routes (\`routes/\`), business logic (\`services/\`), background jobs (\`functions/\`, Inngest).
|
|
65
|
-
- \`packages/database/src\` - Drizzle schema + queries (\`db/auth.ts\` is generated - see *Don't modify*).
|
|
66
|
-
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
67
|
-
- \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
|
|
68
|
-
- \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
|
|
69
|
-
- \`${jt}\` - the ${kn} app (${qs}).${p}
|
|
70
|
-
- \`docs/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${a}.
|
|
71
|
-
|
|
72
|
-
## Code style
|
|
73
|
-
|
|
74
|
-
- TypeScript strict - no \`any\`, no unsafe casts (\`as any\`, \`as unknown as\`).
|
|
75
|
-
- JSDoc on exported functions/composables/utilities; no inline comments unless asked.
|
|
76
|
-
- Reach for the existing libs (Better Auth, Drizzle, Hono) before hand-rolling - check their docs first.
|
|
77
|
-
|
|
78
|
-
## Don't modify
|
|
79
|
-
|
|
80
|
-
- \`pnpm-lock.yaml\` (you own lockfile changes intentionally - use \`pnpm add\`/\`pnpm remove\`, not hand edits) and don't hand-edit \`package.json\` deps.
|
|
81
|
-
- \`packages/database/src/db/auth.ts\` - regenerated by \`pnpm auth:generate\`. Add user fields via \`additionalFields\` in \`packages/auth/src/config.ts\`, never here.
|
|
82
|
-
|
|
83
|
-
## Gotchas (where agents trip)
|
|
84
|
-
|
|
85
|
-
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
86
|
-
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
87
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${m} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
88
|
-
- **Navigation:** \`next/link\` for links; \`redirect()\` from \`next/navigation\` for programmatic redirects in Server Components.
|
|
89
|
-
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
90
|
-
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
91
|
-
|
|
92
|
-
## Backend packages target multiple runtimes
|
|
93
|
-
|
|
94
|
-
In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\` (not \`node:crypto\`), the \`node:\` import prefix, \`Uint8Array\` over \`Buffer\`, global \`performance.now()\`.
|
|
95
|
-
|
|
96
|
-
## This project
|
|
97
|
-
|
|
98
|
-
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
99
|
-
`}async function En(e){await l(wn(e.projectDir,"AGENTS.md"),Js(e)),await l(wn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
100
|
-
`)}import{join as Xs}from"path";var Sn="apps/web",hr="Next.js 16",Zs={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function Qs(e){let t=e.appName.trim()||e.projectName,r=Zs[e.databaseProvider],n=e.architecture==="fullstack"?`${hr} app at \`${Sn}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${hr} app at \`${Sn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
2
|
+
import{Command as $l}from"commander";import*as uo from"@clack/prompts";import{existsSync as zc,readdirSync as qc,rmSync as Jc}from"fs";import{join as Xc,resolve as Zc}from"path";import{Option as Q}from"commander";import*as b from"@clack/prompts";import*as Pt from"@clack/prompts";import er from"picocolors";function Vr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Pt.intro(er.bgYellow(er.black(t)))}function Br(){Pt.outro(er.yellow("Happy building!"))}import*as m from"@clack/prompts";import h from"picocolors";var lt={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)"}},Rt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},It={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Tt={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Kr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Re={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var H={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Ie={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},Te={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},Be=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],Ke=[{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)."}],fo=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ne(e){return fo.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var ie={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},_e=Object.keys(ie);function tr(e){let t=[];for(let r of Be)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of Ke)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Gr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Ge(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var He=["fullstack","separate"],Ye=["stripe","polar","none"],We=["smtp","ses","resend"];var Hr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],se=["node","vercel"],ae=["postgres","neon","supabase"],ce=["redis","upstash"],V=["sentry","posthog"];function Yr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function _t(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ot(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Wr=["runner"];function rr(e){if(!Wr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function pt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function zr(e){return Wr.some(r=>e[r]===!0)&&(e.ai=!0),e}function qr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function Jr(e){let t=ho(e,e.desktopAi);return delete e.desktopAi,t}function ho(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Xr(e){let t={};if(e.name!==void 0){if(!Ot(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.projects!==void 0&&(t.projects=e.projects),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),rr(t),pt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!se.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${se.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ae.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ae.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ce.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ce.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!V.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${V.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!_e.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${_e.join(", ")}`);let r=ie[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,projects:!1,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Zr(e){let t=e.projectName??ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??_t(t),i=e.deploymentTarget??ze.deploymentTarget,s=H[i]?.edgeRuntime??!1,o=e.databaseProvider??(s?"neon":ze.databaseProvider),a=e.cacheProvider??(s?"upstash":ze.cacheProvider),p=e.emailProvider??(s?"resend":ze.emailProvider),u={...ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:o,cacheProvider:a,emailProvider:p};u.paymentProvider==="none"&&(u.credits=!1);for(let g of Be){if(u.deploymentTarget!==g.target)continue;let k=u.databaseProvider===g.provider?"database":"cache";if(u.databaseProvider===g.provider||u.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ke)if(u.architecture===g.architecture&&u.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ne(u);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return pt(u),u}function R(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function nr(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Qr(e,t){let r=!1;e&&rr(e),e&&pt(e),m.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Ot(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return R(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await m.text({message:"App name:",initialValue:_t(n),validate:d=>{if(!d?.trim())return"App name is required."}});return R(c),c})(),s=e?.projectDir??await(async()=>{r=!0;let c=await m.text({message:"Project location:",initialValue:`./${n}`});return R(c),c==="."?process.cwd():c})();m.log.info(h.bold("Infrastructure"));let o={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await m.select({message:"Infrastructure:",options:[..._e.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(R(c),c!=="custom"){let d=ie[c].values;o.deploymentTarget=d.deploymentTarget,o.databaseProvider=d.databaseProvider,o.cacheProvider=d.cacheProvider,m.log.info(`${ie[c].label}: ${ie[c].hint}.`)}}let a=e?.deploymentTarget??o.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&o.deploymentTarget===void 0){r=!0;let c=await m.select({message:"Deployment target:",options:se.map(d=>({value:d,label:H[d].label,hint:H[d].hint}))});R(c),a=c}let p=e?.architecture?Ke.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let u=ne({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let w=ne({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ke.filter(c=>c.target===a).map(c=>c.architecture)),k=He.filter(c=>!g.has(c)),P=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return m.log.info(`Auto-selected ${lt[d].label} architecture (only compatible option for ${H[a].label}).`),d}r=!0;let c=await m.select({message:"Architecture:",options:k.map(d=>({value:d,label:lt[d].label,hint:lt[d].hint}))});return R(c),c})(),f=e?.databaseProvider??o.databaseProvider??await(async()=>{r=!0;let c=ae.filter(_=>!Be.some(he=>he.target===a&&he.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${Ie[_].label} (only compatible option for ${H[a].label}).`),_}let d=await m.select({message:"Database provider:",options:c.map(_=>({value:_,label:Ie[_].label,hint:Ie[_].hint}))});return R(d),d})(),C=e?.cacheProvider??o.cacheProvider??await(async()=>{r=!0;let c=ce.filter(_=>!Be.some(he=>he.target===a&&he.provider===_));if(c.length===1){let _=c[0];return m.log.info(`Auto-selected ${Te[_].label} (only compatible option for ${H[a].label}).`),_}let d=await m.select({message:"Cache provider:",options:c.map(_=>({value:_,label:Te[_].label,hint:Te[_].hint}))});return R(d),d})();if(H[a]?.edgeRuntime){let c=Gr.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);m.note(c,"Unavailable on edge runtime")}m.log.info(h.bold("Features"));let U=e?.paymentProvider??await(async()=>{r=!0;let c=await m.select({message:"Payment provider:",options:Ye.map(d=>({value:d,label:Rt[d].label,hint:Rt[d].hint}))});return R(c),c})(),Ee=e?.defaultCurrency??await(async()=>{if(U==="none")return"USD";r=!0;let c=await m.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Re[d].name}))});return R(c),c})(),ee=e?.emailProvider??await(async()=>{r=!0;let c=await m.select({message:"Email provider:",options:We.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return R(c),c})(),Fe=e?.observability??await(async()=>{r=!0;let c=await m.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:V.map(d=>({value:d,label:Tt[d].label,hint:Tt[d].hint}))});return R(c),c})(),Se=e?.multiTenancy??await(async()=>{r=!0;let c=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return R(c),c})(),v=e?.projects??await(async()=>{r=!0;let c=await m.confirm({message:"Enable projects (a switcher that scopes a user's work)?",initialValue:!1});return R(c),c})(),L=e?.docs??await(async()=>{r=!0;let c=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return R(c),c})(),te=t?.desktopAllowed!==!1,J=e?.desktop??(te?await(async()=>{r=!0;let c=await m.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),T=e?.ai??await(async()=>{r=!0;let c=await m.confirm({message:"Add AI features? (chat, models, automations, integrations - and unlocks the runner)",initialValue:!1});return R(c),c})(),fe=t?.runnerAllowed!==!1,Ae=e?.webAi===!1,F=!T||w||Ae?!1:e?.runner??(fe?await(async()=>{r=!0;let c=await m.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return R(c),c})():(m.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));T&&w?m.log.info(h.dim(`Runner: ${H[a].label} cannot hold a connection open - skipped.`)):T&&Ae&&m.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let re=e?.webAi??(J&&T&&!F?await(async()=>{r=!0;let c=await m.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return R(c),c})():!0);pt({webAi:re,ai:T,desktop:J,runner:F});let At=e?.revenueSharing??await(async()=>{r=!0;let c=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return R(c),c})(),Ve=U==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return R(c),c})(),I=e?.demo,Pe=nr({databaseProvider:f,cacheProvider:C,paymentProvider:U,emailProvider:ee,demo:I}),ct={};if(Pe.length>0&&r){m.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Pe)if(r=!0,c.secret){let d=await m.password({message:c.message,mask:"*"});R(d),typeof d=="string"&&d.trim()&&(ct[c.key]=d.trim())}else{let d=await m.text({message:c.message,placeholder:c.placeholder});R(d),typeof d=="string"&&d.trim()&&(ct[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(s)}`,` Architecture: ${h.cyan(lt[P].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${h.cyan(H[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Ie[f].label)}`,` Cache: ${h.cyan(Te[C].label)}`].filter(Boolean).join(`
|
|
5
|
+
`),_=[U!=="none"?` Payment: ${h.cyan(Rt[U].label)} (${Ee})`:` Payment: ${h.dim("none")}`,` Credits: ${Ve?h.cyan("Yes"):h.dim("No")}`,` AI features: ${T?h.cyan("Yes"):h.dim("No")}`,...T?[` Runner: ${F?h.cyan("Yes"):h.dim("No")}`]:[],...re?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(It[ee].label)}`,` Observability: ${Fe.length===0?h.dim("none"):h.cyan(Fe.map(Qt=>Tt[Qt].label).join(", "))}`,` Multi-tenancy: ${Se?h.cyan("Yes"):h.dim("No")}`,` Projects: ${v?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${L?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${J?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${At?h.cyan("Yes"):h.dim("No")}`].join(`
|
|
6
|
+
`),he=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),_];if(Pe.length>0){let Qt=Pe.map(Fr=>{let mo=ct[Fr.key]?h.green("provided"):h.dim("skipped");return` ${Fr.key}: ${mo}`}).join(`
|
|
7
|
+
`);he.push("",h.bold("Credentials"),Qt)}m.note(he.join(`
|
|
8
|
+
`),"Summary");let Mr=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Mr)||!Mr)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:s,architecture:P,deploymentTarget:a,databaseProvider:f,cacheProvider:C,paymentProvider:U,emailProvider:ee,observability:Fe,multiTenancy:Se,projects:v,docs:L,desktop:J,ai:T,webAi:re,runner:F,revenueSharing:At,credits:Ve,defaultCurrency:Ee,...Object.keys(ct).length>0?{credentials:ct}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...I!==void 0?{demo:I}:{}}}import{createReadStream as dn,existsSync as Po}from"fs";import{mkdir as Ro}from"fs/promises";import{join as Io}from"path";import{Readable as To}from"stream";import{pipeline as ur}from"stream/promises";import{extract as _o}from"tar";import{join as Oe}from"path";import{homedir as go}from"os";var dt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",Y=".generatesaas",ge=Oe(Y,"manifest.json"),en="nextjs",ir="nuxt",or="2.4.1",tn=Oe(Y,"hashes.json"),xt=Oe(Y,"template-hashes.json"),Dt=Oe(Y,"template"),rn=Oe(Y,"staging"),nn=Oe(Y,"staging.json"),le=Oe(go(),".generatesaas");var $=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function pe(e){return{apiKey:e,baseUrl:dt}}async function ye(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.3.0"}});if(!i.ok){let s,o;try{o=await i.json(),s=o.error??`API ${i.status}: ${t}`}catch{s=`API ${i.status}: ${t}`}throw new $(i.status,s,o)}return i}import{existsSync as yo,readFileSync as vo,writeFileSync as wo,mkdirSync as bo}from"fs";import{dirname as ko}from"path";import*as ve from"@clack/prompts";function ut(){if(!yo(le))return null;try{let e=JSON.parse(vo(le,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&ve.log.warning(`Found old GitHub token in ${le}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function xe(e){bo(ko(le),{recursive:!0}),wo(le,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function qe(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=ut();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return mt()}async function mt(){let e=await ve.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return ve.isCancel(e)&&(ve.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Eo}from"fs/promises";async function we(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Eo(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 ye(e,"/versions")).json()}async function on(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await ye(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof $&&r.status===404)return null;throw r}}async function sn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await ye(e,`/skill/${encodeURIComponent(t)}`)).json()}function Nt(e){if(!(e instanceof $)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var sr="nextjs";function an(e){return{frontend:sr,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:!0,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function ar(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await ye(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function cn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await ye(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function cr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function ln(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var lr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".next-e2e-web",".next-e2e-desktop",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results",".drive-out",".mastra"]),pr=new Set(["pnpm-lock.yaml"]);function Je(e){if(dr(e))return!0;for(let t of e.split("/"))if(pr.has(t))return!0;return!1}var So=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),pn=["scripts/docs-lint.ts"],Ao=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","apps/web/tests/content/competitor-claims.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function dr(e){let t=e.split("/");for(let r of t)if(lr.has(r))return!0;if(pn.includes(e)||pn.some(r=>r.startsWith(e+"/")))return!1;if(So.has(t[0]))return!0;for(let r of Ao)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function Ct(e,t,r){await Ro(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Io(n,`v${t}.tar.gz`);if(!Po(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ur(dn(a),mr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await ur(dn(i),mr(r));return}let s=await ye(e,`/template/${encodeURIComponent(t)}`);if(!s.body)throw new Error("Empty response body");let o=To.fromWeb(s.body);await ur(o,mr(r))}function mr(e){return _o({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!dr(r):!0},sync:!1})}import{readdir as Lt,readFile as Xe,rm as mn,rmdir as Oo,writeFile as ft}from"fs/promises";import{join as B}from"path";async function fn(e){let t;try{t=await Lt(e,{withFileTypes:!0})}catch{return!1}let r=!1;for(let n of t){let i=B(e,n.name);if(n.isDirectory()){await fn(i)&&(r=!0);continue}if(n.name.startsWith("_")){r=!0;continue}await mn(i,{force:!0})}return r||await Oo(e).catch(()=>{}),r}async function hn(e){let t=B(e,"packages/content"),r=[];try{r=(await Lt(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name)}catch{return}let n=new Set;for(let o of r){let a=B(t,o),p;try{p=(await Lt(a,{withFileTypes:!0})).filter(u=>u.isDirectory())}catch{continue}for(let u of p)n.add(u.name),await fn(B(a,u.name))}let i=await Co(e),s=new Set([...n].filter(o=>i===void 0||i.has(o)));await Promise.all([...s].map(o=>mn(B(e,"apps/web/public/images",o),{recursive:!0,force:!0}))),await $o(e,s)}var xo="packages/config/src/index.ts",Do=/\bcontent:\s*\{[\s\S]*?\bsections:\s*\[([\s\S]*?)\]/,No=/\bslug:\s*"([^"]+)"/g;async function Co(e){let t;try{t=await Xe(B(e,xo),"utf-8")}catch{return}let r=Do.exec(t)?.[1];if(r===void 0)return;let n=[...r.matchAll(No)].map(i=>i[1]).filter(i=>i!==void 0);return n.length>0?new Set(n):void 0}var Lo="packages/translate/.meta/mdx-translation-meta.json";async function $o(e,t){if(t.size===0)return;let r=B(e,Lo),n;try{n=JSON.parse(await Xe(r,"utf-8"))}catch{return}if(typeof n!="object"||n===null)return;let i=n;if(typeof i.files!="object"||i.files===null)return;let s=i.files,o={};for(let[a,p]of Object.entries(s)){let u=a.split("/"),w=u.length>1?u[0]:void 0,g=u[u.length-1]?.startsWith("_")===!0;w!==void 0&&t.has(w)&&!g||(o[a]=p)}await ft(r,JSON.stringify({...i,files:o},null," ")+`
|
|
11
|
+
`)}var jo="packages/config/src/blog.ts";async function gn(e){let t=B(e,jo),r=await Xe(t,"utf-8"),n=un(un(r,"blogCategories",t),"blogAuthors",t);await ft(t,n)}function un(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function yn(e){let t=B(e,"packages/i18n/translations"),r;try{r=await Lt(t)}catch{return}for(let n of r){let i=B(t,n,"web.json"),s;try{s=await Xe(i,"utf-8")}catch{continue}let o=JSON.parse(s);!o.content?.categories||o.content.categories.blog===void 0||(o.content.categories.blog={},await ft(i,JSON.stringify(o,null," ")+`
|
|
12
|
+
`))}}var Uo="packages/config/src/ai/tasks.ts",Mo="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Fo="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function vn(e){let t=B(e,Uo),r=await Xe(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Mo,Fo);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await ft(t,i)}async function wn(e){let t=B(e,".claude","settings.json"),r;try{r=await Xe(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Vo)),await ft(t,JSON.stringify(n,null," ")+`
|
|
13
|
+
`)}function Vo(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{readFileSync as Xo}from"fs";import{dirname as Zo,join as hr}from"path";import{fileURLToPath as Qo}from"url";import{existsSync as Bo}from"fs";import{join as bn}from"path";function $t(e,t,r){let n=bn(e,...t);return Bo(n)?n:bn(e,r)}import{mkdir as Ko,readdir as Go,rm as Ho,rmdir as Yo,writeFile as Wo}from"fs/promises";import{dirname as jt,join as zo,relative as qo,sep as Jo}from"path";function De(e){return e.split(Jo).join("/")}async function Ut(e){await Ko(e,{recursive:!0})}async function l(e,t){await Ut(jt(e)),await Wo(e,t,"utf-8")}async function Mt(e,t){await Ho(e,{force:!0});let r=jt(e);for(;r!==t&&r!==jt(r);){try{await Yo(r)}catch{return}r=jt(r)}}async function de(e,t,r,n){let i=[],s=await Go(e,{withFileTypes:!0});for(let o of s){let a=zo(e,o.name),p=De(qo(t,a));r(p)||(o.isDirectory()?i.push(...await de(a,t,r,n)):o.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}var es={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},ts={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},rs={redis:"Redis",upstash:"Upstash Redis"},ns={node:"Node.js / Docker",vercel:"Vercel"},fr="apps/web",is="Next.js 16",os="`app/` routes, `components/`, `lib/`",ss={stripe:"Stripe",polar:"Polar"};function as(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${fr}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=rs[e.cacheProvider],s=ns[e.deploymentTarget],o=e.paymentProvider==="none"?"":`
|
|
14
|
+
- **Payments:** ${ss[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",u=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${fr}/i18n/request.ts\`.`;return ls({archSuffix:r,apiLocation:n,databaseName:es[e.databaseProvider],cacheName:i,paymentLine:o,emailName:ts[e.emailProvider],deployName:s,runnerBullet:p,desktopDocsRef:a,i18nRule:u,webAppDir:fr,webAppName:is,webAppLayout:os})}function cs(){return $t(Zo(Qo(import.meta.url)),["generators","content"],"content")}function ls(e){let t=Xo(hr(cs(),"AGENTS.template.md"),"utf-8"),r=new Map(Object.entries(e)),n=t.replace(/\{\{(\w+)\}\}/g,(s,o)=>{let a=r.get(o);if(a===void 0)throw new Error(`AGENTS.template.md uses unknown token {{${o}}}`);return a}),i=/\{\{[^}]*\}\}/.exec(n);if(i)throw new Error(`AGENTS.template.md carries an unrendered token: ${i[0]}`);return n}async function kn(e){await l(hr(e.projectDir,"AGENTS.md"),as(e)),await l(hr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
15
|
+
`)}import{join as ps}from"path";var En="apps/web",gr="Next.js 16",ds={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function us(e){let t=e.appName.trim()||e.projectName,r=ds[e.databaseProvider],n=e.architecture==="fullstack"?`${gr} app at \`${En}/\` 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.`:`${gr} app at \`${En}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
101
16
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
102
17
|
- API: http://localhost:3010
|
|
103
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
104
|
-
|
|
18
|
+
- Inngest dev server: http://127.0.0.1:8288`,s=e.ai?`pnpm mastra:studio # optional: inspect the AI assistant and its memory (localhost:4111)
|
|
19
|
+
`:"",o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
20
|
+
`,a=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
|
|
105
21
|
|
|
106
22
|
${n}
|
|
107
23
|
|
|
108
24
|
## Stack
|
|
109
25
|
|
|
110
|
-
- **Frontend:** ${
|
|
26
|
+
- **Frontend:** ${gr}
|
|
111
27
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
112
28
|
- **Auth:** Better Auth
|
|
113
29
|
- **ORM / DB:** Drizzle + ${r}
|
|
@@ -123,7 +39,7 @@ pnpm install
|
|
|
123
39
|
# reference. All apps load the single root \`.env\`.
|
|
124
40
|
${o}pnpm db:setup # first run: create the database schema (idempotent)
|
|
125
41
|
pnpm dev
|
|
126
|
-
\`\`\`
|
|
42
|
+
${s}\`\`\`
|
|
127
43
|
|
|
128
44
|
${i}
|
|
129
45
|
|
|
@@ -140,12 +56,11 @@ App-level configuration lives in \`packages/config/src/index.ts\`. Translation s
|
|
|
140
56
|
\`\`\`bash
|
|
141
57
|
pnpm db:setup # apply the database schema (idempotent)
|
|
142
58
|
pnpm -F @repo/database push # push schema changes only
|
|
143
|
-
pnpm
|
|
144
|
-
pnpm -F @repo/database studio # open Drizzle Studio
|
|
59
|
+
pnpm drizzle:studio # open Drizzle Studio (browse and edit tables)
|
|
145
60
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
146
61
|
\`\`\`
|
|
147
62
|
|
|
148
|
-
${
|
|
63
|
+
${a}
|
|
149
64
|
|
|
150
65
|
## Removing the GenerateSaaS license
|
|
151
66
|
|
|
@@ -158,27 +73,29 @@ pnpm dlx generatesaas eject
|
|
|
158
73
|
## Updates
|
|
159
74
|
|
|
160
75
|
To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
|
|
161
|
-
`}async function
|
|
76
|
+
`}async function Sn(e){await l(ps(e.projectDir,"README.md"),us(e))}import{access as ms}from"fs/promises";import{join as Ft}from"path";async function fs(e,t,r){let n=Ft(e,"apps/electron/dev-app-update.yml");try{await ms(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
|
|
162
77
|
url: ${t}
|
|
163
78
|
updaterCacheDirName: ${r}
|
|
164
|
-
`)}function
|
|
165
|
-
`):'{ enabled: false, clientId: "runner" }'}function
|
|
79
|
+
`)}function hs(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function gs(e,t){let r=Yr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var Ze={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function ys(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(Ze.name)},`,` binary: ${JSON.stringify(Ze.binary)},`,` envPrefix: ${JSON.stringify(Ze.envPrefix)},`,` repoUrl: ${JSON.stringify(Ze.repoUrl)},`,` installBase: ${JSON.stringify(Ze.installBase)},`,` image: ${JSON.stringify(Ze.image)}`," }"," }"].join(`
|
|
80
|
+
`):'{ enabled: false, clientId: "runner" }'}function vs(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
|
|
166
81
|
`),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
|
|
167
82
|
`)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
|
|
168
83
|
`):`${t}
|
|
169
84
|
observability: {
|
|
170
85
|
${r.join(`,
|
|
171
86
|
`)}
|
|
172
|
-
},`}async function
|
|
87
|
+
},`}async function An(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",s=hs(i),o=e.demo?"false":"true",a=e.multiTenancy?`{
|
|
173
88
|
multiTenant: true,
|
|
174
|
-
organizationLimit: 5
|
|
175
|
-
|
|
89
|
+
organizationLimit: 5,
|
|
90
|
+
defaultOrganizationName: "Personal"
|
|
91
|
+
}`:"{ multiTenant: false }",p=e.projects?"{ enabled: true }":"{ enabled: false }",u=vs(e.observability),w=e.demo?`{
|
|
176
92
|
enableInDev: true,
|
|
177
93
|
chatwoot: {
|
|
178
94
|
baseUrl: "https://support.alexchelan.com",
|
|
179
95
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
180
96
|
}
|
|
181
|
-
}`:"{}",
|
|
97
|
+
}`:"{}",g=e.architecture==="fullstack"?"false":"true",k=gs(t,s),P=`https://cdn.${s}/desktop`,f=ys(e),C=`import type { AgentsConfig, AppConfig } from "@repo/config/types";
|
|
98
|
+
import { resolveAgentsConfig } from "./agents";
|
|
182
99
|
import { desktopConfig } from "./desktop.mjs";
|
|
183
100
|
import { supportConfig } from "./support";
|
|
184
101
|
|
|
@@ -199,14 +116,20 @@ export const config: AppConfig = {
|
|
|
199
116
|
fullSiteName: "${t}",
|
|
200
117
|
domain: "${i}",
|
|
201
118
|
baseUrl: "${n}",
|
|
202
|
-
indexable: ${
|
|
119
|
+
indexable: ${o},
|
|
203
120
|
logo: {
|
|
204
121
|
main: "/images/logo.svg",
|
|
205
122
|
square: "/images/logo-square.svg"
|
|
206
123
|
},
|
|
124
|
+
// The footer's "Built with GenerateSaaS" line. Fill in \`founderName\` to make it read
|
|
125
|
+
// "Built by <you> using GenerateSaaS". DELETE this whole block to remove the line.
|
|
126
|
+
builtWith: {
|
|
127
|
+
founderName: ""
|
|
128
|
+
},
|
|
207
129
|
origins: ["http://localhost:3000", "http://localhost:5173"],
|
|
208
130
|
waitlist: false,
|
|
209
131
|
tenancy: ${a},
|
|
132
|
+
projects: ${p},
|
|
210
133
|
theme: {
|
|
211
134
|
default: "system",
|
|
212
135
|
switcher: true,
|
|
@@ -224,16 +147,16 @@ export const config: AppConfig = {
|
|
|
224
147
|
limitPerSecond: 3,
|
|
225
148
|
senders: {
|
|
226
149
|
transactional: {
|
|
227
|
-
email: "noreply@${
|
|
150
|
+
email: "noreply@${s}",
|
|
228
151
|
senderName: "${t}"
|
|
229
152
|
},
|
|
230
153
|
marketing: {
|
|
231
|
-
email: "hello@${
|
|
154
|
+
email: "hello@${s}",
|
|
232
155
|
senderName: "${t}",
|
|
233
156
|
signatureName: "Alex"
|
|
234
157
|
},
|
|
235
158
|
support: {
|
|
236
|
-
email: "support@${
|
|
159
|
+
email: "support@${s}",
|
|
237
160
|
senderName: "${t} Support"
|
|
238
161
|
}
|
|
239
162
|
},
|
|
@@ -261,8 +184,8 @@ export const config: AppConfig = {
|
|
|
261
184
|
prefix: "key_"
|
|
262
185
|
},
|
|
263
186
|
apiDocs: true,
|
|
264
|
-
performanceMonitor: { enabled: ${
|
|
265
|
-
${
|
|
187
|
+
performanceMonitor: { enabled: ${g} },
|
|
188
|
+
${u}
|
|
266
189
|
notifications: {
|
|
267
190
|
enabled: true,
|
|
268
191
|
maxPerUser: 100,
|
|
@@ -306,28 +229,61 @@ ${p}
|
|
|
306
229
|
}`:`{
|
|
307
230
|
base: "${e.defaultCurrency}",
|
|
308
231
|
list: [
|
|
309
|
-
{ symbol: "${
|
|
232
|
+
{ symbol: "${Re[e.defaultCurrency].symbol}", name: "${Re[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Re[e.defaultCurrency].place}", space: ${Re[e.defaultCurrency].space} }
|
|
310
233
|
],
|
|
311
234
|
countryMap: {
|
|
312
235
|
default: "${e.defaultCurrency}"
|
|
313
236
|
}
|
|
314
237
|
}`},
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
238
|
+
// Content sections: one URL prefix each. Delete an entry to drop the section (its routes
|
|
239
|
+
// then 404); add one to serve a new prefix from \`packages/content/{locale}/{slug}/\`.
|
|
240
|
+
content: {
|
|
241
|
+
sections: [
|
|
242
|
+
{ slug: "blog", template: "article" },
|
|
243
|
+
{ slug: "alternatives", template: "alternatives" },
|
|
244
|
+
{ slug: "compare", template: "compare" }
|
|
245
|
+
],
|
|
246
|
+
// Renamed a section? Add its old slug here and the old URLs 308 to the new ones; see
|
|
247
|
+
// \`ContentRedirect\` for the recipe.
|
|
248
|
+
redirects: [],
|
|
249
|
+
defaults: {
|
|
250
|
+
postsPerPage: 15,
|
|
251
|
+
relatedCount: 3,
|
|
252
|
+
imagePosition: "before-first-h2",
|
|
253
|
+
viewTracking: {
|
|
254
|
+
enabled: true,
|
|
255
|
+
dedupWindowHours: 24
|
|
256
|
+
}
|
|
323
257
|
}
|
|
324
|
-
}
|
|
258
|
+
},
|
|
325
259
|
contentApi: { enabled: false },
|
|
326
260
|
docs: {
|
|
327
261
|
enabled: ${e.docs},
|
|
328
262
|
url: "/docs",
|
|
329
263
|
contentDir: "content/docs"
|
|
330
264
|
},
|
|
265
|
+
// How this site presents itself to AI crawlers and agents. \`markdown\` serves a
|
|
266
|
+
// markdown rendition of every marketing page (by \`Accept: text/markdown\` and at a
|
|
267
|
+
// \`.md\` suffix) plus /llms.txt; the crawler flags below are DECLARATIONS written into
|
|
268
|
+
// robots.txt that a crawler may ignore. Allowing all three is the default because
|
|
269
|
+
// blocking search and live-fetch bots costs the citations that send readers back.
|
|
270
|
+
agents: {
|
|
271
|
+
markdown: true,
|
|
272
|
+
apiCatalog: true,
|
|
273
|
+
crawlers: {
|
|
274
|
+
namedGroups: true,
|
|
275
|
+
search: true,
|
|
276
|
+
userFetch: true,
|
|
277
|
+
training: true,
|
|
278
|
+
contentSignals: {
|
|
279
|
+
search: "yes",
|
|
280
|
+
aiInput: "yes",
|
|
281
|
+
// Unstated on purpose. Set "no" to assert an EU DSM Article 4
|
|
282
|
+
// text-and-data-mining reservation, "yes" to grant training explicitly.
|
|
283
|
+
aiTrain: "unset"
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
},
|
|
331
287
|
ai: {
|
|
332
288
|
enabled: ${e.ai},
|
|
333
289
|
// Where the AI features SHOW UP. False is the desktop-first shape: the AI pages and their nav
|
|
@@ -348,10 +304,42 @@ ${p}
|
|
|
348
304
|
byok: true,
|
|
349
305
|
// What every user starts on (their own choice, once made, always wins). Plain
|
|
350
306
|
// OpenRouter model ids.
|
|
351
|
-
defaults: {
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
307
|
+
defaults: {
|
|
308
|
+
model: "~deepseek/deepseek-v4-flash-latest"
|
|
309
|
+
},
|
|
310
|
+
// The model that NAMES each conversation, per lane - your decision, never a user setting.
|
|
311
|
+
// Every entry is the cheapest sensible model its provider offers: naming fires on every
|
|
312
|
+
// conversation's first message, abandoned one-liners included. A built-in chat bills its naming
|
|
313
|
+
// from the same credits; a BYOK chat names on the user's own key; a desktop coding-CLI chat
|
|
314
|
+
// names THROUGH that CLI on the user's own subscription. Remove an entry to keep prefix titles
|
|
315
|
+
// on that lane.
|
|
316
|
+
titles: {
|
|
317
|
+
builtin: "~deepseek/deepseek-v4-flash-latest",
|
|
318
|
+
byok: {
|
|
319
|
+
openrouter: "~deepseek/deepseek-v4-flash-latest",
|
|
320
|
+
anthropic: "claude-haiku-4-5",
|
|
321
|
+
openai: "gpt-5.6-luna",
|
|
322
|
+
google: "gemini-3.5-flash-lite"
|
|
323
|
+
},
|
|
324
|
+
cli: {
|
|
325
|
+
// "haiku" is Claude Code's rolling alias for the newest Haiku.
|
|
326
|
+
"claude-code": { model: "haiku" },
|
|
327
|
+
codex: { model: "gpt-5.6-luna", effort: "none" },
|
|
328
|
+
// grok's SUBSCRIPTION logins serve only the current pair (4.6/4.5); 4.5 is the cheaper.
|
|
329
|
+
grok: { model: "grok-4.5", effort: "low" },
|
|
330
|
+
opencode: { model: "opencode/deepseek-v4-flash-free", effort: "low" }
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
// The model each coding CLI's interactive TERMINAL session STARTS on, by CLI id - the user
|
|
334
|
+
// switches inside the TUI whenever they want. EMPTY by default: your users drive these CLIs on
|
|
335
|
+
// their OWN subscriptions, so each CLI's own default is the right starting point. Pin one to keep
|
|
336
|
+
// terminal work on a cheaper model, e.g. "claude-code": { model: "haiku" }.
|
|
337
|
+
terminals: {
|
|
338
|
+
cli: {}
|
|
339
|
+
},
|
|
340
|
+
// Let end-users author their own AI automations. Set to false to ship only the
|
|
341
|
+
// create-disabled view (existing automations still list/run/edit/delete).
|
|
342
|
+
userAutomations: true,
|
|
355
343
|
// Server-side chat thread limits: at most \`cap\` stored threads per user (chat history lives in
|
|
356
344
|
// Mastra Memory threads; the server evicts the oldest-by-activity beyond the cap).
|
|
357
345
|
chats: {
|
|
@@ -361,11 +349,17 @@ ${p}
|
|
|
361
349
|
// empty by default (starters are product copy you write for your users).
|
|
362
350
|
chat: {
|
|
363
351
|
suggestions: []
|
|
352
|
+
},
|
|
353
|
+
// Your users can connect ANY HTTP API or MCP server out of the box, through the two built-in
|
|
354
|
+
// generic connectors. Set genericConnectors: false to offer only the curated entries you
|
|
355
|
+
// declare in ai/integrations.ts.
|
|
356
|
+
integrations: {
|
|
357
|
+
genericConnectors: true
|
|
364
358
|
}
|
|
365
359
|
},
|
|
366
360
|
desktop: desktopConfig,
|
|
367
361
|
// Runner: the AgentRunner daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
368
|
-
runner: ${
|
|
362
|
+
runner: ${f},
|
|
369
363
|
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
370
364
|
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
371
365
|
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
@@ -378,45 +372,66 @@ ${p}
|
|
|
378
372
|
revenueSharing: { enabled: ${e.revenueSharing} },
|
|
379
373
|
seo: {
|
|
380
374
|
description: "Production-ready SaaS application",
|
|
381
|
-
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
375
|
+
foundingDate: "${new Date().getFullYear()}-01-01",
|
|
376
|
+
// Google "preferred sources": readers who mark you as preferred see you more often in Top
|
|
377
|
+
// Stories. Off until your domain actually resolves in Google's source preferences tool
|
|
378
|
+
// (https://www.google.com/preferences/source?q=your-domain) - only a domain or subdomain is
|
|
379
|
+
// ever eligible there, never a subdirectory, so the ask renders nothing until one resolves.
|
|
380
|
+
// The default \`"link"\` variant is your OWN button, upgraded on click to a popup window so the
|
|
381
|
+
// reader keeps the page behind them. \`variant: "button"\` swaps in Google's widget, which
|
|
382
|
+
// also opens in place but paints its own white pill and ignores your theme.
|
|
383
|
+
preferredSource: { enabled: true }
|
|
382
384
|
},
|
|
383
385
|
routes: {
|
|
384
386
|
home: "/",
|
|
385
387
|
auth: "/auth",
|
|
386
388
|
loginRedirect: "/dashboard",
|
|
387
389
|
dashboard: "/dashboard",
|
|
388
|
-
pricing: "
|
|
390
|
+
pricing: "/#pricing",
|
|
389
391
|
onboarding: "/onboarding",
|
|
390
392
|
settings: "/settings/profile",
|
|
391
393
|
chat: "/chat",
|
|
392
|
-
|
|
394
|
+
automations: "/automations",
|
|
393
395
|
settingsModels: "/settings/models",
|
|
394
396
|
settingsIntegrations: "/settings/integrations",
|
|
395
397
|
settingsRunners: "/settings/runners",
|
|
396
398
|
settingsMcp: "/settings/mcp",
|
|
399
|
+
settingsBilling: "/settings/billing",
|
|
397
400
|
notifications: "/notifications",
|
|
398
|
-
admin: "/admin/users"
|
|
401
|
+
admin: "/admin/users",
|
|
402
|
+
adminOrganizations: "/admin/organizations",
|
|
403
|
+
adminBillingLogs: "/admin/billing-logs"
|
|
399
404
|
}
|
|
400
405
|
};
|
|
401
406
|
|
|
402
407
|
export const mainCurrency = config.currency.list.find((c) => c.code === config.currency.base)
|
|
403
408
|
?? config.currency.list[0]!;
|
|
404
409
|
|
|
410
|
+
// \`agents\` is optional on AppConfig, so reading it through this resolved constant keeps the
|
|
411
|
+
// fallbacks in one place - they live in \`./agents\`, which ships verbatim. \`apps/web\` reads this
|
|
412
|
+
// export to gate the markdown renditions and robots.txt, both of which break if it goes missing.
|
|
413
|
+
export const agentsConfig: AgentsConfig = resolveAgentsConfig(config.agents);
|
|
414
|
+
|
|
415
|
+
export * from "./agents";
|
|
405
416
|
export * from "./ai-providers";
|
|
406
417
|
export * from "./billing-fields";
|
|
407
418
|
export * from "./social-providers";
|
|
408
419
|
export * from "./blog";
|
|
409
420
|
export * from "./cache";
|
|
421
|
+
export * from "./content";
|
|
410
422
|
export * from "./runner";
|
|
411
423
|
export * from "./footer";
|
|
412
424
|
export * from "./i18n";
|
|
413
425
|
export * from "./landing";
|
|
414
426
|
export * from "./nav-active";
|
|
427
|
+
export * from "./password";
|
|
415
428
|
export * from "./pricing";
|
|
429
|
+
export * from "./projects";
|
|
430
|
+
export * from "./robots";
|
|
416
431
|
export * from "./roles";
|
|
417
432
|
export * from "./section-tabs";
|
|
418
433
|
export * from "./tenancy";
|
|
419
|
-
|
|
434
|
+
`,U=Ft(e.projectDir,"packages/config/src/index.ts");await l(U,C),await l(Ft(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
|
|
420
435
|
|
|
421
436
|
/**
|
|
422
437
|
* Live-chat (support widget) configuration, re-exported by the config index as
|
|
@@ -428,8 +443,8 @@ export * from "./tenancy";
|
|
|
428
443
|
* Node, which cannot resolve the index's extensionless relative imports. Keep any relative
|
|
429
444
|
* import here type-only.
|
|
430
445
|
*/
|
|
431
|
-
export const supportConfig: SupportConfig = ${
|
|
432
|
-
`),await l(
|
|
446
|
+
export const supportConfig: SupportConfig = ${w};
|
|
447
|
+
`),await l(Ft(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
433
448
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
434
449
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
435
450
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -437,35 +452,28 @@ export const supportConfig: SupportConfig = ${m};
|
|
|
437
452
|
|
|
438
453
|
export const desktopConfig = {
|
|
439
454
|
enabled: ${e.desktop},
|
|
440
|
-
appId: "${
|
|
441
|
-
productName: "${
|
|
442
|
-
protocol: "${
|
|
455
|
+
appId: "${k.appId}",
|
|
456
|
+
productName: "${k.productName}",
|
|
457
|
+
protocol: "${k.protocol}",
|
|
443
458
|
baseUrl: "${n}",
|
|
444
459
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
445
460
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
446
461
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
447
|
-
autoUpdate: { url: "${
|
|
462
|
+
autoUpdate: { url: "${P}" },
|
|
448
463
|
// Whether the support live-chat widget you configured in config.support (Crisp,
|
|
449
464
|
// Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
|
|
450
465
|
// every surface. Set false to keep live chat on your website only - the app then
|
|
451
466
|
// mounts no widget and its CSP never names the provider's origins.
|
|
452
467
|
supportChat: true,
|
|
453
|
-
// Integrations your users connect inside the app by entering their own credentials.
|
|
454
|
-
// Empty by default, which hides the Integrations tab entirely. Everything stays on the
|
|
455
|
-
// user's machine: credentials are encrypted with the OS keychain and never reach your
|
|
456
|
-
// backend.
|
|
457
|
-
// { id, name, description?, kind: "mcp" | "api", credentials: [{ key, label, secret? }], mcp? }
|
|
458
|
-
// An \`mcp\` entry becomes a local MCP server for chats, schedules and terminal sessions
|
|
459
|
-
// once every credential is set; give it \`mcp: { command, args?, env? }\` and reference a
|
|
460
|
-
// credential in an env VALUE as the whole string "{credential:KEY}". An \`api\` entry only
|
|
461
|
-
// stores the credentials - read them from your own main-process code with
|
|
462
|
-
// \`readIntegrationCredentials(id)\`.
|
|
463
|
-
integrations: [],
|
|
464
468
|
agents: {
|
|
465
469
|
// Feature toggles only. Agents run on the agent runtime the app forks from its own
|
|
466
470
|
// binary, supervised by the main process and driven through the @repo/agent-core
|
|
467
471
|
// seam - typed TypeScript wiring next to the markdown prompt files you tune.
|
|
468
472
|
enabled: ${e.desktop&&e.ai},
|
|
473
|
+
// The product instructions every desktop local session opens with (CLI chats and
|
|
474
|
+
// terminal sessions), after the automatic identity line. The desktop counterpart of
|
|
475
|
+
// the web assistant's persona. Unset ships the identity line alone:
|
|
476
|
+
// instructions: "You help users of Acme manage their fleet. Be concise.",
|
|
469
477
|
// Provider ids that ship in this app (catalog ids like "anthropic", "openai").
|
|
470
478
|
// Omitted here, which ships them ALL; add \`providers: ["anthropic", ...]\` to trim
|
|
471
479
|
// the catalog to just the ids you list.
|
|
@@ -474,21 +482,21 @@ export const desktopConfig = {
|
|
|
474
482
|
// "Sign in" is offered only for a provider whose clientId is set here; the
|
|
475
483
|
// boilerplate ships none, so it starts empty.
|
|
476
484
|
oauth: {},
|
|
477
|
-
// Let end users author their own background
|
|
478
|
-
// Set to false to ship only builder-registered
|
|
479
|
-
|
|
485
|
+
// Let end users author their own background automations on the Automations screen.
|
|
486
|
+
// Set to false to ship only builder-registered automations.
|
|
487
|
+
userAutomations: true,
|
|
480
488
|
// Cap how many chat conversations are kept per agent on the user's machine;
|
|
481
489
|
// creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
|
|
482
490
|
maxChatsPerAgent: 20,
|
|
483
491
|
// Whether agent work continues after the window closes. OFF by default: the runtime is a
|
|
484
492
|
// child process of the app and is killed at quit. Turn it on if your product's value
|
|
485
|
-
// depends on
|
|
493
|
+
// depends on automations firing while the app is closed; end users then get a
|
|
486
494
|
// "Keep running after I close the window" toggle.
|
|
487
495
|
background: false
|
|
488
496
|
}
|
|
489
497
|
};
|
|
490
|
-
`),e.desktop&&await
|
|
491
|
-
`)}async function
|
|
498
|
+
`),e.desktop&&await fs(e.projectDir,P,`${k.protocol}-updater`)}import{join as ws}from"path";function bs(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function yr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxConcurrentRuns!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxConcurrentRuns: ${e.maxConcurrentRuns}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
499
|
+
`)}async function Pn(e){let t=ws(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let P=`import type { PricingConfig } from "@repo/config/types";
|
|
492
500
|
|
|
493
501
|
export const pricingConfig: PricingConfig = {
|
|
494
502
|
defaultPlan: "free",
|
|
@@ -517,21 +525,27 @@ export const pricingConfig: PricingConfig = {
|
|
|
517
525
|
credits: { enabled: false },
|
|
518
526
|
products: { enabled: false, items: [] }
|
|
519
527
|
};
|
|
520
|
-
`;await l(t,
|
|
528
|
+
`;await l(t,P);return}let n=e.paymentProvider,i=bs(n),s=e.credits,o=!!e.ai,a=yr({credits:5,rateLimit:100,withCredits:s,...o&&{maxConcurrentRuns:2}}),p=yr({credits:10,rateLimit:1e3,withCredits:s,...o&&{maxConcurrentRuns:5}}),u=yr({credits:40,rateLimit:5e3,withCredits:s,...o&&{maxConcurrentRuns:10}}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
521
529
|
// !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
|
|
522
|
-
// !! ${r} amounts above cover the USD cost per credit (~0.
|
|
523
|
-
// !!
|
|
524
|
-
`;
|
|
530
|
+
// !! ${r} amounts above cover the USD cost per credit (~0.50 USD at creditsPerUsd 1 with the
|
|
531
|
+
// !! 100% markup) - and raise prices or creditsPerUsd if they do not.
|
|
532
|
+
`;s&&r!=="USD"&&console.warn(`
|
|
525
533
|
!! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
526
534
|
!! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
|
|
527
|
-
!! carries ~0.
|
|
535
|
+
!! carries ~0.50 USD of AI cost - verify every ${r} price still covers it (see the comment on the
|
|
528
536
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
529
|
-
`);let g=
|
|
530
|
-
//
|
|
531
|
-
// external APIs, your own features)
|
|
532
|
-
//
|
|
533
|
-
//
|
|
534
|
-
|
|
537
|
+
`);let g=s?` // creditsPerUsd scales USD cost -> credits (1 = 1 credit carries ~0.50 USD of cost after the
|
|
538
|
+
// 100% markup); markupPercent is the DEFAULT margin for everything that debits credits (AI,
|
|
539
|
+
// external APIs, your own features), and credits.markupByCategory overrides it per metered
|
|
540
|
+
// service ("ai", "webSearch", "webExtract"). Two optional knobs shape each debit's size:
|
|
541
|
+
// credits.step is the amount every debit ceils UP to (default 0.000001, the ledger's own
|
|
542
|
+
// scale - raise it to bill in coarser units, max 1 credit) and credits.minCharge is a floor
|
|
543
|
+
// applied after it, for a fixed per-call overhead the provider's price does not cover (max 10
|
|
544
|
+
// credits). Either one set past its cap throws at debit time. Sanity-check whenever
|
|
545
|
+
// you change plan credits, prices, or any markup: each plan's credits / (creditsPerUsd *
|
|
546
|
+
// (1 + your LOWEST markup)) must stay BELOW what that plan earns per credit interval, or full
|
|
547
|
+
// utilization runs you at a loss.
|
|
548
|
+
${w} credits: { enabled: true, creditsPerUsd: 1, markupPercent: 100 }`:" credits: { enabled: false }",k=`import type { PricingConfig } from "@repo/config/types";
|
|
535
549
|
|
|
536
550
|
export const pricingConfig: PricingConfig = {
|
|
537
551
|
defaultPlan: "free",
|
|
@@ -612,7 +626,7 @@ ${i}
|
|
|
612
626
|
anchorAmounts: { ${r}: 349 }
|
|
613
627
|
}
|
|
614
628
|
],
|
|
615
|
-
${
|
|
629
|
+
${u}
|
|
616
630
|
}
|
|
617
631
|
],
|
|
618
632
|
${g},
|
|
@@ -621,11 +635,11 @@ ${g},
|
|
|
621
635
|
items: []
|
|
622
636
|
}
|
|
623
637
|
};
|
|
624
|
-
`;await l(t,k)}var
|
|
625
|
-
`)}var
|
|
626
|
-
`)}async function
|
|
627
|
-
`+
|
|
628
|
-
`+
|
|
638
|
+
`;await l(t,k)}var ks={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"}]},Es={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"},{key:"STRIPE_API_BASE",comment:"# Point the Stripe SDK at another host - a local mock, or a proxy of your own. Unset means api.stripe.com."}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function Vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function ht(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function vr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Tn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var Ss="https://your-app.example.com/api";function Bt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function Rn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Tn(e),s=[];e.architecture==="separate"?s.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):s.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),s.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?s.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):s.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),s.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),s.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),s.push("","# Database"),ht(Vt(Ie[e.databaseProvider].envVars,r),s),s.push("","# Cache"),ht(Vt(Te[e.cacheProvider].envVars,r),s),e.cacheProvider==="redis"&&s.push("# Optional prefix on every Redis key the app writes. Set it when several deployments share","# one Redis instance, or to keep a load test out of the live keyspace.","# Set it once, before first boot. Changing it on a running deployment orphans in-flight","# auto-top-up claims and distributed locks (autotopup:pending:*, withMutex) - drain or use","# a maintenance window first.","#REDIS_KEY_PREFIX="),s.push("","# Authentication"),t==="example"&&s.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Bt(s,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),s.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Bt(s,"CONTENT_API_KEY",vr(32),t),s.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Bt(s,"INNGEST_EVENT_KEY",vr(32),t),Bt(s,"INNGEST_SIGNING_KEY",vr(32),t),s.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(s.push("","# API Port (standalone backend)","API_PORT=3010"),s.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let o=ks[e.emailProvider];if(o&&(s.push("","# Email"),ht(Vt(o,r),s)),e.paymentProvider!=="none"){let p=Es[e.paymentProvider];p&&(s.push("","# Payment"),ht(Vt(p,r),s))}s.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),s.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),s.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),s.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),s.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),s.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(s.push("","# Error and product reporting (optional)"),ht(a,s)),s.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only MODEL provider key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database.","# Override the OpenRouter API base - a gateway or a proxy of your own. It must carry the","# /api/v1 suffix. Unset uses the hosted API.","#OPENROUTER_BASE_URL=https://openrouter.ai/api/v1","","# AI web tools (optional)","# Give the assistant its own web access. A key's presence is the whole switch: set one","# and the model gets its tools, set neither and chat is unchanged. Users still opt in","# per chat with the composer's web-search toggle, and config.ai.webSearch: false","# disables both. Calls bill to user credits - set the price and engine in","# config.ai.webTools.","# EITHER key alone covers both capabilities. Firecrawl is the recommended one, so a","# single signup is the whole setup, and with both keys set Firecrawl serves search","# and extract.","# Firecrawl (recommended) - `web_search` AND `web_extract` (reads one page).","# https://firecrawl.dev/","#FIRECRAWL_API_KEY=","# Parallel (optional) - both tools, cheaper on each, at high quality; extract is slower","# on a page it has not already indexed. Note its customer terms include a license to","# train on submitted queries. Set config.ai.webTools.searchEngine or .extractEngine to",'# "parallel" to use it alongside a Firecrawl key.',"# https://platform.parallel.ai/","#PARALLEL_API_KEY="),e.desktop&&s.push("","# Desktop app (optional)","# Base URL the marketing download page reads the release feed from.","# Unset uses config.desktop.autoUpdate.url.","#DESKTOP_FEED_BASE_URL="),s.push("","# Build output (optional)","# Next's distDir for apps/web. Unset uses .next; the e2e harness sets its own so a test","# build never overwrites a dev server's.","#NEXT_DIST_DIR="),s.push(""),s.join(`
|
|
639
|
+
`)}var In="NEXT_PUBLIC_API_URL";function As(e){let{apiUrl:t}=Tn(e),r=["# API Configuration",`${In}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${In}=${Ss}`),r.push(""),r.join(`
|
|
640
|
+
`)}async function _n(e){let t=As(e);await l(`${e.projectDir}/.env`,t+`
|
|
641
|
+
`+Rn(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
|
|
642
|
+
`+Rn(e,"example"))}import{join as Ps}from"path";async function On(e){let t=Ge(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
|
|
629
643
|
image: postgres:18-alpine
|
|
630
644
|
restart: unless-stopped
|
|
631
645
|
ports:
|
|
@@ -660,7 +674,7 @@ ${g},
|
|
|
660
674
|
- "\${MAILPIT_UI_PORT:-8025}:8025"
|
|
661
675
|
environment:
|
|
662
676
|
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
|
663
|
-
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let
|
|
677
|
+
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let o=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
|
|
664
678
|
image: inngest/inngest:v1.17.4
|
|
665
679
|
restart: unless-stopped
|
|
666
680
|
ports:
|
|
@@ -675,232 +689,34 @@ ${g},
|
|
|
675
689
|
# Linux, which is what \`extra_hosts\` supplies.
|
|
676
690
|
command: >-
|
|
677
691
|
inngest dev
|
|
678
|
-
-u ${
|
|
692
|
+
-u ${o}
|
|
679
693
|
extra_hosts:
|
|
680
|
-
- "host.docker.internal:host-gateway"`)}let
|
|
694
|
+
- "host.docker.internal:host-gateway"`)}let s=`name: ${`${e.projectName}-infra`}
|
|
681
695
|
|
|
682
696
|
services:
|
|
683
697
|
${r.join(`
|
|
684
698
|
|
|
685
699
|
`)}
|
|
686
|
-
`;n.length>0&&(
|
|
700
|
+
`;n.length>0&&(s+=`
|
|
687
701
|
volumes:
|
|
688
702
|
${n.join(`
|
|
689
703
|
`)}
|
|
690
|
-
`),await l(
|
|
691
|
-
`)}import{readFile as
|
|
692
|
-
export const pool = db.$client;`,
|
|
704
|
+
`),await l(Ps(e.projectDir,"infra/docker-compose.yml"),s)}import{join as Rs}from"path";var gt="Next.js";function Is(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:gt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/electron",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Ts(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${gt} + Backend + Inngest)`,configurations:["Backend",gt,"Inngest"]}):t.push({name:`Dev (${gt} + Inngest)`,configurations:[gt,"Inngest"]}),t}async function xn(e){let t={version:"0.2.0",configurations:Is(e),compounds:Ts(e)};await l(Rs(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
705
|
+
`)}import{readFile as Nn}from"fs/promises";import{join as Cn}from"path";var wr='import { drizzle } from "drizzle-orm/node-postgres";',br=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
706
|
+
export const pool = db.$client;`,_s={postgres:{importLine:wr,instantiation:br},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
|
|
693
707
|
import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
|
|
694
708
|
export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
695
709
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
696
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
697
|
-
|
|
698
|
-
import { RedisStore } from "rate-limit-redis";
|
|
699
|
-
import type { RedisReply } from "rate-limit-redis";
|
|
700
|
-
import { env } from "./env";
|
|
701
|
-
|
|
702
|
-
/** Options for \`redis.cacheSet\`. */
|
|
703
|
-
export interface CacheSetOptions {
|
|
704
|
-
/** TTL in seconds (SET EX). Mutually exclusive with \`ttlMilliseconds\`. */
|
|
705
|
-
ttlSeconds?: number;
|
|
706
|
-
/** TTL in milliseconds (SET PX). Mutually exclusive with \`ttlSeconds\`. */
|
|
707
|
-
ttlMilliseconds?: number;
|
|
708
|
-
/** Only set if the key does not already exist (SET NX). */
|
|
709
|
-
ifNotExists?: boolean;
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
/**
|
|
713
|
-
* Small helpers extended onto the native \`redis\` client for the SDK
|
|
714
|
-
* methods whose signatures differ between ioredis and Upstash. Use these in
|
|
715
|
-
* your own code when you want a uniform API; everything else on \`redis\` is
|
|
716
|
-
* the native ioredis surface (or Upstash, on that backend) - use those
|
|
717
|
-
* directly with their native syntax.
|
|
718
|
-
*/
|
|
719
|
-
export interface BoilerplateRedisHelpers {
|
|
720
|
-
/** SET with optional TTL and NX in one call. Returns \`true\` if stored, \`false\` only when \`ifNotExists\` was set and the key already existed. */
|
|
721
|
-
cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean>;
|
|
722
|
-
/** GET typed as \`string | null\`. (On Upstash this also disables auto-deserialization for consistent string round-trip.) */
|
|
723
|
-
cacheGet(key: string): Promise<string | null>;
|
|
724
|
-
/** MGET over an array of keys, typed as \`(string | null)[]\` in the order given. The SDKs' native \`mget\` differ in both arity and return typing. */
|
|
725
|
-
cacheMGet(keys: string[]): Promise<(string | null)[]>;
|
|
726
|
-
/** Iterate keys matching a glob pattern via SCAN. Yields each key as it's discovered. */
|
|
727
|
-
cacheScan(opts: { match: string; count?: number }): AsyncIterable<string>;
|
|
728
|
-
/** Run a Lua script via EVAL with explicit key and argument lists (the SDKs' native \`eval\` signatures differ). Returns the script's raw reply. */
|
|
729
|
-
cacheEval(script: string, keys: string[], args: (string | number)[]): Promise<unknown>;
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
// \`lazyConnect\` keeps the client from dialing Redis the moment this module is
|
|
733
|
-
// imported. Without it, a build/prerender (or any process that merely imports
|
|
734
|
-
// @repo/runtime) eagerly opens a connection, and if Redis isn't reachable yet -
|
|
735
|
-
// e.g. a Docker/Dokploy build where the Redis host only resolves at runtime -
|
|
736
|
-
// ioredis retries the DNS lookup forever and the build hangs. With lazyConnect
|
|
737
|
-
// the connection opens on the first real command instead, at runtime.
|
|
738
|
-
let everConnected = false;
|
|
739
|
-
const ioredis = new Redis(env.REDIS_URL, {
|
|
740
|
-
lazyConnect: true,
|
|
741
|
-
// Reconnect forever once a connection has ever succeeded (runtime
|
|
742
|
-
// resilience across Redis restarts), but give up after 10 attempts when
|
|
743
|
-
// the FIRST connection cannot be established - e.g. a build/prerender
|
|
744
|
-
// where the Redis host only resolves at runtime. Without this, pending
|
|
745
|
-
// retries keep the event loop alive and the build never exits.
|
|
746
|
-
retryStrategy(times) {
|
|
747
|
-
if (!everConnected && times > 10) return null;
|
|
748
|
-
return Math.min(times * 200, 2000);
|
|
749
|
-
}
|
|
750
|
-
});
|
|
751
|
-
ioredis.on("connect", () => {
|
|
752
|
-
everConnected = true;
|
|
753
|
-
});
|
|
754
|
-
|
|
755
|
-
/**
|
|
756
|
-
* Native ioredis client + the boilerplate helpers. Every native
|
|
757
|
-
* ioredis method (\`zadd\`, \`hset\`, \`pubsub\`, etc.) is available
|
|
758
|
-
* directly on this object - see ioredis's docs for usage. The
|
|
759
|
-
* \`cache*\` helpers cover the SDK calls whose signatures differ between
|
|
760
|
-
* ioredis and Upstash.
|
|
761
|
-
*/
|
|
762
|
-
export const redis: Redis & BoilerplateRedisHelpers = Object.assign(ioredis, {
|
|
763
|
-
async cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean> {
|
|
764
|
-
const args: (string | number)[] = [key, value];
|
|
765
|
-
if (opts?.ttlSeconds !== undefined) args.push("EX", opts.ttlSeconds);
|
|
766
|
-
if (opts?.ttlMilliseconds !== undefined) args.push("PX", opts.ttlMilliseconds);
|
|
767
|
-
if (opts?.ifNotExists) args.push("NX");
|
|
768
|
-
const result = await ioredis.call("SET", ...args);
|
|
769
|
-
return result === "OK";
|
|
770
|
-
},
|
|
771
|
-
async cacheGet(key: string): Promise<string | null> {
|
|
772
|
-
return ioredis.get(key);
|
|
773
|
-
},
|
|
774
|
-
async cacheMGet(keys: string[]): Promise<(string | null)[]> {
|
|
775
|
-
if (keys.length === 0) return [];
|
|
776
|
-
return ioredis.mget(...keys);
|
|
777
|
-
},
|
|
778
|
-
async *cacheScan(opts: { match: string; count?: number }): AsyncIterable<string> {
|
|
779
|
-
let cursor = "0";
|
|
780
|
-
do {
|
|
781
|
-
const [next, keys] =
|
|
782
|
-
opts.count !== undefined
|
|
783
|
-
? await ioredis.scan(cursor, "MATCH", opts.match, "COUNT", opts.count)
|
|
784
|
-
: await ioredis.scan(cursor, "MATCH", opts.match);
|
|
785
|
-
for (const k of keys) yield k;
|
|
786
|
-
cursor = next;
|
|
787
|
-
} while (cursor !== "0");
|
|
788
|
-
},
|
|
789
|
-
async cacheEval(script: string, keys: string[], args: (string | number)[]): Promise<unknown> {
|
|
790
|
-
return ioredis.eval(script, keys.length, ...keys, ...args);
|
|
791
|
-
}
|
|
792
|
-
});
|
|
793
|
-
|
|
794
|
-
/**
|
|
795
|
-
* Build a \`hono-rate-limiter\`-compatible store backed by \`rate-limit-redis\`.
|
|
796
|
-
* Wraps RedisStore in an adapter exposing only the methods the middleware uses
|
|
797
|
-
* so we don't need an unsafe cross-package type cast.
|
|
798
|
-
*/
|
|
799
|
-
export function createLimiterStore(): Store {
|
|
800
|
-
const inner = new RedisStore({
|
|
801
|
-
sendCommand: (command: string, ...args: string[]) => {
|
|
802
|
-
const pending = ioredis.call(command, ...args) as Promise<RedisReply>;
|
|
803
|
-
// Mark it handled WITHOUT consuming it. A limiter command outlives the request that
|
|
804
|
-
// issued it: the request fail-opens and returns, and nobody is awaiting this promise any
|
|
805
|
-
// more when the cache blips and ioredis rejects the queued command with "Connection is
|
|
806
|
-
// closed". Node treats an unhandled rejection as fatal, so a cache hiccup could take the
|
|
807
|
-
// process down - and during a Docker build or prerender, where Redis is not reachable
|
|
808
|
-
// yet, the fire-and-forget SCRIPT LOAD aborts the build outright.
|
|
809
|
-
//
|
|
810
|
-
// Attaching a catch marks THIS promise handled; returning the same promise leaves the
|
|
811
|
-
// store free to await it and see the error, so nothing is swallowed from a caller that
|
|
812
|
-
// cares.
|
|
813
|
-
pending.catch(() => undefined);
|
|
814
|
-
return pending;
|
|
815
|
-
}
|
|
816
|
-
});
|
|
710
|
+
export const db = drizzle(client, { schema });`}};async function Ln(e){let t=Cn(e.projectDir,"packages/database/src/index.ts"),r=await Nn(t,"utf-8");if(!r.includes(wr)||!r.includes(br))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=_s[e.databaseProvider],i=r.replace(wr,n.importLine).replace(br,n.instantiation);await l(t,i),await xs(e)}var Dn='import { Client } from "pg";',kr=` const client = new Client({ connectionString });
|
|
711
|
+
await client.connect();
|
|
817
712
|
return {
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
},
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
resetKey: (key) => inner.resetKey(key)
|
|
826
|
-
};
|
|
827
|
-
}
|
|
828
|
-
|
|
829
|
-
let closed = false;
|
|
830
|
-
|
|
831
|
-
/** Gracefully close the Redis connection; idempotent. Falls back to disconnect() on error. */
|
|
832
|
-
export async function closeRedis() {
|
|
833
|
-
if (closed) return;
|
|
834
|
-
try {
|
|
835
|
-
await ioredis.quit();
|
|
836
|
-
} catch (error) {
|
|
837
|
-
ioredis.disconnect();
|
|
838
|
-
throw error;
|
|
839
|
-
} finally {
|
|
840
|
-
closed = true;
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
`)}async function ko(e){await l(Vt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
844
|
-
import { redis } from "./redis";
|
|
845
|
-
|
|
846
|
-
export class MutexTimeoutError extends Error {
|
|
847
|
-
constructor(key: string) {
|
|
848
|
-
super(\`Failed to acquire mutex for key: \${key}\`);
|
|
849
|
-
this.name = "MutexTimeoutError";
|
|
850
|
-
}
|
|
851
|
-
}
|
|
852
|
-
|
|
853
|
-
/** Delay between acquisition attempts. */
|
|
854
|
-
const RETRY_INTERVAL_MS = 500;
|
|
855
|
-
|
|
856
|
-
/**
|
|
857
|
-
* Execute \`fn\` while holding a distributed mutex on \`key\`. Backed by
|
|
858
|
-
* \`redis-semaphore\`, which uses Lua scripts for atomic compare-and-delete
|
|
859
|
-
* on release and refreshes the lock while \`fn\` runs.
|
|
860
|
-
*
|
|
861
|
-
* \`acquireTimeout\` is honoured; the attempt budget is derived from it so the two cannot disagree.
|
|
862
|
-
*
|
|
863
|
-
* \`onLockLost\` is supplied because the library's default is \`throw err\`, and it fires from the
|
|
864
|
-
* REFRESH TIMER rather than this call stack - so one failed refresh became an unhandled rejection
|
|
865
|
-
* and, by Node's default, killed the process in the middle of whatever the lock was guarding. The
|
|
866
|
-
* handler logs and lets the work finish: crashing is the defect, and failing a completed operation
|
|
867
|
-
* invites a retry of work that already happened.
|
|
868
|
-
*/
|
|
869
|
-
export async function withMutex<T>(
|
|
870
|
-
key: string,
|
|
871
|
-
fn: () => Promise<T>,
|
|
872
|
-
options?: { lockTimeout?: number; acquireTimeout?: number }
|
|
873
|
-
): Promise<T> {
|
|
874
|
-
const acquireTimeout = options?.acquireTimeout ?? 5_000;
|
|
875
|
-
const mutex = new Mutex(redis, key, {
|
|
876
|
-
lockTimeout: options?.lockTimeout ?? 10_000,
|
|
877
|
-
acquireTimeout,
|
|
878
|
-
acquireAttemptsLimit: Math.max(1, Math.ceil(acquireTimeout / RETRY_INTERVAL_MS)),
|
|
879
|
-
retryInterval: RETRY_INTERVAL_MS,
|
|
880
|
-
onLockLost: (error) => {
|
|
881
|
-
console.error(
|
|
882
|
-
\`[Mutex] Lock lost while the critical section was still running - mutual exclusion has lapsed (key: \${key})\`,
|
|
883
|
-
error
|
|
884
|
-
);
|
|
885
|
-
}
|
|
886
|
-
});
|
|
887
|
-
|
|
888
|
-
const acquired = await mutex.tryAcquire();
|
|
889
|
-
if (!acquired) {
|
|
890
|
-
throw new MutexTimeoutError(key);
|
|
891
|
-
}
|
|
892
|
-
|
|
893
|
-
try {
|
|
894
|
-
return await fn();
|
|
895
|
-
} finally {
|
|
896
|
-
// Releasing a lock that was already lost rejects. Letting that escape from \`finally\` would
|
|
897
|
-
// REPLACE whatever the critical section returned or threw.
|
|
898
|
-
await mutex.release().catch((error: unknown) => {
|
|
899
|
-
console.error(\`[Mutex] Failed to release lock (its TTL will expire it) (key: \${key})\`, error);
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
`)}async function Eo(e){await l(Vt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
713
|
+
query: async (text) => ({ rows: (await client.query<LiveColumnRow>(text)).rows }),
|
|
714
|
+
end: () => client.end()
|
|
715
|
+
};`,Os={postgres:null,neon:{importLine:'import { Client } from "@neondatabase/serverless";',open:kr},supabase:{importLine:'import postgres from "postgres";',open:` const sql = postgres(connectionString, { prepare: false });
|
|
716
|
+
return {
|
|
717
|
+
query: async (text) => ({ rows: await sql.unsafe(text) }),
|
|
718
|
+
end: () => sql.end()
|
|
719
|
+
};`}};async function xs(e){let t=Os[e.databaseProvider];if(!t)return;let r=Cn(e.projectDir,"packages/database/src/db-verify.ts"),n=await Nn(r,"utf-8");if(!n.includes(Dn)||!n.includes(kr))throw new Error("generateDbDriver: boilerplate packages/database/src/db-verify.ts is missing the node-postgres verifier anchors (the import line or the openVerifyClient body); the boilerplate drifted.");await l(r,n.replace(Dn,t.importLine).replace(kr,t.open))}import{join as $n}from"path";async function jn(e){e.cacheProvider==="upstash"&&(await Ds(e),await Ns(e))}async function Ds(e){await l($n(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
904
720
|
import type { Store } from "hono-rate-limiter";
|
|
905
721
|
import { env } from "./env";
|
|
906
722
|
|
|
@@ -946,6 +762,29 @@ const upstash = new Redis({
|
|
|
946
762
|
automaticDeserialization: false
|
|
947
763
|
});
|
|
948
764
|
|
|
765
|
+
/**
|
|
766
|
+
* \`REDIS_KEY_PREFIX\` is an IOREDIS-ONLY option, and this backend REFUSES it rather than ignoring it.
|
|
767
|
+
*
|
|
768
|
+
* ioredis applies \`keyPrefix\` inside the client, over the key positions every command publishes, so
|
|
769
|
+
* the namespace is complete by construction. The Upstash REST SDK has no equivalent, and the only way
|
|
770
|
+
* to add one from outside is a hand-maintained table of command -> key position. Such a table cannot
|
|
771
|
+
* be complete: the SDK's command surface is open, and its \`json.*\` commands are a nested OBJECT
|
|
772
|
+
* rather than methods, so no property trap even sees them. Every command the table missed would write
|
|
773
|
+
* an UNPREFIXED key while the deployment believed it was namespaced - two deployments quietly sharing
|
|
774
|
+
* sessions, rate-limit counters and MUTEX keys, with every test green. A wrong key POSITION is worse
|
|
775
|
+
* still: prefixing a set member or a hash field corrupts the value instead of moving the key.
|
|
776
|
+
*
|
|
777
|
+
* A deployment that refuses to boot is recoverable; a keyspace that is silently half-namespaced is
|
|
778
|
+
* not, and the distributed mutex behind every credit and plan mutation sits inside it. Give each
|
|
779
|
+
* deployment its own Upstash database, or choose the ioredis cache backend, where the SDK does this
|
|
780
|
+
* itself.
|
|
781
|
+
*/
|
|
782
|
+
if (env.REDIS_KEY_PREFIX) {
|
|
783
|
+
throw new Error(
|
|
784
|
+
"REDIS_KEY_PREFIX is not supported on the Upstash cache backend: the Upstash REST SDK has no key-prefix option, so a prefix applied from outside would silently miss any command it did not know about and split the keyspace. Give each deployment its own Upstash database, or use the ioredis cache backend."
|
|
785
|
+
);
|
|
786
|
+
}
|
|
787
|
+
|
|
949
788
|
/**
|
|
950
789
|
* Native Upstash REST client + the boilerplate helpers. Every native
|
|
951
790
|
* Upstash method (\`zadd\`, \`hset\`, \`json.*\`, etc.) is available
|
|
@@ -1047,7 +886,7 @@ export function createLimiterStore(): Store {
|
|
|
1047
886
|
|
|
1048
887
|
/** No persistent connection to close with Upstash REST. */
|
|
1049
888
|
export async function closeRedis(): Promise<void> {}
|
|
1050
|
-
`)}async function
|
|
889
|
+
`)}async function Ns(e){await l($n(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
1051
890
|
import { redis } from "./redis";
|
|
1052
891
|
|
|
1053
892
|
export class MutexTimeoutError extends Error {
|
|
@@ -1125,10 +964,10 @@ export async function withMutex<T>(
|
|
|
1125
964
|
});
|
|
1126
965
|
}
|
|
1127
966
|
}
|
|
1128
|
-
`)}import{readFile as
|
|
1129
|
-
UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function
|
|
1130
|
-
`)}function
|
|
1131
|
-
`))}}import{readFile as
|
|
967
|
+
`)}import{readFile as Cs}from"fs/promises";import{join as Ls}from"path";var Un=" REDIS_URL: z.string(),",$s=` UPSTASH_REDIS_REST_URL: z.string(),
|
|
968
|
+
UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Mn(e){let t=Ls(e.projectDir,"packages/runtime/src/env.ts"),r=await Cs(t,"utf-8");if(!r.includes(Un))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Un,$s):r;await l(t,n)}import{readFile as Fn}from"fs/promises";import{join as X}from"path";var Kt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Qe(e){let t=await Fn(e,"utf-8");return JSON.parse(t)}async function et(e,t){let r=/\n([\t ]+)"/.exec(await Fn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
|
|
969
|
+
`)}function Ne(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function yt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Vn(e){await js(e),await Us(e),await Ms(e),await Bs(e),await Ks(e),await Ws(e)}async function js(e){let t=X(e.projectDir,"packages/api/package.json"),r=await Qe(t);Ne(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ne(r,["ioredis"]),await et(t,r)}async function Us(e){let t=X(e.projectDir,"apps/web/package.json"),r=await Qe(t);Ne(r,["@upstash/ratelimit","@upstash/redis"]),await et(t,r)}async function Ms(e){let t=X(e.projectDir,"packages/runtime/package.json"),r=await Qe(t);e.cacheProvider==="upstash"&&(Ne(r,["ioredis","rate-limit-redis","redis-semaphore"]),yt(r,"@upstash/redis",Kt["@upstash/redis"]),yt(r,"@upstash/lock",Kt["@upstash/lock"])),await et(t,r)}var Er={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Fs=["@sentry/electron"],Vs=[...Er.sentry,...Er.posthog];async function Bs(e){let t=X(e.projectDir,"packages/observability/package.json"),r=await Qe(t),n=new Set(e.observability.flatMap(i=>Er[i]));if(!e.desktop)for(let i of Fs)n.delete(i);Ne(r,Vs.filter(i=>!n.has(i))),await et(t,r)}async function Ks(e){let t=X(e.projectDir,"packages/database/package.json"),r=await Qe(t);e.databaseProvider==="neon"?(Ne(r,["pg","@types/pg"]),yt(r,"@neondatabase/serverless",Kt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ne(r,["pg","@types/pg"]),yt(r,"postgres",Kt.postgres)),await et(t,r)}var Gs=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Hs(e){let t=await Qe(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],yt(t,"@repo/api",r,!0),await et(e,t))}var Ys=["instrumentation.ts","tests/instrumentation.test.ts"];async function Ws(e){if(e.architecture!=="separate")return;let t=X(e.projectDir,"apps/web");await Mt(X(t,"app/api/[[...rest]]/route.ts"),t);for(let r of Gs)await Mt(X(t,r),t);for(let r of Ys)await Mt(X(t,r),t);await Hs(X(t,"package.json"))}import{readFile as zs}from"fs/promises";import{join as qs}from"path";var Js=["base.json","node.json","next.json"],Bn="GenerateSaaS ";async function Kn(e){if(!e.demo)for(let t of Js){let r=qs(e.projectDir,"tooling/typescript",t),n;try{n=await zs(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Bn)||(i.display=i.display.slice(Bn.length),await l(r,JSON.stringify(i,null," ")+`
|
|
970
|
+
`))}}import{readFile as Hn,rm as Xs}from"fs/promises";import{join as vt}from"path";async function Yn(e){e.cacheProvider==="upstash"&&(await Promise.all([Gn(vt(e.projectDir,"packages/runtime/tests/setup.ts")),Gn(vt(e.projectDir,"packages/mail/tests/setup.ts")),Qs(e.projectDir),Xs(vt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Zs(e.projectDir))}async function Zs(e){await l(vt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
1132
971
|
|
|
1133
972
|
/**
|
|
1134
973
|
* Regression guards for the Upstash-backed cache layer in src/redis.ts.
|
|
@@ -1250,9 +1089,9 @@ describe("cacheScan", () => {
|
|
|
1250
1089
|
expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
|
|
1251
1090
|
});
|
|
1252
1091
|
});
|
|
1253
|
-
`)}async function
|
|
1092
|
+
`)}async function Gn(e){let t;try{t=await Hn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1254
1093
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1255
|
-
`);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function
|
|
1094
|
+
`);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function Qs(e){let t=vt(e,"packages/api/tests/setup.ts"),r;try{r=await Hn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1256
1095
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1257
1096
|
`),n=n.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1258
1097
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1281,20 +1120,52 @@ vi.mock("@upstash/lock", () => {
|
|
|
1281
1120
|
return { Lock };
|
|
1282
1121
|
});
|
|
1283
1122
|
|
|
1284
|
-
$1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
`)}async function
|
|
1288
|
-
`)
|
|
1289
|
-
|
|
1290
|
-
|
|
1123
|
+
$1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let s of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(s))throw new Error(`pruneCacheTests: ${t} still contains ${s} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as ea}from"fs/promises";var ta=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,ra=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Wn=32;function na(e){let t=e.lastIndexOf(".");return t>=0&&ra.has(e.slice(t))}async function ia(e){let t=await ea(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(ta,"");r!==t&&await l(e,r)}async function zn(e){let t=await de(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),na);for(let r=0;r<t.length;r+=Wn)await Promise.all(t.slice(r,r+Wn).map(ia))}import{readdir as Qn,readFile as Le,rm as Z}from"fs/promises";import{join as S}from"path";import{readFile as bt,rm as oa}from"fs/promises";import{join as wt}from"path";function sa(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function be(e,t,r,n){let i=sa(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let s=e.replace(i,"");if(s.includes(`gsaas:${r}-start`)||s.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return s.replace(/\n{3,}/g,`
|
|
1124
|
+
|
|
1125
|
+
`).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function K(e,t,r,n,i){let s=await bt(e,"utf-8"),o=s.indexOf(t);if(o===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(s.indexOf(t,o+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,s.slice(0,o)+r+s.slice(o+t.length))}async function Ce(e,t,r,n){let i=/\n([\t ]+)"/.exec(await bt(e,"utf-8"))?.[1];if(i!==r){let s=o=>o===" "?"tab":`${o.length}-space`;throw new Error(`${n}: expected ${e} to be ${s(r)}-indented, but it is ${i===void 0?"not indented":s(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
|
|
1126
|
+
`)}async function aa(e,t,r){let n=wt(e,"ai.mdx"),s=(await bt(n,"utf-8")).split(`
|
|
1127
|
+
`).find(o=>o.includes(`href="${t}"`));if(s===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await K(n,`${s}
|
|
1128
|
+
`,"",`ai.mdx ${t} card`,r)}async function ca(e,t,r){let n=wt(e,"ai.mdx"),i=`| **${t}** |`,o=(await bt(n,"utf-8")).split(`
|
|
1129
|
+
`).find(a=>a.startsWith(i));if(o===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await K(n,`${o}
|
|
1130
|
+
`,"",`ai.mdx ${t} hub-table row`,r)}async function qn(e,t,r,n,i){let s=wt(e,"docs/(platform)");await oa(wt(s,t),{recursive:!0}),await K(wt(s,"meta.json"),` "${t}",
|
|
1131
|
+
`,"",`docs meta.json ${t} nav entry`,n);for(let o of r)await aa(s,o,n);i!==void 0&&await ca(s,i,n)}function la(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
|
|
1132
|
+
`;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
|
|
1133
|
+
`&&(t+=`
|
|
1134
|
+
`),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let s=n;for(r++;r<e.length&&e[r]!==s;)e[r]==="\\"?r++:e[r]===`
|
|
1135
|
+
`&&(t+=`
|
|
1136
|
+
`),r++;r++;continue}t+=n,r++}return t}async function Jn(e){let t=`import { config } from "@repo/config";
|
|
1137
|
+
`,r=await bt(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=la(n);/\bconfig\b/.test(i)||await l(e,n)}import{readFile as Zn,rm as A}from"fs/promises";import{join as E}from"path";import{readFile as kt}from"fs/promises";import{join as Et}from"path";async function Xn(e,t){let r=Et(e,"packages/api/src/routes/internal/index.ts");await l(r,be(await kt(r,"utf-8"),"internal router","runner",t)),await Jn(r);let n=Et(e,"packages/api/src/ai/automation-runner.ts");await l(n,be(await kt(n,"utf-8"),"automation-runner.ts","runner",t));for(let o of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/automations-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/automations.test.ts","packages/api/tests/ai/automations-runs-route.test.ts","packages/api/tests/routes/ai.test.ts","packages/api/tests/ai/summarize-cap.test.ts"]){let a=Et(e,o);await l(a,be(await kt(a,"utf-8"),o,"runner",t))}let i=Et(e,"packages/api/src/ai/settings-store.ts");await l(i,be(await kt(i,"utf-8"),"settings-store.ts","runner",t));let s=Et(e,"packages/api/tests/ai/settings-store.test.ts");await l(s,be(await kt(s,"utf-8"),"settings-store.test.ts","runner",t))}async function Sr(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await A(E(t,"packages/api/src/relay"),{recursive:!0}),await A(E(t,"packages/api/src/runner"),{recursive:!0}),await A(E(t,"packages/api/src/ai/runner-model.ts")),await A(E(t,"packages/api/src/ai/runner-routing.ts")),await A(E(t,"packages/api/tests/relay"),{recursive:!0}),await A(E(t,"packages/api/tests/runner"),{recursive:!0}),await A(E(t,"packages/api/src/routes/internal/runner.ts")),await A(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await A(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await A(E(t,"packages/api/tests/routes/runner.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await A(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await A(E(t,"packages/api/tests/ai/automation-coalesce.test.ts")),await A(E(t,"packages/api/tests/ai/automations-lazy-expiry.test.ts")),await A(E(t,"packages/api/tests/ai/runner-model.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-routing.test.ts")),await A(E(t,"packages/api/tests/unit/runner-unavailable-interactive.test.ts")),await A(E(t,"packages/api/tests/unit/runner-arm-harness.ts")),await A(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await A(E(t,"packages/api/tests/helpers/runner-protocol.ts")),await A(E(t,"packages/api/tests/helpers/runner-frames.ts")),await A(E(t,"packages/api/tests/helpers/relay-runtime-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Zn(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Ce(n,i," ",r),await Xn(t,r),await qn(t,"runner",["/runner"],r,"Runners"),await K(E(t,"docs/(platform)/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await K(E(t,"docs/(platform)/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let s=E(t,"docs/(platform)/configuration.mdx"),o="| `runner.enabled` |",a=(await Zn(s,"utf-8")).split(`
|
|
1138
|
+
`).find(p=>p.startsWith(o));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await K(s,`${a}
|
|
1139
|
+
`,"","configuration.mdx runner config-table row",r)}var pa=new Set(["ci.yml","desktop-release.yml"]),da=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],ua=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function ei(e){let t=S(e.projectDir,".github/workflows"),r=await Qn(t).catch(()=>[]);for(let n of r)pa.has(n)||await Z(S(t,n),{recursive:!0,force:!0})}async function ma(e,t){let r=S(e,"package.json"),n=JSON.parse(await Le(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let o of t)o in n.scripts&&(delete n.scripts[o],i=!0);if(!i)return;let s=/\n([\t ]+)"/.exec(await Le(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,s)+`
|
|
1140
|
+
`)}async function ti(e){await ma(e.projectDir,[...ua])}async function ri(e){let t=S(e.projectDir,"package.json"),r=await Le(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(n,null," ")+`
|
|
1141
|
+
`))}async function ni(e){let t=S(e.projectDir,"package.json"),r=JSON.parse(await Le(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test --concurrency=4 && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test --concurrency=4 && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test --concurrency=4",await l(t,JSON.stringify(r,null," ")+`
|
|
1142
|
+
`)}async function ii(e){e.docs||await Z(S(e.projectDir,"apps/docs"),{recursive:!0})}async function oi(e){let t=S(e.projectDir,"docs/(platform)/meta.json"),r=JSON.parse(await Le(t,"utf-8"));if(r.title!=="GenerateSaaS")throw new Error(`stripUnusedDocsSilo: expected the feature-page group to be titled "GenerateSaaS", found ${JSON.stringify(r.title)} (boilerplate drift).`);r.title=e.appName,await Ce(t,r," ","stripUnusedDocsSilo"),e.desktop||await Z(S(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await fa(e)}async function ue(e,t,r,n){await l(e,be(await Le(e,"utf-8"),t,r,n))}async function fa(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=S(t,"docs/(platform)/configuration.mdx"),i=e.desktop,s=e.desktop&&e.ai;e.desktop||(await K(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await ue(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await K(S(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await ue(S(t,"docs/(platform)/payments/organizations.mdx"),"payments organizations.mdx desktop tenancy callout","desktop-tenancy-docs",r),await ue(S(t,"docs/(platform)/projects.mdx"),"projects.mdx desktop scoping callout","desktop-projects-docs",r),await ue(S(t,"docs/(platform)/client-architecture.mdx"),"client-architecture.mdx desktop card","desktop-architecture-docs",r),await ue(S(t,"docs/(platform)/testing/e2e.mdx"),"testing/e2e.mdx desktop e2e callout","desktop-testing-docs",r),await K(S(t,"docs/(platform)/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
|
|
1143
|
+
`,"","index.mdx desktop app card",r),await ue(S(t,"docs/(platform)/ai.mdx"),"ai.mdx automation lanes row + section","desktop-lanes-docs",r)),i||(await ue(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),await K(S(t,"docs/(platform)/navigation.mdx"),"gates the desktop app's Chat and Automations, see [desktop AI](/desktop/ai) |","gates the desktop app's Chat and Automations |","navigation.mdx sidebar-flag agents-row link",r)),!s&&e.runner&&(await ue(S(t,"docs/(platform)/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await ue(S(t,"docs/(platform)/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function si(e){if(e.desktop)return;await Z(S(e.projectDir,"apps/electron"),{recursive:!0});let t=S(e.projectDir,"packages/i18n/translations");for(let i of await Qn(t,{withFileTypes:!0}))i.isDirectory()&&await Z(S(t,i.name,"desktop.json"),{force:!0});await Z(S(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of da)await Z(S(e.projectDir,i),{recursive:!0});await Z(S(e.projectDir,"packages/utils/src/desktop-download.ts")),await Z(S(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=S(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await Le(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ce(r,n," ","stripDesktopApp")}function ha(e){return e.desktop}async function ai(e){ha(e)||await Z(S(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ga}from"fs/promises";import{join as ya}from"path";var ci=`on:
|
|
1291
1144
|
workflow_run:
|
|
1292
1145
|
workflows: ["Tag Release"]
|
|
1293
1146
|
branches: [main]
|
|
1294
1147
|
types: [completed]
|
|
1295
|
-
workflow_dispatch:`,
|
|
1296
|
-
workflow_dispatch:`;async function
|
|
1297
|
-
|
|
1148
|
+
workflow_dispatch:`,va=`on:
|
|
1149
|
+
workflow_dispatch:`;async function li(e){if(!e.desktop)return;let t=ya(e.projectDir,".github/workflows/desktop-release.yml"),r=await ga(t,"utf8");if(!r.includes(ci))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(ci,va))}import{join as wa}from"path";async function ui(e){let t=ba(e);await l(wa(e.projectDir,".github/workflows/ci.yml"),t)}function pi(e){return e.databaseProvider!=="neon"&&e.cacheProvider!=="upstash"}function di(e,t,r){return` - uses: actions/upload-artifact@v4
|
|
1150
|
+
if: \${{ ${r} }}
|
|
1151
|
+
with:
|
|
1152
|
+
name: playwright-report-${e}
|
|
1153
|
+
path: |
|
|
1154
|
+
${t}/playwright-report
|
|
1155
|
+
${t}/test-results
|
|
1156
|
+
if-no-files-found: ignore
|
|
1157
|
+
retention-days: 7
|
|
1158
|
+
`}function ba(e){let t=e.cacheProvider==="upstash",r=t?"":` redis:
|
|
1159
|
+
image: redis:8-alpine
|
|
1160
|
+
ports:
|
|
1161
|
+
- 6379:6379
|
|
1162
|
+
options: >-
|
|
1163
|
+
--health-cmd "redis-cli ping"
|
|
1164
|
+
--health-interval 10s
|
|
1165
|
+
--health-timeout 5s
|
|
1166
|
+
--health-retries 5
|
|
1167
|
+
`,n=r===""?"":` services:
|
|
1168
|
+
${r}`,o=` postgres:
|
|
1298
1169
|
image: postgres:18-alpine
|
|
1299
1170
|
env:
|
|
1300
1171
|
POSTGRES_USER: postgres
|
|
@@ -1307,23 +1178,105 @@ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`prun
|
|
|
1307
1178
|
--health-interval 10s
|
|
1308
1179
|
--health-timeout 5s
|
|
1309
1180
|
--health-retries 5
|
|
1310
|
-
${
|
|
1311
|
-
image:
|
|
1181
|
+
${r} mailpit:
|
|
1182
|
+
image: axllent/mailpit
|
|
1312
1183
|
ports:
|
|
1313
|
-
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1184
|
+
- 1025:1025
|
|
1185
|
+
- 8025:8025
|
|
1186
|
+
env:
|
|
1187
|
+
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
|
1188
|
+
MP_SMTP_AUTH_ALLOW_INSECURE: 1
|
|
1189
|
+
`,a=` # MinIO and Inngest are containers rather than \`services:\` entries: a service container takes
|
|
1190
|
+
# no command override, and both images need one. Preflight creates the buckets and their public
|
|
1191
|
+
# read policy, so the compose file's one-shot bucket init has no counterpart here.
|
|
1192
|
+
- name: Start MinIO
|
|
1193
|
+
run: |
|
|
1194
|
+
docker run -d --name minio --network host \\
|
|
1195
|
+
-e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \\
|
|
1196
|
+
minio/minio:RELEASE.2025-09-07T16-13-09Z server /data
|
|
1197
|
+
|
|
1198
|
+
# No \`-u\`: the harness registers the app by PUTting its own /api/inngest endpoint, and the
|
|
1199
|
+
# suite's port is derived per checkout - a baked URL would name a port nothing serves.
|
|
1200
|
+
- name: Start Inngest
|
|
1201
|
+
run: docker run -d --name inngest --network host inngest/inngest:v1.17.4 inngest dev
|
|
1202
|
+
`,p=pi(e)?`
|
|
1203
|
+
# The end-to-end suite, on every push and PR. It needs no keys and no internet: the harness
|
|
1204
|
+
# preflights the services below, builds and starts the app itself, provisions a throwaway database,
|
|
1205
|
+
# and answers every vendor from a local fake. Any other outbound host fails the spec by name.
|
|
1206
|
+
e2e:
|
|
1207
|
+
name: E2E
|
|
1208
|
+
runs-on: ubuntu-latest
|
|
1209
|
+
timeout-minutes: 30
|
|
1210
|
+
services:
|
|
1211
|
+
${o} steps:
|
|
1212
|
+
- uses: actions/checkout@v6
|
|
1213
|
+
- uses: ./.github/actions/setup
|
|
1214
|
+
|
|
1215
|
+
- name: Cache Playwright browsers
|
|
1216
|
+
uses: actions/cache@v4
|
|
1217
|
+
with:
|
|
1218
|
+
path: ~/.cache/ms-playwright
|
|
1219
|
+
key: playwright-\${{ runner.os }}-\${{ hashFiles('pnpm-lock.yaml') }}
|
|
1220
|
+
|
|
1221
|
+
# The suite installs nothing itself. Preflight names this exact command when the browser is
|
|
1222
|
+
# missing, so a cold runner fails in seconds rather than part-way through a build.
|
|
1223
|
+
- name: Install Chromium
|
|
1224
|
+
run: pnpm --filter web exec playwright install --with-deps chromium
|
|
1225
|
+
|
|
1226
|
+
${a}
|
|
1227
|
+
# A Next production build does not fit the runner's default heap: it compiles, then dies in the
|
|
1228
|
+
# TypeScript pass with "Ineffective mark-compacts near heap limit", which reads as the suite
|
|
1229
|
+
# being broken rather than the runner running out of room. A ceiling is not a reservation.
|
|
1230
|
+
- run: pnpm --filter web e2e:ci
|
|
1231
|
+
env:
|
|
1232
|
+
NODE_OPTIONS: --max-old-space-size=6144
|
|
1233
|
+
|
|
1234
|
+
${di("web","apps/web","!cancelled()")}`:"\n # No end-to-end job: this project's stack cannot run one in CI without credentials.\n # - a `neon` database talks over a serverless websocket that only reaches a managed endpoint,\n # so a Postgres service container is unreachable from the app;\n # - an `upstash` cache is a hosted REST endpoint, and this file carries no secrets.\n # The suite itself works locally: `pnpm infra` for a project on self-hosted Postgres and Redis,\n # then `pnpm e2e:ci`. To run it here, add a job with those services plus your own credentials as\n # repository secrets, or point a second CI environment at a disposable managed instance.\n",u=e.desktop&&pi(e),w=u?`
|
|
1235
|
+
# The DESKTOP end-to-end suite, on a manual "Run workflow" dispatch only: it builds the Electron
|
|
1236
|
+
# bundles AND a Next production build, which is too slow to pay for on every push. It has its own
|
|
1237
|
+
# port and its own build directory, so it can never collide with the web job above.
|
|
1238
|
+
desktop-e2e:
|
|
1239
|
+
name: Desktop E2E
|
|
1240
|
+
if: \${{ github.event_name == 'workflow_dispatch' }}
|
|
1241
|
+
runs-on: ubuntu-latest
|
|
1242
|
+
timeout-minutes: 45
|
|
1243
|
+
services:
|
|
1244
|
+
${o} steps:
|
|
1245
|
+
- uses: actions/checkout@v6
|
|
1246
|
+
- uses: ./.github/actions/setup
|
|
1247
|
+
|
|
1248
|
+
# An apt install, deliberately NOT \`playwright install\`: the suite launches the app's OWN
|
|
1249
|
+
# Electron binary, so a downloaded Chromium would sit unused while the libraries that binary
|
|
1250
|
+
# links against stayed missing. Ubuntu 24.04's 64-bit-time_t transition renamed several of
|
|
1251
|
+
# these with a \`t64\` suffix; on an older release, drop the suffix.
|
|
1252
|
+
- name: Install Electron system libraries
|
|
1253
|
+
run: |
|
|
1254
|
+
sudo apt-get update
|
|
1255
|
+
sudo apt-get install -y --no-install-recommends xvfb libgtk-3-0t64 libnss3 \\
|
|
1256
|
+
libasound2t64 libgbm1 libatk1.0-0t64 libatk-bridge2.0-0t64 libatspi2.0-0t64 \\
|
|
1257
|
+
libcups2t64 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 \\
|
|
1258
|
+
libxrandr2 libxtst6 libnotify4 libsecret-1-0 libpango-1.0-0 libcairo2
|
|
1259
|
+
|
|
1260
|
+
${a}
|
|
1261
|
+
# \`--auto-servernum\` picks a free display rather than assuming :99 is unused. The command
|
|
1262
|
+
# itself is the one you run locally, unchanged.
|
|
1263
|
+
- name: Desktop E2E under Xvfb
|
|
1264
|
+
run: xvfb-run --auto-servernum pnpm --filter desktop e2e:desktop:ci
|
|
1265
|
+
env:
|
|
1266
|
+
NODE_OPTIONS: --max-old-space-size=6144
|
|
1267
|
+
|
|
1268
|
+
${di("desktop","apps/electron","failure()")}`:"",g=u?"\n # Manual trigger for the opt-in desktop E2E job (see its `if:` below).\n workflow_dispatch:":"",k=e.databaseProvider==="neon"?`
|
|
1269
|
+
# Required for neon: the api suite's embedded Postgres is TCP-only and the neon
|
|
1270
|
+
# websocket driver cannot reach it. Add this repository secret (any Postgres this
|
|
1271
|
+
# suite may CREATE DATABASE on - a Neon branch works).
|
|
1272
|
+
GENERATESAAS_TEST_DATABASE_ADMIN_URL: \${{ secrets.GENERATESAAS_TEST_DATABASE_ADMIN_URL }}`:"",P=t?`
|
|
1320
1273
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1321
1274
|
UPSTASH_REDIS_REST_TOKEN: test-token`:`
|
|
1322
|
-
REDIS_URL: redis://localhost:6379`,
|
|
1275
|
+
REDIS_URL: redis://localhost:6379`,f=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1323
1276
|
STRIPE_SECRET_KEY: test
|
|
1324
1277
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1325
1278
|
POLAR_ACCESS_TOKEN: test
|
|
1326
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1279
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let U=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(U)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1327
1280
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1328
1281
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1329
1282
|
|
|
@@ -1333,7 +1286,7 @@ on:
|
|
|
1333
1286
|
push:
|
|
1334
1287
|
branches: [main]
|
|
1335
1288
|
pull_request:
|
|
1336
|
-
branches: [main]
|
|
1289
|
+
branches: [main]${g}
|
|
1337
1290
|
|
|
1338
1291
|
concurrency:
|
|
1339
1292
|
group: ci-\${{ github.ref }}
|
|
@@ -1347,8 +1300,8 @@ jobs:
|
|
|
1347
1300
|
name: Checks
|
|
1348
1301
|
runs-on: ubuntu-latest
|
|
1349
1302
|
timeout-minutes: 20
|
|
1350
|
-
${
|
|
1351
|
-
CONTENT_API_KEY: test-contentapi-key-16chars${
|
|
1303
|
+
${n} env:
|
|
1304
|
+
CONTENT_API_KEY: test-contentapi-key-16chars${k}${P}${f}
|
|
1352
1305
|
STORAGE_REGION: test
|
|
1353
1306
|
STORAGE_ENDPOINT: http://test
|
|
1354
1307
|
STORAGE_ACCESS_KEY_ID: test
|
|
@@ -1363,25 +1316,22 @@ ${i} env:
|
|
|
1363
1316
|
|
|
1364
1317
|
- run: pnpm check-types
|
|
1365
1318
|
|
|
1366
|
-
- name: Write root env
|
|
1367
|
-
run: echo "DATABASE_URL=${o}" > .env
|
|
1368
|
-
|
|
1369
1319
|
- run: pnpm test
|
|
1370
|
-
`}import{readFile as
|
|
1371
|
-
`))}async function
|
|
1372
|
-
`))}async function
|
|
1373
|
-
// ${
|
|
1320
|
+
${p}${w}`}import{readFile as mi}from"fs/promises";import{existsSync as ka}from"fs";import{join as Ar}from"path";var fi="@repo/database";function Ea(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy":"pnpm -F @repo/database run deploy"}function Sa(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function Aa(e,t,r){let n=await mi(e,"utf-8"),i=JSON.parse(n),s=i.scripts?.[t];if(!s)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);s.includes(fi)||(i.scripts={...i.scripts,[t]:`${r} && ${s}`},await l(e,JSON.stringify(i,null," ")+`
|
|
1321
|
+
`))}async function Pa(e,t){let r=ka(e)?JSON.parse(await mi(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(fi)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
|
|
1322
|
+
`))}async function hi(e){let t=Ea(e.demo===!0),r=Sa(e.architecture),n=Ar(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await Aa(Ar(n,"package.json"),"start",t);return;case"vercel":await Pa(Ar(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as Ra}from"fs/promises";import{existsSync as Ia}from"fs";import{join as Gt}from"path";var gi=["stripe","polar"],Ta=[...gi,"none"];async function yi(e){let t=Gt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
|
|
1323
|
+
// ${Ta.filter(s=>s!==r).map(s=>`"./${s}/index"`).join(" or ")} (other folders are kept in place).
|
|
1374
1324
|
export { ops } from "./${r}/index";
|
|
1375
|
-
`;await l(Gt(t,"providers/index.ts"),i),await l(Gt(t,"index.ts"),await
|
|
1376
|
-
`).filter(
|
|
1377
|
-
`)}import{access as
|
|
1325
|
+
`;await l(Gt(t,"providers/index.ts"),i),await l(Gt(t,"index.ts"),await _a(t,r))}async function _a(e,t){let r=Gt(e,"index.ts");if(!Ia(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await Ra(r,"utf-8"),i=gi.filter(o=>o!==t);return n.split(`
|
|
1326
|
+
`).filter(o=>!i.some(a=>o.includes(`./providers/${a}/`))).join(`
|
|
1327
|
+
`)}import{access as Oa,readFile as Wt,rm as Ht}from"fs/promises";import{join as W}from"path";var Ei=["sentry","posthog"],Pr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Yt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},xa=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Da=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Na=["./desktop-main","./desktop-renderer"],Ca=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
|
|
1378
1328
|
`,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
|
|
1379
|
-
`],
|
|
1329
|
+
`],La=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],vi=`
|
|
1380
1330
|
});
|
|
1381
|
-
|
|
1382
|
-
`).find(a=>a.trim().length>0&&!a.startsWith(`${
|
|
1383
|
-
`&&(
|
|
1384
|
-
`)[0]}`);n=n.replace(i.find,i.replace)}return n}function
|
|
1331
|
+
`,$a=" ";async function Si(e){let t=W(e.projectDir,"packages/observability");await wi(t,"packages/observability");let r=e.observability,n=r.filter(o=>!V.includes(o));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${V.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let o of r)await wi(W(t,Pr[o]),`packages/observability/${Pr[o]}`);let i=e.desktop?[...ki,...bc]:ki,s=new Map;for(let o of i)s.set(o.file,await Wt(W(t,o.file),"utf-8"));for(let o of Ya(r,e.desktop))await Wa(t,o);for(let o of Ei)if(!r.includes(o)){await Ht(W(t,Pr[o]),{recursive:!0,force:!0});for(let a of Yt[o])await Ht(W(t,a),{force:!0})}for(let o of xa)await Ht(W(t,o),{force:!0});e.desktop||await ja(t,r);for(let o of i){let a=s.get(o.file);a!==void 0&&await l(W(t,o.file),Fa(a,o,r))}}async function wi(e,t){try{await Oa(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function ja(e,t){for(let i of Da)await Ht(W(e,i),{force:!0});t.includes("sentry")&&await Ua(e);let r=W(e,"package.json"),n=JSON.parse(await Wt(r,"utf-8"));for(let i of Na){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ce(r,n," ","generateObservabilityProvider")}async function Ua(e){let t=W(e,Yt.sentry[0]),r=await Wt(t,"utf-8");r=Rr(r,Ca.map(n=>({find:n,replace:""})),Yt.sentry[0]);for(let n of La)r=Ma(r,n,Yt.sentry[0]);await l(t,r)}function Ma(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(vi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let s=e.slice(n+t.length,i).split(`
|
|
1332
|
+
`).find(a=>a.trim().length>0&&!a.startsWith(`${$a} `));if(s!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${s.trim()}`);let o=i+vi.length;return e[o]===`
|
|
1333
|
+
`&&(o+=1),e.slice(0,n)+e.slice(o)}function Fa(e,t,r){let n=Ei.filter(o=>!r.includes(o)),i=e,s=[];for(let o of n){let a=Va(i,o);i=a.source,s.push(...a.bindings)}t.dualMode!==!1&&(i=Rr(i,[{find:Ka,replace:Ga(r)}],t.file)),i=Rr(i,t.edits(r),t.file);for(let o of n)if(i.includes(`./providers/${o}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${o} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let o of s)if(new RegExp(String.raw`\b${o}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${o}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Rr(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
|
|
1334
|
+
`)[0]}`);n=n.replace(i.find,i.replace)}return n}function Va(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,s=>(n.push(...Ba(s)),"")),bindings:n}}function Ba(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(o=>o.trim().replace(/^type\s+/,"")).map(o=>o.split(/\s+as\s+/).at(-1)??"").filter(o=>o.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),s=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return s?.[1]?r.push(s[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var Ka=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Ga(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
|
|
1385
1335
|
* SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports to ${t}. No other provider's adapter or SDK was generated, so
|
|
1386
1336
|
* there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
|
|
1387
1337
|
*
|
|
@@ -1389,123 +1339,123 @@ export { ops } from "./${r}/index";
|
|
|
1389
1339
|
* run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
|
|
1390
1340
|
* update stages nothing while you are already on the latest version, so the switch lands with the
|
|
1391
1341
|
* next release. Pasting the other provider's credential into \`config.observability\` on its own
|
|
1392
|
-
* cannot: the adapter it would need is not here.`}var
|
|
1393
|
-
`,i=r.indexOf(n),
|
|
1342
|
+
* cannot: the adapter it would need is not here.`}var bi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Ha={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ya(e,t){return e.includes("sentry")?[]:t?[bi,Ha]:[bi]}async function Wa(e,t){let r=await Wt(W(e,t.source),"utf-8"),n=`export interface ${t.name} {
|
|
1343
|
+
`,i=r.indexOf(n),s=r.indexOf(`
|
|
1394
1344
|
}
|
|
1395
|
-
`,i);if(i===-1||
|
|
1396
|
-
`).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(
|
|
1397
|
-
|
|
1345
|
+
`,i);if(i===-1||s===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let o=r.slice(i+n.length,s).split(`
|
|
1346
|
+
`).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(o.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${o.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var za=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",qa=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
|
|
1347
|
+
`,Ja=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
|
|
1398
1348
|
ops.push(posthogServerOps);
|
|
1399
1349
|
}
|
|
1400
|
-
`,
|
|
1350
|
+
`,Xa=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
|
|
1401
1351
|
await initSentryServer();
|
|
1402
1352
|
}
|
|
1403
|
-
`,
|
|
1404
|
-
`,
|
|
1405
|
-
`,
|
|
1406
|
-
`,
|
|
1353
|
+
`,Za=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
|
|
1354
|
+
`,Qa=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
|
|
1355
|
+
`,ec=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
|
|
1356
|
+
`,Ai=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
|
|
1407
1357
|
announceMissingDesktopSdk("posthog");
|
|
1408
1358
|
}
|
|
1409
|
-
`,
|
|
1359
|
+
`,tc="export type BrowserReportingOptions = SentryBrowserInitOptions;",rc=`export interface BrowserReportingOptions {
|
|
1410
1360
|
/** The deployment environment reports are tagged with. */
|
|
1411
1361
|
environment: string;
|
|
1412
|
-
}`,
|
|
1413
|
-
`,
|
|
1414
|
-
`,
|
|
1362
|
+
}`,nc=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
|
|
1363
|
+
`,ic=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
|
|
1364
|
+
`,oc="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",sc=`export interface DesktopMainReportingOptions {
|
|
1415
1365
|
/** The deployment environment reports are tagged with. */
|
|
1416
1366
|
environment: string;
|
|
1417
1367
|
/** Whether Electron's \`app\` has emitted \`ready\` yet. */
|
|
1418
1368
|
appIsReady: boolean;
|
|
1419
|
-
}`,
|
|
1420
|
-
`,
|
|
1421
|
-
`;function
|
|
1422
|
-
`},{find:
|
|
1423
|
-
`},{find:
|
|
1369
|
+
}`,ac=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
|
|
1370
|
+
`,cc=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
|
|
1371
|
+
`;function Pi(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function lc(e){let t=[{find:za,replace:" into every browser bundle."},...Pi(e,{sentry:qa,posthog:Ja})];return e.includes("sentry")||t.push({find:Xa,replace:""}),t}function pc(e){let t=[...Pi(e,{sentry:Za,posthog:Qa})];return e.includes("sentry")||t.push({find:ec,replace:""},dc),t}var dc={find:tc,replace:rc};function uc(e){let t=[];return e.includes("posthog")||t.push({find:Ai,replace:""}),e.includes("sentry")||t.push({find:nc,replace:` return [];
|
|
1372
|
+
`},{find:ic,replace:""},{find:oc,replace:sc}),t}function mc(e){let t=[];return e.includes("posthog")||t.push({find:Ai,replace:""}),e.includes("sentry")||t.push({find:ac,replace:` return [];
|
|
1373
|
+
`},{find:cc,replace:""}),t}var fc=` if (!posthogConfigured()) return;
|
|
1424
1374
|
try {
|
|
1425
1375
|
const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
|
|
1426
1376
|
await capture(event);
|
|
1427
1377
|
} catch (reportingError) {
|
|
1428
1378
|
logReportingFailure("[observability] failed to report an AI generation", reportingError);
|
|
1429
1379
|
}
|
|
1430
|
-
`,
|
|
1431
|
-
`,
|
|
1432
|
-
`,
|
|
1380
|
+
`,hc=` // No PostHog adapter was generated for this project, so there is nothing to report to.
|
|
1381
|
+
`,gc=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
|
|
1382
|
+
`,yc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
|
|
1433
1383
|
function posthogConfigured(): boolean {
|
|
1434
1384
|
return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
|
|
1435
1385
|
}
|
|
1436
1386
|
|
|
1437
|
-
`,
|
|
1387
|
+
`,vc=` if (!posthogConfigured()) return;
|
|
1438
1388
|
try {
|
|
1439
1389
|
const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
|
|
1440
1390
|
await flush();
|
|
1441
1391
|
} catch (reportingError) {
|
|
1442
1392
|
logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
|
|
1443
1393
|
}
|
|
1444
|
-
`;function
|
|
1394
|
+
`;function wc(e){return e.includes("posthog")?[]:[{find:fc,replace:hc},{find:vc,replace:gc},{find:yc,replace:""},{find:`import { logReportingFailure } from "./logger";
|
|
1445
1395
|
`,replace:""},{find:`import { config } from "@repo/config";
|
|
1446
|
-
`,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var
|
|
1447
|
-
`),await l(
|
|
1448
|
-
`)}import{relative as
|
|
1449
|
-
`);
|
|
1450
|
-
${g}`:
|
|
1451
|
-
`),
|
|
1452
|
-
`),
|
|
1453
|
-
`),
|
|
1454
|
-
`),await Ii(f,f)}await Oi(f),await Pi($,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await Di(f)&&$.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Ni(f),X=$.demo!==!0&&e.dbMigration!==!1,he=!1;X&&fe&&(await Ci(f),he=!0),await $i(f),fe&&await Li(f);let Ee=Ue("docker"),Re=nr($).map(v=>v.key).filter(v=>!$.credentials?.[v]);ji($,{pnpmInstalled:fe,dockerAvailable:Ee,skippedCredentials:Re,baselineMigrationMissing:X&&!he}),Fr(),b.log.info(Mc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Nr}from"fs";import{readFile as zi}from"fs/promises";import{join as st,resolve as zc}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as Bc,rm as Kc}from"fs/promises";import{tmpdir as Gc}from"os";import{join as Hc}from"path";async function Or(e,t,r,n){let i=await Bc(Hc(Gc(),"generatesaas-stage-"));try{await Nt(e,t,i),await qt({...r,projectDir:i}),await Ar(i,n)}finally{await Kc(i,{recursive:!0,force:!0})}}function Et(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var xr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:qe,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:ze,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Je,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:B,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, schedules, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ie({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>Et(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function Yc(e,t){return e[t]!==void 0}function Vi(e){return xr.filter(t=>t.adoptable&&!Yc(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function Wc(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function qc(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Bi(e){let t=[];for(let r of xr){let n=e[r.key];n!==void 0&&(Wc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${qc(r)}.`))}return t}function Ki(e){let t={};for(let r of xr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Gi(e){return e?"ON":"OFF"}var St="packages/config/src/index.ts";function Hi(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function Yi(e){return[...We({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Dr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${St} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${St} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${St}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===Et(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Gi(e.aiBuiltin)}, but it is now a plain config value generated ${Gi(Et(e))} for a project ${Et(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${St} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${St} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Hi(e).join(",")===Yi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Hi(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${Yi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Kr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${je.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`}],sf=Dr.map(e=>e.key);function Wi(e){for(let t of Dr)t.normalize?.(e)}function qi(e){let t=[];for(let r of Dr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function Ji(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=zc(r.cwd??process.cwd()),o=st(i,ve),s;try{s=JSON.parse(await zi(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===ir&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
|
|
1396
|
+
`,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var ki=[{file:"src/resolve-server.ts",edits:lc},{file:"src/resolve-browser.ts",edits:pc},{file:"src/llm-analytics.ts",edits:wc,dualMode:!1}],bc=[{file:"src/resolve-desktop-main.ts",edits:uc},{file:"src/resolve-desktop-renderer.ts",edits:mc}];import{readdir as kc,readFile as Ec}from"fs/promises";import{join as Ri}from"path";async function Ii(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ri(e.projectDir,"packages/i18n/translations"),i;try{i=await kc(n)}catch{return}for(let s of i){let o=Ri(n,s,"web.json"),a;try{a=await Ec(o,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(o,p)}}async function zt(e){let t=e.projectDir;e.demo||(await hn(t),await gn(t),await yn(t),await vn(t)),await wn(t),await kn(e),await Sn(e),await An(e),e.demo||await Pn(e),await _n(e),await On(e),await xn(e),await Ln(e),await jn(e),await Mn(e),await Vn(e),await Kn(e),await Yn(e),await ei(e),await ui(e),await ti(e),await ri(e),await ni(e),await ii(e),await oi(e),await si(e),await ai(e),await li(e),await Sr(e),await hi(e),await yi(e),await Si(e),await Ii(e),await zn(e)}import{basename as _i,join as Oi,relative as Ac}from"path";import{createHash as Ti}from"crypto";import{readFile as Sc}from"fs/promises";async function qt(e){let t=await Sc(e);return Ti("sha256").update(t).digest("hex")}function Ir(e){return Ti("sha256").update(e).digest("hex")}var Pc=new Set(["data",Y]);function Rc(e){let t=e.split("/");for(let r of t)if(lr.has(r)||pr.has(r)||Pc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function xi(e,t){return{projectName:e.projectName??_i(t),appName:e.appName??e.projectName??_i(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,projects:e.projects??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,webAi:e.webAi??!0,runner:e.runner??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Ic(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:en,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,projects:e.projects,docs:e.docs,desktop:e.desktop,ai:e.ai,webAi:e.webAi,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Di(e,t){let n=(await de(e.projectDir,e.projectDir,Rc)).sort(),i=await Promise.all(n.map(async a=>[De(Ac(e.projectDir,a)),await qt(a)])),s=Object.fromEntries(i),o=Ic(e,t);await l(Oi(e.projectDir,ge),JSON.stringify(o,null," ")+`
|
|
1397
|
+
`),await l(Oi(e.projectDir,tn),JSON.stringify(s,null," ")+`
|
|
1398
|
+
`)}import{relative as Tc}from"path";async function tt(e){let r=(await de(e,e,Je)).sort(),n=await Promise.all(r.map(async i=>[De(Tc(e,i)),await qt(i)]));return Object.fromEntries(n)}import{copyFile as _c,mkdir as Oc,rm as xc}from"fs/promises";import{dirname as Dc,join as Ni,relative as Nc}from"path";import{existsSync as Cc}from"fs";async function Tr(e,t){Cc(t)&&await xc(t,{recursive:!0,force:!0});let n=(await de(e,e,Je)).map(i=>({file:i,dest:Ni(t,De(Nc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>Dc(i)))].map(i=>Oc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:s})=>_c(i,s)))}async function Ci(e,t){await Tr(e,Ni(t,Dt))}import{readFile as Li,readdir as Lc}from"fs/promises";import{join as ke,dirname as $c,resolve as jc,sep as Uc}from"path";import{fileURLToPath as Mc}from"url";var Fc={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},$e=Object.values(Fc),_r="generatesaas-update",Vc=$c(Mc(import.meta.url));function Bc(){return $t(Vc,["skill","content"],"content")}async function Or(e,t,r){for(let n of $e){let i=ke(e,n,_r),s=ke(i,"scripts"),o=ke(i,"references");await Ut(s),await Ut(o),await l(ke(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(ke(o,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let u=jc(s,a);u.startsWith(s+Uc)&&await l(u,p)}}}async function $i(e){let t=Bc(),r=await Li(ke(t,"SKILL.md"),"utf-8"),n=ke(t,"scripts"),i=await Lc(n),s={};for(let o of i)o!==".gitkeep"&&(s[o]=await Li(ke(n,o),"utf-8"));await Or(e,r,s)}import{execFile as Kc,execFileSync as Gc}from"child_process";import{access as ji,readFile as Hc}from"fs/promises";import{join as xr}from"path";import*as j from"@clack/prompts";function nt(e){try{let t=process.platform==="win32"?"where":"which";return Gc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function rt(e,t,r,n=3e5){return new Promise((i,s)=>{Kc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(o,a,p)=>{if(o){let u=String(a||"").trim(),g=[String(p||"").trim(),u].filter(Boolean).join(`
|
|
1399
|
+
`);s(new Error(g?`${o.message}
|
|
1400
|
+
${g}`:o.message))}else i()})})}async function Ui(e){if(!nt("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await rt("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${r}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Mi(e){if(!nt("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 rt("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return j.log.warn(`pnpm install failed: ${n}`),j.log.warn("You can run it manually later."),!1}}async function Fi(e){try{return await ji(xr(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!nt("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await rt("git",["init"],e),await rt("git",["add","-A"],e),await rt("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 Vi(e){if(!nt("pnpm"))return!1;try{await ji(xr(e,".git"))}catch{return!1}try{let t=JSON.parse(await Hc(xr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await rt("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 it from"@clack/prompts";import z from"picocolors";function Bi(e,t){let r=Ge(e);t.dockerAvailable||it.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${z.dim(`# ${r.map(a=>Kr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${z.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(z.dim("Fill in remaining TODO values in .env"))),it.note(n.join(`
|
|
1401
|
+
`),z.yellow("Start Development"));let i=[];i.push(`App ${z.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${z.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${z.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${z.cyan("http://localhost:8288")}`),it.note(i.join(`
|
|
1402
|
+
`),z.yellow("Dev Tools"));let s=[],o=Yc(e);o.length>0&&s.push(`Set in production: ${z.dim(o.join(", "))}`),s.push("pnpm db:setup # Apply the database schema"),s.push(Wc(e)),it.note(s.join(`
|
|
1403
|
+
`),z.yellow("Deployment"))}function Yc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function Wc(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function ot(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function je(e,t){let r=ot(e),n=ot(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function Jt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Ki(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:ot(e)===null}function Xt(e,t,r="3.3.0"){if(Ki(r))return{ok:!0};let n=Jt(e,e.latest);return!n||ot(n)===null?{ok:!0}:je(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function Gi(e,t,r="3.3.0"){if(Ki(r))return{ok:!0};let n=Jt(e,t);return!n||ot(n)===null?{ok:!0}:je(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Qc from"picocolors";var el="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function tl(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Hi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new Q("--architecture <type>","fullstack or separate").choices([...He])).addOption(new Q("--payment <provider>","payment provider").choices([...Ye])).addOption(new Q("--email <provider>","email provider").choices([...We])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--projects","enable projects (a switcher that scopes a user's work)").option("--no-projects","disable projects").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, automations, integrations); unlocks the runner").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop app is the AI product. Requires --desktop and --ai, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new Q("--currency <code>","default currency for billing").choices([...oe])).addOption(new Q("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([..._e])).addOption(new Q("--deploy <target>","deployment target").choices([...se])).addOption(new Q("--database <provider>","database provider").choices([...ae])).addOption(new Q("--cache <provider>","cache provider").choices([...ce])).option("--observability <providers>",`comma-separated observability providers (${V.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new Q("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new Q("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await rl(t?{...r,apiKey:t}:r)})}async function rl(e){let t=performance.now();Vr("3.3.0");let r;try{r=Xr(e)}catch(v){b.cancel(D(v)),process.exit(1)}let n=b.spinner(),i;try{i=await qe({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(D(v)),process.exit(1)}e.demo&&Ir(i)!==el&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let s=pe(i),o,a=async()=>{o=await we(s);let v=Xt(o,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:o.latest,selectedVersion:o.latest,desktopAllowed:o.entitlements?.desktopAllowed??!0,runnerAllowed:o.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,u,w=!0,g=!0;try{({latestVersion:p,selectedVersion:u,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),xe(i)}catch(v){if(n.stop("Access verification failed."),v instanceof $&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await mt(),s=pe(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:u,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),xe(i)}catch(L){n.stop("Access verification failed."),b.cancel(L instanceof $&&L.status===401?"Invalid API key.":D(L)),process.exit(1)}}else b.cancel(D(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!w&&(b.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(b.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let k;e.yes?k=Zr({...r,...w?{}:{desktop:!1},...g?{}:{runner:!1}}):k=await Qr(r,{desktopAllowed:w,runnerAllowed:g});let P;n.start("Activating license...");try{let v=e.demo&&k.baseUrl?await tl(k.baseUrl):crypto.randomUUID(),L=()=>({frontend:sr,version:u,installId:v,projectName:k.projectName,options:an(k)}),te;try{te=await ar(s,L())}catch(J){let T=Nt(J);if(!T?.lastAllowedVersion||!o)throw J;n.stop("License activation failed.");let fe=Gi(o,T.lastAllowedVersion);if(fe.ok||(b.cancel(`${T.message} ${fe.message}`),process.exit(1)),e.yes){let F=Jt(o,T.lastAllowedVersion);b.cancel(`${T.message} Re-run ${F?`npx generatesaas@${F} init`:"init"} without --yes to continue with v${T.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let Ae=await b.confirm({message:`Your update window has ended. Continue with v${T.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(Ae)||!Ae)&&(b.cancel("Setup cancelled."),process.exit(0)),u=T.lastAllowedVersion,n.start(`Activating license for v${u}...`),te=await ar(s,L())}P={token:te.token,keyHash:Ir(i),installId:te.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(D(v)),process.exit(1)}let f=Zc(k.projectDir);if(zc(f)&&qc(f).length>0)if(e.yes)b.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let L=await b.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(b.isCancel(L)||L==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),L==="overwrite"&&Jc(f,{recursive:!0,force:!0})}let C={...k,projectDir:f,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await Ct(s,u,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(D(v)),process.exit(1)}n.start("Generating project files...");try{if(await zt(C),!e.demo){let v=await tt(f);await l(Xc(f,xt),JSON.stringify(v,null," ")+`
|
|
1404
|
+
`),await Ci(f,f)}await $i(f),await Di(C,P),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await Ui(f)&&C.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let Ee=await Mi(f);await Fi(f),Ee&&await Vi(f);let ee=nt("docker"),Se=nr(C).map(v=>v.key).filter(v=>!C.credentials?.[v]);Bi(C,{pnpmInstalled:Ee,dockerAvailable:ee,skippedCredentials:Se}),Br(),b.log.info(Qc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Lr}from"fs";import{readFile as eo}from"fs/promises";import{join as at,resolve as pl}from"path";import*as y from"@clack/prompts";import N from"picocolors";import{mkdtemp as nl,rm as il}from"fs/promises";import{tmpdir as ol}from"os";import{join as sl}from"path";async function Dr(e,t,r,n){let i=await nl(sl(ol(),"generatesaas-stage-"));try{await Ct(e,t,i),await zt({...r,projectDir:i}),await Tr(i,n)}finally{await il(i,{recursive:!0,force:!0})}}function St(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Nr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:He,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:se,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ye,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:We,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:V,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"projects",label:"Projects",hint:"Adds projects - a switcher that scopes a user's work inside their account or organization.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, automations, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, automations, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ne({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>St(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function al(e,t){return e[t]!==void 0}function Yi(e){return Nr.filter(t=>t.adoptable&&!al(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 cl(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function ll(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Wi(e){let t=[];for(let r of Nr){let n=e[r.key];n!==void 0&&(cl(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${ll(r)}.`))}return t}function zi(e){let t={};for(let r of Nr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function qi(e){return e?"ON":"OFF"}var st="packages/config/src/index.ts";function Ji(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function Xi(e){return[...Ge({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Cr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${st} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${st} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${st}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===St(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${qi(e.aiBuiltin)}, but it is now a plain config value generated ${qi(St(e))} for a project ${St(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${st} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${st} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>Ji(e).join(",")===Xi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Ji(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${Xi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Hr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${$e.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`},{key:"blog",severity:"warn",preserved:e=>e.blog!==!1,describe:()=>`Retired option \`blog\`: your project recorded the blog OFF, but content is no longer an option. This update adds the \`/blog\`, \`/alternatives\` and \`/compare\` route code to your project; every one of them 404s until you add a file under \`packages/content/{locale}/{section}/\`, and none of them appears in your navbar, footer, sitemap or llms.txt while it is empty. Delete an entry from \`config.content.sections\` in ${st} to drop a section for good.`}],Pf=Cr.map(e=>e.key);function Zi(e){for(let t of Cr)t.normalize?.(e)}function Qi(e){let t=[];for(let r of Cr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function to(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=pl(r.cwd??process.cwd()),s=at(i,ge),o;try{o=JSON.parse(await eo(s,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}o.frontend===ir&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${ir}"\`).
|
|
1455
1405
|
|
|
1456
|
-
v${
|
|
1406
|
+
v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
|
|
1457
1407
|
|
|
1458
|
-
Your project keeps working exactly as it is - stay on v${
|
|
1408
|
+
Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${N.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Wi(o);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
|
|
1459
1409
|
|
|
1460
1410
|
${a.map(f=>` - ${f}`).join(`
|
|
1461
1411
|
`)}
|
|
1462
1412
|
|
|
1463
|
-
Correct it there, then run ${
|
|
1413
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1)),Zi(o);let p=ne(o);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
|
|
1464
1414
|
|
|
1465
1415
|
${p.reason}
|
|
1466
1416
|
|
|
1467
|
-
Correct it there, then run ${
|
|
1417
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let u=tr(o);u.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
|
|
1468
1418
|
|
|
1469
|
-
${
|
|
1419
|
+
${u.map(f=>` - ${f}`).join(`
|
|
1470
1420
|
`)}
|
|
1471
1421
|
|
|
1472
|
-
Correct it there, then run ${
|
|
1422
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let w=qr(o);w.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
|
|
1473
1423
|
|
|
1474
1424
|
${w.map(f=>` - ${f}`).join(`
|
|
1475
1425
|
`)}
|
|
1476
1426
|
|
|
1477
|
-
Correct it there, then run ${
|
|
1427
|
+
Correct it there, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await qe()}catch(f){y.cancel(D(f)),process.exit(1)}let k=pe(g),P=y.spinner();try{P.start("Verifying access...");let f;try{f=await we(k)}catch(I){throw I instanceof $&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let C=Xt(f,"update");if(!C.ok)throw new Error(C.message);P.stop("Access verified."),xe(g),P.start("Fetching latest skill files...");let U=await sn(k,f.latest);await Or(i,U.skillMd,U.scripts);let Ee=$e;if(P.stop("Skills updated."),y.log.success(`Skill files installed to ${N.cyan(Ee.length.toString())} locations.`),o.version===f.latest){y.log.info(`Already on the latest version (${o.version}).`);return}let ee=f.entitlements;ee&&(o.desktop&&!ee.desktopAllowed&&(y.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),o.runner&&!ee.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let Fe=JSON.stringify(o);zr(o),await dl(o,Jr(o),n),await ml(Qi(o),n);let Se=Yi(o),v=zi(o),L=tr(v);L.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
|
|
1478
1428
|
|
|
1479
|
-
${
|
|
1429
|
+
${L.map(I=>` - ${I}`).join(`
|
|
1480
1430
|
`)}
|
|
1481
1431
|
|
|
1482
|
-
Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${
|
|
1483
|
-
`),
|
|
1484
|
-
`);let
|
|
1485
|
-
`)}if(
|
|
1486
|
-
`),
|
|
1487
|
-
`),y.log.info(`Update staged: ${
|
|
1432
|
+
Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${N.cyan("generatesaas update")} again.`),process.exit(1));let te=JSON.stringify(v)!==Fe;if(o=v,o.licenseToken)try{let I=await cn(k,{currentToken:o.licenseToken,newVersion:f.latest});o.licenseToken=I.token,I.licenseKeyHash&&(o.licenseKeyHash=I.licenseKeyHash),await l(s,JSON.stringify(o,null," ")+`
|
|
1433
|
+
`),te=!1,y.log.success("License refreshed.")}catch(I){let Pe=Nt(I);Pe&&(y.cancel(Pe.message),process.exit(1)),y.log.warn("License refresh skipped.")}te&&await l(s,JSON.stringify(o,null," ")+`
|
|
1434
|
+
`);let J=xi(o,i),T=at(i,rn);P.start(`Staging v${f.latest} (shaped for your config)...`),await Dr(k,f.latest,J,T),P.stop("Template staged.");let{text:fe,title:Ae}=await gl(k,f,o.version);fe&&y.note(fe,Ae);let F=at(i,xt),re=at(i,Dt),At=!Lr(re),Ve=!Lr(F);if(At){if(P.start("Building baseline template (one-time migration)..."),await Dr(k,o.version,J,re),Ve){let I=await tt(re);await l(F,JSON.stringify(I,null," ")+`
|
|
1435
|
+
`)}if(P.stop("Baseline template stored."),!Ve){let I=await yl(F,re);I>0&&y.log.warn(`Rebuilt baseline differs from the original for ${I} 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(Ve){P.start("Computing baseline template hashes...");let I=await tt(re);await l(F,JSON.stringify(I,null," ")+`
|
|
1436
|
+
`),P.stop("Baseline hashes computed.")}await l(at(i,nn),JSON.stringify({currentVersion:o.version,targetVersion:f.latest,changelog:fe,stagedAt:new Date().toISOString(),...Se.length>0?{newOptions:Se}:{},...n?{mode:n}:{}},null," ")+`
|
|
1437
|
+
`),y.log.info(`Update staged: ${N.cyan(o.version)} \u2192 ${N.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${N.cyan("'update my GenerateSaaS project'")}.`),o.desktop===!0&&Lr(at(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${N.cyan("apps/electron")}). Your project still has the old Tauri shell (${N.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${N.cyan("/desktop/updates")}.`)}catch(f){P.stop("Failed."),y.cancel(`Update failed: ${D(f)}`),process.exit(1)}})}async function dl(e,t,r){if(t.kind==="none")return;let n=hl[t.kind];r==="auto"&&(y.cancel(`${n.message}
|
|
1488
1438
|
|
|
1489
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1439
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var ul={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function ml(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?ul[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(y.cancel(`${n.message}
|
|
1490
1440
|
|
|
1491
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1441
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${N.cyan("generatesaas update")} without ${N.cyan("auto")} and answer it.`),process.exit(1));let s=await y.select({message:n.message,options:i});(y.isCancel(s)||s==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function fl(e){e.desktop=!1}var hl={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:fl},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function gl(e,t,r){let n=t.latest,i=t.versions.filter(p=>je(p.version,r)>0&&je(p.version,n)<=0).sort((p,u)=>je(p.version,u.version)),s=async p=>{try{return await on(e,p)}catch{return null}};if(i.length<=1)return{text:await s(n),title:`Changelog v${n}`};let o=await Promise.all(i.map(p=>s(p.version)));return{text:i.map((p,u)=>{let w=p.date?` (${p.date.slice(0,10)})`:"",g=o[u]??"_No changelog available for this release._";return`# v${p.version}${w}
|
|
1492
1442
|
|
|
1493
|
-
${
|
|
1443
|
+
${g}`}).join(`
|
|
1494
1444
|
|
|
1495
|
-
`),title:`Changelog v${r} \u2192 v${n}`}}async function
|
|
1496
|
-
`);
|
|
1497
|
-
`),
|
|
1498
|
-
`).map(
|
|
1445
|
+
`),title:`Changelog v${r} \u2192 v${n}`}}async function yl(e,t){let r=JSON.parse(await eo(e,"utf-8")),n=await tt(t),i=0;for(let[s,o]of Object.entries(r))Je(s)||n[s]!==o&&i++;for(let s of Object.keys(n))s in r||i++;return i}import*as G from"@clack/prompts";import me from"picocolors";import{readFile as vl}from"fs/promises";import{join as wl,resolve as bl}from"path";function ro(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=bl(t.cwd??process.cwd()),n=wl(r,ge),i;try{i=JSON.parse(await vl(n,"utf-8"))}catch{G.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s=[`Version: ${me.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${me.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${me.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${me.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
|
|
1446
|
+
`);G.note(s,me.bold("Project Status"));let o=G.spinner();o.start("Checking for updates...");try{let a=await qe(),p=pe(a),w=(await we(p)).latest;i.version===w?(o.stop("Up to date."),G.log.success(`Already on the latest version (${me.green(w)})`)):(o.stop("Update available."),G.log.warning(`Update available: ${me.yellow(i.version)} \u2192 ${me.green(w)}`),G.log.info(`Open this project in your AI coding agent and ask it to ${me.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){o.stop("Check failed."),a instanceof $&&a.status===401?G.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):G.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as kl}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function El(){return process.env.GENERATESAAS_API_KEY??ut()}function Sl(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 Al(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Pl(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.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 x.log.error(`${O.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 x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function no(e,t){let r=process.env.GENERATESAAS_API_URL??dt,n=El();e.start("Cross-referencing license records...");try{let i=n?Sl(await ln(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Al(await cr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),Pl(i)}catch(i){return e.stop(`${O.yellow("Skipped")} - ${D(i)}`),null}}function Rl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function $r(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function io(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${$r(e.pat)}`,`Last updated: ${$r(e.uat)}`,`Expires: ${$r(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1447
|
+
`),O.yellow("License Details"))}function Il(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function oo(e){let t=x.spinner(),r=null,n="no candidates";for(let o of Il(e)){t.start(`Checking ${o}...`);try{let a=await fetch(o);if(!a.ok){n=`${o} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${o} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${o}: ${D(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let o=so(e);return o?await no(t,{domain:o})??!1:!1}let i;try{i=Rl(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let o=process.env.GENERATESAAS_API_URL??dt,a=await cr(o,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),io(i),!1}return io(i),await no(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:so(e)})??!0}function so(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ao(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await kl(r.file,"utf-8")).split(`
|
|
1448
|
+
`).map(o=>o.trim()).filter(o=>o&&!o.startsWith("#"));i.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let s=0;for(let o of i)await oo(o)&&s++,x.log.info("");x.log.success(`${s}/${i.length} sites verified.`)}else await oo(t)||process.exit(1)})}import{existsSync as Tl,rmSync as _l}from"fs";import*as q from"@clack/prompts";function co(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Tl(le)?(_l(le),q.log.success("API key removed.")):q.log.info("No API key configured.");return}let r=ut();r?q.log.info(`Current API key: ****${r.slice(-4)}`):q.log.info("No API key configured.");let n=await mt(),i=pe(n),s=q.spinner();s.start("Verifying API key...");try{await we(i),s.stop("API key verified."),xe(n),q.log.success("API key saved.")}catch(o){s.stop("Verification failed."),o instanceof $&&o.status===401?q.cancel("Invalid API key."):q.cancel(D(o)),process.exit(1)}})}import{existsSync as Zt,rmSync as Ol,readFileSync as Ur,writeFileSync as lo}from"fs";import{join as Ue}from"path";import*as M from"@clack/prompts";var xl=["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"],Dl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1499
1449
|
`,` licenseHeartbeatFunction,
|
|
1500
1450
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1501
1451
|
`,` .route("/license", licenseRoutes)
|
|
1502
1452
|
`]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
|
|
1503
|
-
`],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function
|
|
1453
|
+
`],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function Nl(){return $e.map(e=>Ue(e,_r))}function jr(e){return Zt(e)?(Ol(e,{recursive:!0}),!0):!1}function Cl(e,t,r=[]){if(!Zt(e))return!1;let n=Ur(e,"utf-8"),i=n;for(let s of t)i=i.replace(s,"");for(let{from:s,to:o}of r)i=i.replace(s,o);return i===n?!1:(lo(e,i,"utf-8"),!0)}function Ll(e){let t=Ue(e,".gitignore");if(!Zt(t))return!1;let r=Ur(t,"utf-8"),n=r.split(`
|
|
1504
1454
|
`).filter(i=>!i.includes(".generatesaas")).join(`
|
|
1505
|
-
`);return n===r?!1:(
|
|
1455
|
+
`);return n===r?!1:(lo(t,n,"utf-8"),!0)}function po(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ue(t,ge),n;try{n=JSON.parse(Ur(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(M.isCancel(i)&&(M.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let s=[],o=[];for(let a of Nl())jr(Ue(t,a))&&s.push(a);for(let a of xl)jr(Ue(t,a))&&s.push(a);jr(Ue(t,Y))&&s.push(Y+"/");for(let a of Dl){let p=Ue(t,a.file);Cl(p,a.removals,a.replacements)?o.push(a.file):Zt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Ll(t)&&o.push(".gitignore");for(let a of s)M.log.info(`Deleted ${a}`);for(let a of o)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Me=new $l().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.3.0").addHelpText("after",`
|
|
1506
1456
|
Examples:
|
|
1507
1457
|
$ generatesaas init Interactive setup
|
|
1508
1458
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1509
1459
|
$ generatesaas status Check for updates
|
|
1510
1460
|
$ generatesaas auth Set or update API key
|
|
1511
|
-
`);
|
|
1461
|
+
`);Hi(Me);to(Me);ro(Me);ao(Me);co(Me);po(Me);Me.parseAsync().catch(e=>{uo.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|