generatesaas 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +107 -107
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as zc}from"commander";import*as xi from"@clack/prompts";import{existsSync as ac,readdirSync as sc,rmSync as cc}from"fs";import{join as pc,resolve as lc}from"path";import{Option as ee}from"commander";import*as A from"@clack/prompts";import*as Nt from"@clack/prompts";import hn from"picocolors";function lr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(hn.bgYellow(hn.black(t)))}function dr(){Nt.outro(hn.yellow("Happy building!"))}import*as f from"@clack/prompts";import h from"picocolors";var ht={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},yt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},$t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ut={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},qe={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}},wt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var Ne={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 se={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}},X={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"}]}},ce={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},vt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],kt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ur=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function jt(e){let t=X[e.databaseProvider].managed,n=ce[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ge={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var $e=["nextjs","nuxt"],Ye=["fullstack","separate"],We=["stripe","polar","none"],Xe=["smtp","ses","resend"],Ze=["postgres","redis","inngest","mailpit"],Qe=["claude-code","cursor","codex","gemini-cli","windsurf"],et=["user","organization"],he=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ye=["node","vercel"],we=["postgres","neon","supabase"],ve=["redis","upstash"],tt=["google","github","facebook","discord","x"],Le=["shared","vendored"];function Mt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Vt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function re(e){let t=e?.trim();return t?`${nt(t)} Companion`:"My Companion"}var Ue="https://github.com/Duzbee/OpenCompanion";function pe(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function mr(e){return e.desktop===!0&&e.ai===!0}function Z(e){if(mr(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return pe(e)}function Q(e){return mr(e)?!0:e.companion===!0&&pe(e)==="vendored"}function Ee(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var fr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:$e,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ye,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ye,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:we,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ve,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:he,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:et,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>Z(e),choices:Le,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Ue,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&pe(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&pe(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>re(e.projectName),adoptable:!0,impact:"config",requires:e=>Q(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ee(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ee(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>Ee(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:tt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,adoptable:!1,impact:"config"}];function _i(e,t){return e[t]!==void 0}function gr(e){return fr.filter(t=>t.adoptable&&!_i(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 hr(e){let t={};for(let n of fr)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as wn}from"fs/promises";import{join as yr}from"path";var yn="GENERATESAAS_COMPANION_BRAND_JSON",Ft=["daemon/brand.json","apps/companion/brand.json"];function le(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function wr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Bt(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}async function Oi(e,t){let n=yr(e,"apps/companion/brand.json"),r;try{r=await wn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=le(o)}catch{return null}return wr(i,t)?Bt(r,`the template (${n})`):null}async function Ci(e,t){for(let n of Ft){let r=yr(e,n),o;try{o=await wn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Bt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=le(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!wr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Ft.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function Di(e){for(let t of Ft){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return Bt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Ft.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function vr(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=le(t),r=await Oi(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Ci(o,n);let i=process.env[yn]?.trim();if(i){let a;try{a=await wn(i,"utf8")}catch(s){throw new Error(`Could not read ${yn} (${i}): ${T(s)}.`)}return Bt(a,`${yn} (${i})`)}return await Di(n)}var kr=["companion","mcpServer"];function kn(e){if(!kr.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function br(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ee(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function bn(e){if(!br(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Sr(e){return kr.some(n=>e[n]===!0)&&(e.ai=!0),e}function Er(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ee(e)||(e.aiBuiltin=!1),br(e)||(e.aiByok=!0)),e}function Ir(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=Ni(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&Sn(e),n}function Sn(e){return Q(e)&&(e.companionSource=Z(e),e.companionName===void 0&&(e.companionName=re(e.projectName))),e}function Ni(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function Ar(e){let t={};if(e.name!==void 0){if(!Vt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!$e.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${$e.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!Le.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${Le.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=le(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),kn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, or turn AI off with --no-ai.");if(e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.docker!==void 0&&(t.dockerServices=vn(e.docker,Ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=vn(e.aiTools,Qe,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=vn(e.socialProviders,tt,"social provider")),e.currency!==void 0){if(!he.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${he.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ye.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ye.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!we.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${we.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ve.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ve.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var de={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Pr(e){let t=e.projectName??de.projectName,n=e.projectDir??`./${t}`,r=e.appName??nt(t),o=e.deploymentTarget??de.deploymentTarget,i=se[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":de.databaseProvider),s=e.cacheProvider??(i?"upstash":de.cacheProvider),u=e.emailProvider??(i?"resend":de.emailProvider),g=e.dockerServices??(i?de.dockerServices.filter(m=>m!=="postgres"&&m!=="redis"):de.dockerServices),l={...de,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=de.aiBuiltin,l.aiByok=de.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=Z(l)),Q(l)&&l.companionName===void 0&&(l.companionName=re(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=pe(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=re(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Ue),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),bn(l);for(let m of vt){if(l.deploymentTarget!==m.target)continue;let w=l.databaseProvider===m.provider?"database":"cache";if(l.databaseProvider===m.provider||l.cacheProvider===m.provider)throw new Error(`Incompatible: --deploy ${m.target} + --${w} ${m.provider}. ${m.reason}`)}for(let m of kt)if(l.architecture===m.architecture&&l.deploymentTarget===m.target)throw new Error(`Incompatible: --architecture ${m.architecture} + --deploy ${m.target}. ${m.reason}`);return l}function vn(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function S(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function En(e){let t=[];e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0}));for(let n of e.socialProviders){let r=ge[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Rr(e,t){let n=!1;e&&kn(e),f.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Vt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await f.text({message:"App name:",initialValue:nt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await f.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(ht),d=await f.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:ht[b].label,hint:ht[b].hint}))});return S(d),d})();f.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await f.select({message:"Deployment target:",options:ye.map(d=>({value:d,label:se[d].label,hint:se[d].hint}))});S(c),s=c}let u=e?.architecture?kt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(kt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ye.filter(c=>!g.has(c)),m=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return f.log.info(`Auto-selected ${yt[d].label} architecture (only compatible option for ${se[s].label}).`),d}n=!0;let c=await f.select({message:"Architecture:",options:l.map(d=>({value:d,label:yt[d].label,hint:yt[d].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=we.filter(b=>!vt.some(H=>H.target===s&&H.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${X[b].label} (only compatible option for ${se[s].label}).`),b}let d=await f.select({message:"Database provider:",options:c.map(b=>({value:b,label:X[b].label,hint:X[b].hint}))});return S(d),d})(),v=e?.cacheProvider??await(async()=>{n=!0;let c=ve.filter(b=>!vt.some(H=>H.target===s&&H.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${ce[b].label} (only compatible option for ${se[s].label}).`),b}let d=await f.select({message:"Cache provider:",options:c.map(b=>({value:b,label:ce[b].label,hint:ce[b].hint}))});return S(d),d})();if(se[s]?.edgeRuntime){let c=ur.map(d=>` - ${d}`).join(`
|
|
3
|
-
`);f.note(c,"Unavailable on edge runtime")}f.log.info(h.bold("Features"));let
|
|
4
|
-
`),d=[` Deploy target: ${h.cyan(
|
|
5
|
-
`),b=[
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function rt(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=St();if(n)return n;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return Et()}async function Et(){let e=await
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)}async function I(e,t,n,r,o){let i=await It(e,"utf-8"),a=i.indexOf(t);if(a===-1)throw new Error(`${o}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,a+t.length)!==-1)throw new Error(`${o}: the ${r} seam appears more than once (boilerplate drift).`);await p(e,i.slice(0,a)+n+i.slice(a+t.length))}async function
|
|
13
|
-
`)}function
|
|
14
|
-
`,"",`${t} meta.json ${n} nav entry`,o),await
|
|
2
|
+
import{Command as Jc}from"commander";import*as Ti from"@clack/prompts";import{existsSync as sc,readdirSync as cc,rmSync as pc}from"fs";import{join as lc,resolve as dc}from"path";import{Option as X}from"commander";import*as A from"@clack/prompts";import*as Nt from"@clack/prompts";import yn from"picocolors";function dr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Nt.intro(yn.bgYellow(yn.black(t)))}function ur(){Nt.outro(yn.yellow("Happy building!"))}import*as f from"@clack/prompts";import h from"picocolors";var ht={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},yt={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},$t={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Lt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},Ut={user:{label:"Per user",hint:"each user has their own subscription"},organization:{label:"Per organization",hint:"org subscription shared by members"}},qe={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}},wt={"claude-code":{label:"Claude Code"},cursor:{label:"Cursor"},codex:{label:"Codex"},"gemini-cli":{label:"Gemini CLI"},windsurf:{label:"Windsurf"}};var De={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var ie={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Y={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},ae={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},vt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],kt=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],mr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function jt(e){let t=Y[e.databaseProvider].managed,n=ae[e.cacheProvider].managed;return e.dockerServices.some(r=>!(r==="postgres"&&t||r==="redis"&&n))}var ue={google:{label:"Google",envVars:[{name:"GOOGLE_CLIENT_ID",secret:!1},{name:"GOOGLE_CLIENT_SECRET",secret:!0}]},github:{label:"GitHub",envVars:[{name:"GITHUB_CLIENT_ID",secret:!1},{name:"GITHUB_CLIENT_SECRET",secret:!0}]},facebook:{label:"Facebook",envVars:[{name:"FACEBOOK_CLIENT_ID",secret:!1},{name:"FACEBOOK_CLIENT_SECRET",secret:!0}]},discord:{label:"Discord",envVars:[{name:"DISCORD_CLIENT_ID",secret:!1},{name:"DISCORD_CLIENT_SECRET",secret:!0}]},x:{label:"X",envVars:[{name:"TWITTER_CLIENT_ID",secret:!1},{name:"TWITTER_CLIENT_SECRET",secret:!0}]}};var Ne=["nextjs","nuxt"],Ye=["fullstack","separate"],We=["stripe","polar","none"],Xe=["smtp","ses","resend"],Ze=["postgres","redis","inngest","mailpit"],Qe=["claude-code","cursor","codex","gemini-cli","windsurf"],et=["user","organization"],me=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],fe=["node","vercel"],ge=["postgres","neon","supabase"],he=["redis","upstash"],tt=["google","github","facebook","discord","x"],$e=["shared","vendored"];function Mt(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function nt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Vt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function T(e){return e instanceof Error?e.message:String(e)}function ee(e){let t=e?.trim();return t?`${nt(t)} Companion`:"My Companion"}var Le="https://github.com/Duzbee/OpenCompanion";function se(e){return e.companionSource==="shared"||e.companionSource==="vendored"?e.companionSource:e.companionName?"vendored":"shared"}function fr(e){return e.desktop===!0&&e.ai===!0}function W(e){if(fr(e)){if(e.companionSource==="shared")throw new Error("A desktop app with AI bundles its own companion daemon, so its companion source must be vendored. Remove the shared companion source, or turn AI off on this project.");return"vendored"}return se(e)}function ye(e){return fr(e)?!0:e.companion===!0&&se(e)==="vendored"}function Ft(e){return e.demo===!0&&e.companion===!0?!0:ye(e)}function Ie(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var gr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ne,adoptable:!1,impact:"structural"},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ye,adoptable:!1,impact:"structural"},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:fe,adoptable:!1,impact:"config"},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ge,adoptable:!1,impact:"config"},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:he,adoptable:!1,impact:"config"},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural"},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:me,adoptable:!1,impact:"config"},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Xe,adoptable:!1,impact:"config"},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"billingScope",label:"Billing scope",hint:"Whether subscriptions belong to a user or an organization.",category:"Features",kind:"enum",default:"user",choices:et,adoptable:!1,impact:"config",requires:e=>e.multiTenancy===!0,requiresLabel:"requires multi-tenancy"},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"emailTracking",label:"Email analytics",hint:"Tracks opens and clicks of marketing emails and adds an admin analytics page.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config"},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"desktopAutoRelease",label:"Desktop auto-release",hint:"Release the desktop app on every CI success (vs manual-only).",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.desktop===!0,requiresLabel:"requires the desktop app"},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion, MCP server, and BYOK options. On a desktop project it also ships the app's local AI stack and bundles a companion daemon inside the packaged app. Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural"},{key:"companion",label:"Companion daemon",hint:"Lets your users install a companion daemon that runs their own AI subscriptions (and any device-side work you add) on their hardware. Point it at an existing shared companion like OpenCompanion (default, nothing to maintain), or vendor and publish your own branded daemon.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"companionSource",label:"Companion source",hint:"Point at an existing shared companion repo (like OpenCompanion), or vendor a branded daemon you own and publish yourself.",category:"Features",kind:"enum",default:e=>W(e),choices:$e,adoptable:!0,impact:"structural",requires:e=>e.companion===!0||e.desktop===!0&&e.ai===!0,requiresLabel:"requires the companion, or a desktop app with AI"},{key:"companionRepoUrl",label:"Companion repo URL",hint:"GitHub repository of the shared companion this project points at. Its brand.json supplies the daemon identity; your users install from its latest release.",category:"Features",kind:"text",default:()=>Le,adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionLocalPath",label:"Companion local checkout",hint:"Optional path to your local checkout of the shared companion, if you develop it alongside this project. Leave empty otherwise.",category:"Features",kind:"text",default:()=>"",adoptable:!0,impact:"config",requires:e=>e.companion===!0&&se(e)==="shared",requiresLabel:"requires a shared-source companion"},{key:"companionName",label:"Companion name",hint:"What your users install - the display name of your branded companion daemon.",category:"Features",kind:"text",default:e=>ee(e.projectName),adoptable:!0,impact:"config",requires:e=>ye(e),requiresLabel:"requires a bundled daemon: a vendored companion, or a desktop app with AI"},{key:"mcpServer",label:"Outward MCP server",hint:"Exposes the app's capability layer to external agents as an authenticated MCP OAuth server.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"aiBuiltin",label:"Built-in AI (credits)",hint:"Your app offers models under its own name via OpenRouter, billed from user credits (which need a payment provider to buy). The only setup is OPENROUTER_API_KEY.",category:"Features",kind:"boolean",default:e=>Ie(e),adoptable:!1,impact:"config",requires:e=>e.ai===!0&&Ie(e),requiresLabel:"requires AI features and a payment provider"},{key:"aiByok",label:"User API keys (BYOK)",hint:"Let end-users connect their own provider API keys; runs on their key never use credits.",category:"Features",kind:"boolean",default:!0,adoptable:!1,impact:"config",requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",requires:e=>Ie(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config"},{key:"socialProviders",label:"Social login providers",hint:"Which social sign-in buttons the auth screen shows.",category:"Features",kind:"multiselect",default:[],choices:tt,adoptable:!1,impact:"config"},{key:"dockerServices",label:"Docker services",hint:"Local services scaffolded in docker-compose.",category:"Tooling",kind:"multiselect",default:[],choices:Ze,adoptable:!1,impact:"config"},{key:"aiTools",label:"AI coding tools",hint:"Which AI assistants receive the bundled skill files.",category:"Tooling",kind:"multiselect",default:[],choices:Qe,adoptable:!1,impact:"config"}];function Oi(e,t){return e[t]!==void 0}function hr(e){return gr.filter(t=>t.adoptable&&!Oi(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function yr(e){let t={};for(let n of gr)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}import{readFile as vn}from"fs/promises";import{join as wr}from"path";var wn="GENERATESAAS_COMPANION_BRAND_JSON",Bt=["daemon/brand.json","apps/companion/brand.json"];function ce(e){let t=e.trim(),n;try{n=new URL(t)}catch{throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`)}if(n.protocol!=="https:"&&n.protocol!=="http:")throw new Error(`Invalid companion repo URL "${t}". Use a full GitHub URL like https://github.com/owner/repo.`);let r=n.hostname.toLowerCase();if(r!=="github.com"&&r!=="www.github.com")throw new Error(`Only GitHub-hosted shared companions are supported right now (got "${n.hostname}"). Host the companion on GitHub, or vendor your own with --companion-source vendored.`);let o=n.pathname.split("/").filter(Boolean),i=o[0],a=o[1]?.replace(/\.git$/,"");if(!i||!a)throw new Error(`"${t}" is missing the owner/repo path. Use a full GitHub URL like https://github.com/owner/repo.`);return{owner:i,repo:a,canonicalUrl:`https://github.com/${i}/${a}`}}function vr(e,t){return e.owner.toLowerCase()===t.owner.toLowerCase()&&e.repo.toLowerCase()===t.repo.toLowerCase()}function Gt(e,t){let n;try{n=JSON.parse(e)}catch{throw new Error(`The companion brand.json from ${t} is not valid JSON.`)}if(typeof n!="object"||n===null)throw new Error(`The companion brand.json from ${t} is not a JSON object.`);let r=n;for(let o of["name","binary","envPrefix"]){let i=r[o];if(typeof i!="string"||i.trim()==="")throw new Error(`The companion brand.json from ${t} is missing a usable "${o}" field. Point at a companion repo built with the GenerateSaaS export pipeline, or vendor your own with --companion-source vendored.`)}return{name:r.name,binary:r.binary,envPrefix:r.envPrefix}}async function Ci(e,t){let n=wr(e,"apps/companion/brand.json"),r;try{r=await vn(n,"utf8")}catch(a){if(typeof a=="object"&&a!==null&&"code"in a&&a.code==="ENOENT")return null;throw a}let o;try{o=JSON.parse(r).repoUrl}catch{throw new Error("The template's apps/companion/brand.json is not valid JSON (boilerplate drift).")}if(typeof o!="string"||o.trim()==="")return null;let i;try{i=ce(o)}catch{return null}return vr(i,t)?Gt(r,`the template (${n})`):null}async function Di(e,t){for(let n of Bt){let r=wr(e,n),o;try{o=await vn(r,"utf8")}catch(s){if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")continue;throw s}let i=Gt(o,r),a=JSON.parse(o).repoUrl;if(typeof a=="string"&&a.trim()!==""){let s;try{s=ce(a)}catch{throw new Error(`The companion checkout at ${r} names an unusable repoUrl ("${a}"), so it cannot be verified against ${t.canonicalUrl}. Fix the checkout's brand.json, or drop --companion-local-path to fetch the identity from GitHub.`)}if(!vr(s,t))throw new Error(`The companion checkout at ${e} belongs to ${s.canonicalUrl}, but the project points at ${t.canonicalUrl}. Point --companion-repo-url and --companion-local-path at the same companion, or drop --companion-local-path to fetch the identity from GitHub.`)}return i}throw new Error(`No brand.json found in ${e} (checked ${Bt.join(" and ")}). Point --companion-local-path at a checkout of the companion repo, or remove it to fetch the identity from GitHub.`)}async function Ni(e){for(let t of Bt){let n=`https://raw.githubusercontent.com/${e.owner}/${e.repo}/HEAD/${t}`,r;try{r=await fetch(n)}catch(o){throw new Error(`Could not reach GitHub to read the companion identity (${n}): ${T(o)}. Check your network, or pass --companion-local-path to a local checkout of the companion.`)}if(r.status!==404){if(!r.ok)throw new Error(`GitHub returned ${r.status} for ${n}. Check that ${e.canonicalUrl} exists and is public.`);return Gt(await r.text(),n)}}throw new Error(`No brand.json found in ${e.canonicalUrl} (tried ${Bt.join(" and ")} on the default branch). Point --companion-repo-url at a companion repo built with the GenerateSaaS export pipeline.`)}async function kr(e){let t=e.companionRepoUrl?.trim();if(!t)throw new Error("resolveSharedCompanionBrand: companionRepoUrl is missing for a shared-source companion.");let n=ce(t),r=await Ci(e.projectDir,n);if(r)return r;let o=e.companionLocalPath?.trim();if(o)return await Di(o,n);let i=process.env[wn]?.trim();if(i){let a;try{a=await vn(i,"utf8")}catch(s){throw new Error(`Could not read ${wn} (${i}): ${T(s)}.`)}return Gt(a,`${wn} (${i})`)}return await Ni(n)}var br=["companion","mcpServer"];function bn(e){if(!br.some(n=>e[n]===!0))return e;if(e.ai===!1)throw new Error("--companion / --mcp-server require AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Sr(e){if(e.ai!==!0)return!0;let t=e.aiBuiltin===!0&&Ie(e),n=e.desktop===!0;return t||e.aiByok===!0||e.companion===!0||n}function Sn(e){if(!Sr(e))throw new Error("AI features have no usable model source: built-in AI needs a payment provider (it bills from user credits), user API keys (BYOK) are off, and there is no companion. Enable one - add a payment provider, keep user API keys (drop --no-ai-byok), or add the companion (--companion).")}function Er(e){return br.some(n=>e[n]===!0)&&(e.ai=!0),e}function Ir(e){return e.ai!==!0||(e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1),Ie(e)||(e.aiBuiltin=!1),Sr(e)||(e.aiByok=!0)),e}function Ar(e){let t=e.desktopAi;e.companion!==!0&&e.companionSource==="shared"&&delete e.companionSource;let n=$i(e,t);return delete e.desktopAi,n.kind!=="shared-source-contradiction"&&En(e),n}function En(e){return ye(e)&&(e.companionSource=W(e),e.companionName===void 0&&(e.companionName=ee(e.projectName))),e}function $i(e,t){return e.desktop!==!0?{kind:"none"}:e.ai===!0&&e.companionSource==="shared"?{kind:"shared-source-contradiction"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:e.ai===!0&&e.companionName===void 0?{kind:"daemon-materialized"}:{kind:"none"}}function Pr(e){let t={};if(e.name!==void 0){if(!Vt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.frontend!==void 0){if(!Ne.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ne.join(", ")}`);t.frontend=e.frontend}if(e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.billingScope!==void 0){if(e.org!==!0)throw new Error("--billing-scope requires --org to be enabled.");t.billingScope=e.billingScope}if(e.blog!==void 0&&(t.blog=e.blog),e.emailTracking!==void 0&&(t.emailTracking=e.emailTracking),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.desktopAuto!==void 0&&(t.desktopAutoRelease=e.desktopAuto),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),e.companionSource!==void 0){if(!$e.includes(e.companionSource))throw new Error(`Invalid companion source "${e.companionSource}". Valid values: ${$e.join(", ")}`);if(e.companion===!1)throw new Error("--companion-source requires the companion; remove --no-companion.");t.companionSource=e.companionSource,t.companion===void 0&&(t.companion=!0)}if(e.companionRepoUrl!==void 0){if(e.companion===!1)throw new Error("--companion-repo-url requires the companion; remove --no-companion.");t.companionRepoUrl=ce(e.companionRepoUrl).canonicalUrl,t.companion===void 0&&(t.companion=!0)}if(e.companionLocalPath!==void 0){if(e.companion===!1)throw new Error("--companion-local-path requires the companion; remove --no-companion.");let n=e.companionLocalPath.trim();n!==""&&(t.companionLocalPath=n,t.companion===void 0&&(t.companion=!0))}if(t.companionSource==="vendored"&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path apply to a shared companion; remove them or use --companion-source shared.");if(e.mcpServer!==void 0&&(t.mcpServer=e.mcpServer),e.aiBuiltin!==void 0){if(e.aiBuiltin===!0&&e.payment==="none")throw new Error("--ai-builtin requires a payment provider (got --payment none). Built-in AI bills from user credits.");t.aiBuiltin=e.aiBuiltin}if(e.aiByok!==void 0&&(t.aiByok=e.aiByok),bn(t),e.desktop===!0&&t.ai===!0&&(t.companionRepoUrl!==void 0||t.companionLocalPath!==void 0))throw new Error("--companion-repo-url / --companion-local-path point at a SHARED companion, but a desktop app with AI bundles its own; remove them, or turn AI off with --no-ai.");if(e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.docker!==void 0&&(t.dockerServices=kn(e.docker,Ze,"docker service")),e.aiTools!==void 0&&(t.aiTools=kn(e.aiTools,Qe,"AI tool")),e.socialProviders!==void 0&&(t.socialProviders=kn(e.socialProviders,tt,"social provider")),e.currency!==void 0){if(!me.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${me.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!fe.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${fe.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ge.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ge.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!he.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${he.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var pe={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,billingScope:"user",blog:!0,emailTracking:!0,docs:!1,desktop:!1,desktopAutoRelease:!1,ai:!1,companion:!1,mcpServer:!1,aiBuiltin:!0,aiByok:!0,revenueSharing:!1,credits:!0,dockerServices:["postgres","redis","inngest"],aiTools:[],socialProviders:[],defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"};function Rr(e){let t=e.projectName??pe.projectName,n=e.projectDir??`./${t}`,r=e.appName??nt(t),o=e.deploymentTarget??pe.deploymentTarget,i=ie[o]?.edgeRuntime??!1,a=e.databaseProvider??(i?"neon":pe.databaseProvider),s=e.cacheProvider??(i?"upstash":pe.cacheProvider),u=e.emailProvider??(i?"resend":pe.emailProvider),g=e.dockerServices??(i?pe.dockerServices.filter(m=>m!=="postgres"&&m!=="redis"):pe.dockerServices),l={...pe,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:o,databaseProvider:a,cacheProvider:s,emailProvider:u,dockerServices:g};l.paymentProvider==="none"&&(l.credits=!1),l.multiTenancy||(l.billingScope="user"),l.ai||(l.aiBuiltin=pe.aiBuiltin,l.aiByok=pe.aiByok),l.paymentProvider==="none"&&(l.aiBuiltin=!1),l.desktop&&l.ai&&(l.companionSource=W(l)),ye(l)&&l.companionName===void 0&&(l.companionName=ee(l.projectName)),l.companion&&(l.companionSource===void 0&&(l.companionSource=se(l)),l.companionSource==="vendored"?l.companionName===void 0&&(l.companionName=ee(l.projectName)):(l.companionRepoUrl===void 0&&(l.companionRepoUrl=Le),l.companionLocalPath===void 0&&(l.companionLocalPath=""))),Sn(l);for(let m of vt){if(l.deploymentTarget!==m.target)continue;let w=l.databaseProvider===m.provider?"database":"cache";if(l.databaseProvider===m.provider||l.cacheProvider===m.provider)throw new Error(`Incompatible: --deploy ${m.target} + --${w} ${m.provider}. ${m.reason}`)}for(let m of kt)if(l.architecture===m.architecture&&l.deploymentTarget===m.target)throw new Error(`Incompatible: --architecture ${m.architecture} + --deploy ${m.target}. ${m.reason}`);return l}function kn(e,t,n){if(e.trim()==="")return[];let r=e.split(",").map(i=>i.trim()).filter(Boolean),o=r.filter(i=>!t.includes(i));if(o.length>0)throw new Error(`Invalid ${n}(s): ${o.join(", ")}. Valid values: ${t.join(", ")}`);return r}function S(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function In(e){let t=[];e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0}));for(let n of e.socialProviders){let r=ue[n];for(let o of r.envVars)t.push({key:o.name,message:`${o.name} (${r.label}, optional):`,secret:o.secret})}return e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function xr(e,t){let n=!1;e&&bn(e),f.log.info(h.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let c=await f.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Vt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),o=e?.appName??await(async()=>{n=!0;let c=await f.text({message:"App name:",initialValue:nt(r),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),i=e?.projectDir??await(async()=>{n=!0;let c=await f.text({message:"Project location:",initialValue:`./${r}`});return S(c),c==="."?process.cwd():c})(),a=e?.frontend??await(async()=>{n=!0;let c=Object.keys(ht),d=await f.select({message:"Frontend framework:",options:c.map(b=>({value:b,label:ht[b].label,hint:ht[b].hint}))});return S(d),d})();f.log.info(h.bold("Infrastructure"));let s=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let c=await f.select({message:"Deployment target:",options:fe.map(d=>({value:d,label:ie[d].label,hint:ie[d].hint}))});S(c),s=c}let u=e?.architecture?kt.find(c=>c.architecture===e.architecture&&c.target===s):void 0;if(u)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);let g=new Set(kt.filter(c=>c.target===s).map(c=>c.architecture)),l=Ye.filter(c=>!g.has(c)),m=e?.architecture??await(async()=>{if(l.length===1){let d=l[0];return f.log.info(`Auto-selected ${yt[d].label} architecture (only compatible option for ${ie[s].label}).`),d}n=!0;let c=await f.select({message:"Architecture:",options:l.map(d=>({value:d,label:yt[d].label,hint:yt[d].hint}))});return S(c),c})(),w=e?.databaseProvider??await(async()=>{n=!0;let c=ge.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${Y[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Database provider:",options:c.map(b=>({value:b,label:Y[b].label,hint:Y[b].hint}))});return S(d),d})(),v=e?.cacheProvider??await(async()=>{n=!0;let c=he.filter(b=>!vt.some(K=>K.target===s&&K.provider===b));if(c.length===1){let b=c[0];return f.log.info(`Auto-selected ${ae[b].label} (only compatible option for ${ie[s].label}).`),b}let d=await f.select({message:"Cache provider:",options:c.map(b=>({value:b,label:ae[b].label,hint:ae[b].hint}))});return S(d),d})();if(ie[s]?.edgeRuntime){let c=mr.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);f.note(c,"Unavailable on edge runtime")}f.log.info(h.bold("Features"));let R=e?.paymentProvider??await(async()=>{n=!0;let c=await f.select({message:"Payment provider:",options:We.map(d=>({value:d,label:$t[d].label,hint:$t[d].hint}))});return S(c),c})(),q=e?.defaultCurrency??await(async()=>{if(R==="none")return"USD";n=!0;let c=await f.select({message:"Default currency:",options:me.map(d=>({value:d,label:d,hint:De[d].name}))});return S(c),c})(),be=e?.emailProvider??await(async()=>{n=!0;let c=await f.select({message:"Email provider:",options:Xe.map(d=>({value:d,label:Lt[d].label,hint:Lt[d].hint}))});return S(c),c})(),Q=e?.multiTenancy??await(async()=>{n=!0;let c=await f.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),Se=Q?e?.billingScope??"user":"user";if(Q&&e?.billingScope===void 0){n=!0;let c=await f.select({message:"Billing scope:",options:et.map(d=>({value:d,label:Ut[d].label,hint:Ut[d].hint}))});S(c),Se=c}let Je=e?.blog??await(async()=>{n=!0;let c=await f.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),Ee=e?.emailTracking??await(async()=>{n=!0;let c=await f.confirm({message:"Enable email analytics? (open/click tracking + admin analytics page)",initialValue:!0});return S(c),c})(),E=e?.docs??await(async()=>{n=!0;let c=await f.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),$=t?.desktopAllowed!==!1,L=e?.desktop??($?await(async()=>{n=!0;let c=await f.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack and bundles its own companion daemon.",initialValue:!1});return S(c),c})():(f.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),Oe=L?e?.desktopAutoRelease??await(async()=>{n=!0;let c=await f.select({message:"Desktop release trigger:",options:[{value:!1,label:"Manual only",hint:"run from the Actions tab (saves CI minutes)"},{value:!0,label:"Automatic",hint:"release on every CI success on main"}],initialValue:!1});return S(c),c})():!1,_=e?.ai??await(async()=>{n=!0;let c=await f.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion + MCP server)",initialValue:!1});return S(c),c})(),k=_?e?.companion??await(async()=>{n=!0;let c=await f.confirm({message:"Add the companion daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex / OpenCode subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return S(c),c})():!1,B=L&&_,oe=B?W({desktop:L,ai:_,companion:k,companionSource:e?.companionSource,companionName:e?.companionName}):k?e?.companionSource??await(async()=>{n=!0;let c=await f.select({message:"Companion source:",options:[{value:"shared",label:"Shared companion",hint:"point at an existing companion repo (OpenCompanion by default) - nothing to publish or maintain"},{value:"vendored",label:"Vendored companion",hint:"own a branded daemon: source in this repo, published to your own GitHub repo"}],initialValue:"shared"});return S(c),c})():void 0;B&&f.log.info(h.dim("Companion source: your desktop app bundles its own daemon, so it is vendored into this repo. Nothing to publish - it ships inside the app."));let dn=oe!=="shared"?void 0:e?.companionRepoUrl??await(async()=>{n=!0;let c=await f.text({message:"Companion repo URL (GitHub):",initialValue:Le,validate:d=>{if(!d?.trim())return"A companion repo URL is required for a shared companion.";try{ce(d)}catch(b){return T(b)}}});return S(c),ce(c).canonicalUrl})(),ar=oe!=="shared"?void 0:e?.companionLocalPath??await(async()=>{n=!0;let c=await f.text({message:"Path to your local checkout of this companion (leave empty otherwise):",placeholder:"only if you develop the companion alongside this project",defaultValue:""});return S(c),c.trim()})(),Ot=oe!=="vendored"?void 0:e?.companionName??await(async()=>{n=!0;let c=await f.text({message:B&&!k?"Companion name (your app's bundled daemon - names its binary, service and data folder):":"Companion name (what your users install):",initialValue:ee(r),validate:d=>{if(!d?.trim())return"Companion name is required."}});return S(c),c})(),sr=_?e?.mcpServer??await(async()=>{n=!0;let c=await f.confirm({message:"Add the outward MCP server? Lets external agents (Claude Code, Codex, Hermes, OpenClaw) control the app on a user's behalf over an authenticated MCP endpoint.",initialValue:!1});return S(c),c})():!1,un=R==="none"?!1:_?e?.aiBuiltin??await(async()=>{n=!0;let c=await f.confirm({message:"Built-in AI? (models under your app's name via OpenRouter, billed from user credits)",initialValue:!0});return S(c),c})():!0,mn=_?e?.aiByok??await(async()=>{n=!0;let c=await f.confirm({message:"Allow users to bring their own API keys? (their runs never use credits)",initialValue:!0});return S(c),c})():!0;Sn({ai:_,aiBuiltin:un,aiByok:mn,companion:k,desktop:L,paymentProvider:R});let cr=e?.revenueSharing??await(async()=>{n=!0;let c=await f.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),pr=R==="none"?!1:e?.credits??await(async()=>{n=!0;let c=await f.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),Ct=e?.socialProviders??await(async()=>{n=!0;let c=tt.map(b=>({value:b,label:ue[b].label,hint:`requires ${ue[b].envVars.map(K=>K.name).join(" / ")}`})),d=await f.multiselect({message:"Which social login providers should the sign-in screen show?",options:c,initialValues:[],required:!1});return S(d),d})();f.log.info(h.bold("Tooling"));let fn=e?.dockerServices??await(async()=>{n=!0;let c=[...Ze].filter(H=>H!=="mailpit");be==="smtp"&&c.push("mailpit");let d=c.map(H=>({value:H,label:qe[H].label,hint:qe[H].hint})),b=d.map(H=>H.value).filter(H=>!(H==="postgres"&&(w==="neon"||w==="supabase")||H==="redis"&&v==="upstash")),K=await f.multiselect({message:"Which services should we set up in Docker for you?",options:d,initialValues:b,required:!1});return S(K),K})(),gn=e?.aiTools??await(async()=>{n=!0;let c=Qe.map(b=>({value:b,label:wt[b].label})),d=await f.multiselect({message:"Which AI coding tools do you use?",options:c,initialValues:[],required:!1});return S(d),d})(),hn=e?.demo,Dt=In({databaseProvider:w,cacheProvider:v,paymentProvider:R,emailProvider:be,socialProviders:Ct,demo:hn}),gt={};if(Dt.length>0&&n){f.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Dt)if(n=!0,c.secret){let d=await f.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}else{let d=await f.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(gt[c.key]=d.trim())}}if(n){let c=[` Name: ${h.cyan(r)}`,` App name: ${h.cyan(o)}`,` Location: ${h.cyan(i)}`,` Frontend: ${h.cyan(ht[a].label)}`,` Architecture: ${h.cyan(yt[m].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${h.cyan(ie[s]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Y[w].label)}`,` Cache: ${h.cyan(ae[v].label)}`,fn.length>0?` Docker: ${h.cyan(fn.map(Ce=>qe[Ce].label).join(", "))}`:` Docker: ${h.dim("none")}`].filter(Boolean).join(`
|
|
5
|
+
`),b=[R!=="none"?` Payment: ${h.cyan($t[R].label)} (${q})`:` Payment: ${h.dim("none")}`,` Credits: ${pr?h.cyan("Yes"):h.dim("No")}`,` AI features: ${_?h.cyan("Yes"):h.dim("No")}`,..._?[` AI sources: ${h.cyan([un?"Built-in (credits)":null,mn?"User keys":null].filter(Boolean).join(" + ")||"none")}`,` Companion: ${k?h.cyan("Yes"):h.dim("No")}`,...k?[` Comp. source: ${h.cyan(oe==="shared"?"Shared":"Vendored")}`,oe==="shared"?` Comp. repo: ${h.cyan(dn??"")}`:` Comp. name: ${h.cyan(Ot??"")}`]:[],` MCP server: ${sr?h.cyan("Yes"):h.dim("No")}`]:[],` Email: ${h.cyan(Lt[be].label)}`,` Email stats: ${Ee?h.cyan("Yes"):h.dim("No")}`,` Multi-tenancy: ${Q?h.cyan("Yes")+` (billing: ${Ut[Se].label})`:h.dim("No")}`,` Blog: ${Je?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${E?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` Releases: ${h.cyan(Oe?"Automatic on CI":"Manual only")}`]:[],...B&&!k?[` Desktop AI: ${h.cyan("Yes")} (bundles ${Ot??""})`]:[],` Rev. sharing: ${cr?h.cyan("Yes"):h.dim("No")}`,Ct.length>0?` Social login: ${h.cyan(Ct.map(Ce=>ue[Ce].label).join(", "))}`:` Social login: ${h.dim("none")}`,gn.length>0?` AI tools: ${h.cyan(gn.map(Ce=>wt[Ce].label).join(", "))}`:` AI tools: ${h.dim("none")}`].join(`
|
|
6
|
+
`),K=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),b];if(Dt.length>0){let Ce=Dt.map(lr=>{let _i=gt[lr.key]?h.green("provided"):h.dim("skipped");return` ${lr.key}: ${_i}`}).join(`
|
|
7
|
+
`);K.push("",h.bold("Credentials"),Ce)}f.note(K.join(`
|
|
8
|
+
`),"Summary");let H=await f.confirm({message:"Proceed with these settings?"});(f.isCancel(H)||!H)&&(f.cancel("Setup cancelled."),process.exit(0))}return{projectName:r,appName:o,projectDir:i,frontend:a,architecture:m,deploymentTarget:s,databaseProvider:w,cacheProvider:v,paymentProvider:R,emailProvider:be,multiTenancy:Q,billingScope:Se,blog:Je,emailTracking:Ee,docs:E,desktop:L,desktopAutoRelease:Oe,ai:_,companion:k,...Ot!==void 0?{companionName:Ot}:{},...oe!==void 0?{companionSource:oe}:{},...dn!==void 0?{companionRepoUrl:dn}:{},...ar!==void 0?{companionLocalPath:ar}:{},mcpServer:sr,aiBuiltin:un,aiByok:mn,revenueSharing:cr,credits:pr,dockerServices:fn,aiTools:gn,socialProviders:Ct,defaultCurrency:q,...Object.keys(gt).length>0?{credentials:gt}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...hn!==void 0?{demo:hn}:{}}}import{createReadStream as Lr,existsSync as Ji}from"fs";import{mkdir as qi}from"fs/promises";import{join as Yi}from"path";import{Readable as Wi}from"stream";import{pipeline as On}from"stream/promises";import{extract as Xi}from"tar";import{join as Ue}from"path";import{homedir as Li}from"os";var bt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",z=".generatesaas",Ae=Ue(z,"manifest.json"),Tr=Ue(z,"hashes.json"),Kt=Ue(z,"template-hashes.json"),Ht=Ue(z,"template"),_r=Ue(z,"staging"),Or=Ue(z,"staging.json"),we=Ue(Li(),".generatesaas");var V=class extends Error{constructor(n,r,o){super(r);this.status=n;this.body=o}status;body;name="ApiError"};function ve(e){return{apiKey:e,baseUrl:bt}}async function Pe(e,t,n){let r=`${e.baseUrl}${t}`,o=await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.0.1"}});if(!o.ok){let i,a;try{a=await o.json(),i=a.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new V(o.status,i,a)}return o}import{existsSync as Ui,readFileSync as ji,writeFileSync as Mi,mkdirSync as Vi}from"fs";import{dirname as Fi}from"path";import*as Re from"@clack/prompts";function St(){if(!Ui(we))return null;try{let e=JSON.parse(ji(we,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&Re.log.warning(`Found old GitHub token in ${we}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function je(e){Vi(Fi(we),{recursive:!0}),Mi(we,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function rt(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let n=St();if(n)return n;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return Et()}async function Et(){let e=await Re.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return Re.isCancel(e)&&(Re.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Bi}from"fs/promises";async function xe(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Bi(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await Pe(e,"/versions")).json()}async function An(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await Pe(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(n){if(n instanceof V&&n.status===404)return null;throw n}}async function Cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await Pe(e,`/skill/${encodeURIComponent(t)}`)).json()}function zt(e){if(!(e instanceof V)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}function Dr(e){return{frontend:e.frontend,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,credits:e.credits,revenueSharing:e.revenueSharing,socialProviders:e.socialProviders,aiTools:e.aiTools,currency:e.defaultCurrency}}async function Pn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await Pe(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Nr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await Pe(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function Rn(e,t){let n=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Verification service returned ${n.status}`);return await n.json()}async function $r(e,t,n){let r=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)});if(!r.ok){let o=await r.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${r.status}`)}return await r.json()}var xn=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),Tn=new Set(["pnpm-lock.yaml"]);function ot(e){if(_n(e))return!0;for(let t of e.split("/"))if(Tn.has(t))return!0;return!1}var Gi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","README.md","TODO.md","OVERVIEW.md"]),Ki=["scripts/docs-lint.ts"],Hi=["scripts/companion-export/"],zi=["docs/superpowers","packages/cli","packages/cli-api","docs/opencompanion","infra/docker-compose.yml",".claude/commands",".claude/skills/web-next-port",".claude/skills/web-next-port-workspace",".claude/settings.local.json",".claude/worktrees"];function _n(e){let t=e.split("/");for(let n of t)if(xn.has(n))return!0;if(Ki.includes(e))return!1;for(let n of Hi)if(e.startsWith(n)||`${e}/`===n)return!1;if(Gi.has(t[0]))return!0;for(let n of zi)if(e===n||e.startsWith(n+"/"))return!0;return!1}async function Jt(e,t,n){await qi(n,{recursive:!0});let r=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(r){let s=Yi(r,`v${t}.tar.gz`);if(!Ji(s))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${s} does not exist.`);await On(Lr(s),Cn(n));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await On(Lr(o),Cn(n));return}let i=await Pe(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let a=Wi.fromWeb(i.body);await On(a,Cn(n))}function Cn(e){return Xi({cwd:e,strip:1,filter:t=>{let n=t.replace(/^[^/]+\//,"");return n?!_n(n):!0},sync:!1})}import{readdir as sa,readFile as At,rm as Nn,writeFile as Pt}from"fs/promises";import{join as ke}from"path";import{readFile as It,rm as Ur}from"fs/promises";import{join as Te}from"path";import{mkdir as Zi,readdir as Qi,rm as ea,rmdir as ta,writeFile as na}from"fs/promises";import{dirname as qt,join as ra,relative as oa,sep as ia}from"path";function Me(e){return e.split(ia).join("/")}async function Yt(e){await Zi(e,{recursive:!0})}async function p(e,t){await Yt(qt(e)),await na(e,t,"utf-8")}async function Dn(e,t){await ea(e,{force:!0});let n=qt(e);for(;n!==t&&n!==qt(n);){try{await ta(n)}catch{return}n=qt(n)}}async function Ve(e,t,n){let r=[],o=await Qi(e,{withFileTypes:!0});for(let i of o){let a=ra(e,i.name),s=Me(oa(t,a));n(s)||(i.isDirectory()?r.push(...await Ve(a,t,n)):i.isFile()&&r.push(a))}return r}function aa(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function C(e,t,n="ai",r="stripDesktopAi"){let o=aa(n);if(e.match(o)===null)throw new Error(`${r}: expected gsaas ${n} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${n}-start`)||i.includes(`gsaas:${n}-end`))throw new Error(`${r}: an unbalanced gsaas ${n} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`)}async function I(e,t,n,r,o){let i=await It(e,"utf-8"),a=i.indexOf(t);if(a===-1)throw new Error(`${o}: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,a+t.length)!==-1)throw new Error(`${o}: the ${r} seam appears more than once (boilerplate drift).`);await p(e,i.slice(0,a)+n+i.slice(a+t.length))}async function Wt(e,t,n,r){let o=/\n([\t ]+)"/.exec(await It(e,"utf-8"))?.[1];if(o!==n){let i=a=>a===" "?"tab":`${a.length}-space`;throw new Error(`${r}: expected ${e} to be ${i(n)}-indented, but it is ${o===void 0?"not indented":i(o)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await p(e,`${JSON.stringify(t,null,n)}
|
|
13
|
+
`)}function Xt(e,t,n,r){if(!(t in e))throw new Error(`${r}: expected ${n} (boilerplate drift).`);delete e[t]}function it(e){return e.frontend==="nextjs"?"next":"nuxt"}async function jr(e,t,n,r,o,i){let a=Te(e,"docs",t);await Ur(Te(a,`${n}.mdx`)),await I(Te(a,"meta.json"),` "${n}",
|
|
14
|
+
`,"",`${t} meta.json ${n} nav entry`,o),await Mr(a,t,r,o),i!==void 0&&await Vr(a,t,i,o)}async function Mr(e,t,n,r){let o=Te(e,"ai.mdx"),a=(await It(o,"utf-8")).split(`
|
|
15
15
|
`).find(s=>s.includes(`href="${n}"`));if(a===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${n} (boilerplate drift).`);await I(o,`${a}
|
|
16
|
-
`,"",`${t} ai.mdx ${n} card`,r)}async function
|
|
16
|
+
`,"",`${t} ai.mdx ${n} card`,r)}async function Vr(e,t,n,r){let o=Te(e,"ai.mdx"),i=`| **${n}** |`,s=(await It(o,"utf-8")).split(`
|
|
17
17
|
`).find(u=>u.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${n}" hub-table row (boilerplate drift).`);await I(o,`${s}
|
|
18
|
-
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function
|
|
19
|
-
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await
|
|
20
|
-
`,n=await It(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),o=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await p(e,r)}var
|
|
21
|
-
`))}}var
|
|
22
|
-
`)}function
|
|
23
|
-
- **Payments:** ${
|
|
24
|
-
- \`apps/companion\` - the source of **${e.companionName??
|
|
18
|
+
`,"",`${t} ai.mdx ${n} hub-table row`,r)}async function Fr(e,t,n,r,o,i){let a=Te(e,"docs",t);await Ur(Te(a,n),{recursive:!0}),await I(Te(a,"meta.json"),` "${n}",
|
|
19
|
+
`,"",`${t} meta.json ${n} nav entry`,o);for(let s of r)await Mr(a,t,s,o);i!==void 0&&await Vr(a,t,i,o)}async function Zt(e){let t=`import { config } from "@repo/config";
|
|
20
|
+
`,n=await It(e,"utf-8");if(!n.includes(t))return;let r=n.replace(t,""),o=r.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await p(e,r)}var ca=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function Gr(e){await Promise.all(ca.map(t=>Nn(ke(e,t),{recursive:!0,force:!0})))}var pa=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function Kr(e){let t="removeDesktopDemoScreen";await Nn(ke(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let n of pa){let r=ke(e,n);await Pt(r,C(await At(r,"utf-8"),n,"demo",t))}}var la="packages/config/src/blog.ts";async function Hr(e){let t=ke(e,la),n=await At(t,"utf-8"),r=Br(Br(n,"blogCategories",t),"blogAuthors",t);await Pt(t,r)}function Br(e,t,n){let r=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!r.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${n}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(r,"$1[];")}async function zr(e){let t=ke(e,"packages/i18n/translations"),n;try{n=await sa(t)}catch{return}for(let r of n){let o=ke(t,r,"web.json"),i;try{i=await At(o,"utf-8")}catch{continue}let a=JSON.parse(i);!a.blog||a.blog.categories===void 0||(a.blog.categories={},await Pt(o,JSON.stringify(a,null," ")+`
|
|
21
|
+
`))}}var da="packages/config/src/ai/tasks.ts";async function Jr(e){let t=ke(e,da),n=await At(t,"utf-8"),r=n.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(r===n)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);await Pt(t,r)}async function qr(e,t){t.includes("claude-code")||await Nn(ke(e,".claude"),{recursive:!0,force:!0})}async function Yr(e,t){let n=ke(e,".claude","settings.json"),r;try{r=await At(n,"utf8")}catch{return}let o=JSON.parse(r);delete o.alwaysThinkingEnabled,delete o.enableAllProjectMcpServers,o.env&&(delete o.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(o.env).length===0&&delete o.env),o.permissions?.allow&&(o.permissions.allow=o.permissions.allow.filter(i=>ua(i,t))),await Pt(n,JSON.stringify(o,null," ")+`
|
|
22
|
+
`)}function ua(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as Wr}from"path";var ma={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},fa={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},ga={redis:"Redis",upstash:"Upstash Redis"},ha={node:"Node.js / Docker",vercel:"Vercel"},ya={stripe:"Stripe",polar:"Polar"};function wa(e){let t=e.frontend==="nuxt",n=t?"Nuxt 4":"Next.js 16",r=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",a=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",s=i?`Mounted inside \`${r}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",u=ga[e.cacheProvider],g=ha[e.deploymentTarget],l=e.paymentProvider==="none"?"":`
|
|
23
|
+
- **Payments:** ${ya[e.paymentProvider]}`,m=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",w="";e.companion&&(se(e)==="vendored"?w=`
|
|
24
|
+
- \`apps/companion\` - the source of **${e.companionName??ee(e.projectName)}**, the branded companion daemon your users install. Publish releases with \`pnpm companion:publish\`; \`generatesaas update\` flags when a re-release is due.`:e.companionLocalPath?w=`
|
|
25
25
|
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\`. A local checkout lives at \`${e.companionLocalPath}\` - edit and commit device-side behavior THERE, not in this repo (clone from the repo URL if the checkout is missing).`:w=`
|
|
26
|
-
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let v=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",
|
|
26
|
+
- **Companion daemon** - this app points at the shared companion \`${e.companionRepoUrl}\` (your users install it from that repo's releases). It cannot be modified from this repo; to customize device-side behavior, switch \`companionSource\` to \`vendored\` via \`generatesaas update\`.`);let v=t?"`$t('key')` in templates (global helper); `useI18n()` from `vue-i18n` in `<script setup>` for `locale`/`setLocale`/`t()`.":"`useTranslations()` from `next-intl` in components; messages are loaded in `apps/web-next/i18n/request.ts`.",R=t?"**Navigation:** always use `localePath()` for paths (hardcoded paths break non-default locales); `await navigateTo()` in SSR.":"**Navigation:** `next/link` for links; `redirect()` from `next/navigation` for programmatic redirects in Server Components.";return`# AGENTS.md
|
|
27
27
|
|
|
28
28
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
29
29
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -51,10 +51,10 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
51
51
|
|
|
52
52
|
- **Frontend:** ${n} ${a}
|
|
53
53
|
- **API:** Hono, RPC-typed. ${s}
|
|
54
|
-
- **Database:** Drizzle ORM + ${
|
|
54
|
+
- **Database:** Drizzle ORM + ${ma[e.databaseProvider]}
|
|
55
55
|
- **Cache + jobs:** ${u} + Inngest
|
|
56
56
|
- **Auth:** Better Auth${l}
|
|
57
|
-
- **Email:** ${
|
|
57
|
+
- **Email:** ${fa[e.emailProvider]}
|
|
58
58
|
- **Deploy:** ${g}
|
|
59
59
|
|
|
60
60
|
## Where things live (extend these - don't reinvent)
|
|
@@ -84,7 +84,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
84
84
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
85
85
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
86
86
|
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${v} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
87
|
-
- ${
|
|
87
|
+
- ${R}
|
|
88
88
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
89
89
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
90
90
|
|
|
@@ -95,8 +95,8 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
95
95
|
## This project
|
|
96
96
|
|
|
97
97
|
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
98
|
-
`}async function
|
|
99
|
-
`)}import{join as
|
|
98
|
+
`}async function Xr(e){await p(Wr(e.projectDir,"AGENTS.md"),wa(e)),await p(Wr(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
99
|
+
`)}import{join as va}from"path";var ka={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ba(e){let t=e.appName.trim()||e.projectName,n=e.frontend==="nuxt",r=n?"Nuxt 4":"Next.js 16",o=n?"apps/web-nuxt":"apps/web-next",i=ka[e.databaseProvider],a=jt(e),s=e.architecture==="fullstack"?`${r} app at \`${o}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${r} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,u=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
100
100
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
101
101
|
- API: http://localhost:3010
|
|
102
102
|
- Inngest dev server: http://127.0.0.1:8288`,g=a?`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
@@ -159,18 +159,18 @@ pnpm dlx generatesaas eject
|
|
|
159
159
|
## Updates
|
|
160
160
|
|
|
161
161
|
${m}
|
|
162
|
-
`}async function
|
|
163
|
-
`)}async function
|
|
162
|
+
`}async function Zr(e){await p(va(e.projectDir,"README.md"),ba(e))}import{access as Ea,readFile as Ia}from"fs/promises";import{join as at}from"path";import{join as Sa}from"path";function $n(e,t){let n=Mt(e,"companion"),r=t?new URL(t).hostname.split(".").reverse().join("."):"com",o=n.toUpperCase().replace(/-/g,"_");return{name:e,binary:n,scope:`@${n}`,serviceLabel:`${r}.${n}`,appDirName:n,envPrefix:/^[0-9]/.test(o)?`_${o}`:o,docsUrl:"",repoUrl:"",installBase:""}}async function Qr(e){if(!ye(e)||e.demo||W(e)==="shared")return;if(!e.companionName)throw new Error("generateCompanionBrand: this project ships a companion daemon but options.companionName is missing.");let t=$n(e.companionName,e.baseUrl);await p(Sa(e.projectDir,"apps/companion/brand.json"),JSON.stringify(t,null,2)+`
|
|
163
|
+
`)}async function Aa(e,t,n){let r=at(e,"apps/electron/dev-app-update.yml");try{await Ea(r)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${r} is missing (boilerplate drift).`)}await p(r,`provider: generic
|
|
164
164
|
url: ${t}
|
|
165
165
|
updaterCacheDirName: ${n}
|
|
166
|
-
`)}function
|
|
167
|
-
`)}async function
|
|
166
|
+
`)}function Pa(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function Ra(e,t){let n=Mt(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${n.replace(/-/g,"")}`,productName:e,protocol:n}}async function xa(e){if(!e.companion&&!ye(e))return'{ enabled: false, clientId: "companion" }';let t;if(e.demo)t=JSON.parse(await Ia(at(e.projectDir,"apps/companion/brand.json"),"utf8"));else if(W(e)==="shared"){let r=await kr(e),o=ce(e.companionRepoUrl??"").canonicalUrl;t={name:r.name,binary:r.binary,envPrefix:r.envPrefix,repoUrl:o,installBase:`${o}/releases/latest/download`}}else{if(!e.companionName)throw new Error("generateConfig: this project ships a companion daemon but options.companionName is missing.");t=$n(e.companionName,e.baseUrl)}let n={name:t.name,binary:t.binary,envPrefix:t.envPrefix,repoUrl:t.repoUrl,installBase:t.installBase};return["{",` enabled: ${e.companion},`,' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(n.name)},`,` binary: ${JSON.stringify(n.binary)},`,` envPrefix: ${JSON.stringify(n.envPrefix)},`,` repoUrl: ${JSON.stringify(n.repoUrl)},`,` installBase: ${JSON.stringify(n.installBase)}`," }"," }"].join(`
|
|
167
|
+
`)}async function eo(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=e.paymentProvider!=="none",r=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=Pa(o),a=e.demo?"false":"true",s=e.demo?`{
|
|
168
168
|
enableInDev: true,
|
|
169
169
|
chatwoot: {
|
|
170
170
|
baseUrl: "https://support.alexchelan.com",
|
|
171
171
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
172
172
|
}
|
|
173
|
-
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=
|
|
173
|
+
}`:"{}",u=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",g=Ra(t,i),l=`https://cdn.${i}/desktop`,m=await xa(e),w=`{ enabled: ${e.mcpServer} }`,v=`import type { AppConfig } from "@repo/config/types";
|
|
174
174
|
import { desktopConfig } from "./desktop.mjs";
|
|
175
175
|
import { supportConfig } from "./support.mjs";
|
|
176
176
|
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
@@ -283,7 +283,7 @@ export const config: AppConfig = {
|
|
|
283
283
|
}`:`{
|
|
284
284
|
base: "${e.defaultCurrency}",
|
|
285
285
|
list: [
|
|
286
|
-
{ symbol: "${
|
|
286
|
+
{ symbol: "${De[e.defaultCurrency].symbol}", name: "${De[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${De[e.defaultCurrency].place}", space: ${De[e.defaultCurrency].space} }
|
|
287
287
|
],
|
|
288
288
|
countryMap: {
|
|
289
289
|
default: "${e.defaultCurrency}"
|
|
@@ -374,7 +374,7 @@ export * from "./pricing";
|
|
|
374
374
|
export * from "./roles";
|
|
375
375
|
export * from "./section-tabs";
|
|
376
376
|
export * from "./tenancy";
|
|
377
|
-
`,
|
|
377
|
+
`,R=at(e.projectDir,"packages/config/src/index.ts");await p(R,v),await p(at(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
378
378
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
379
379
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
380
380
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -436,8 +436,8 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
436
436
|
// index re-exports this as config.support.
|
|
437
437
|
|
|
438
438
|
export const supportConfig = ${s};
|
|
439
|
-
`),e.desktop&&await
|
|
440
|
-
`)}async function
|
|
439
|
+
`),e.desktop&&await Aa(e.projectDir,l,`${g.protocol}-updater`)}import{join as Ta}from"path";function _a(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function Ln(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
440
|
+
`)}async function to(e){let t=Ta(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let v=`import type { PricingConfig } from "@repo/config/types";
|
|
441
441
|
|
|
442
442
|
export const pricingConfig: PricingConfig = {
|
|
443
443
|
defaultPlan: "free",
|
|
@@ -466,7 +466,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
466
466
|
credits: { enabled: false },
|
|
467
467
|
products: { enabled: false, items: [] }
|
|
468
468
|
};
|
|
469
|
-
`;await p(t,v);return}let r=e.paymentProvider,o=
|
|
469
|
+
`;await p(t,v);return}let r=e.paymentProvider,o=_a(r),i=e.credits,a=!!e.ai,s=Ln({credits:5,rateLimit:100,withCredits:i,...a&&{maxSchedules:3}}),u=Ln({credits:10,rateLimit:1e3,withCredits:i,...a&&{maxSchedules:10}}),g=Ln({credits:50,rateLimit:5e3,withCredits:i}),l=n==="USD"?"":` // !! ${n} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
470
470
|
// !! USD), but your plan prices and credit purchases are denominated in ${n}. Verify that the
|
|
471
471
|
// !! ${n} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
472
472
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
@@ -570,11 +570,11 @@ ${m},
|
|
|
570
570
|
items: []
|
|
571
571
|
}
|
|
572
572
|
};
|
|
573
|
-
`;await p(t,w)}var
|
|
574
|
-
`)}function
|
|
575
|
-
`)}async function
|
|
576
|
-
`+
|
|
577
|
-
`+
|
|
573
|
+
`;await p(t,w)}var Oa={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]};function Ca(e){let t=ue[e];return t.envVars.map((n,r)=>({key:n.name,...r===0?{comment:`# TODO: Add your ${t.label} OAuth credentials`}:{}}))}var Da={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function st(e,t){return t?e.map(n=>{let r=t[n.key];return r?{...n,defaultValue:r,comment:void 0}:n}):e}function ct(e,t){for(let n of e)n.comment&&t.push(n.comment),n.defaultValue!==void 0?t.push(`${n.key}=${n.defaultValue}`):t.push(`#${n.key}=`)}function Un(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function ro(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Na(e){let{architecture:t,deploymentTarget:n}=e;return t==="fullstack"?n==="vercel"?{frontend:"https://your-app.vercel.app",backend:"https://your-app.vercel.app"}:n==="node"?{frontend:"https://your-app.example.com",backend:"https://your-app.example.com"}:null:{frontend:"https://your-app.example.com",backend:"https://your-app.example.com/api"}}function Qt(e,t,n,r){e.push(r==="example"?`${t}=`:`${t}=${n}`)}function no(e,t){let n=t==="example"?void 0:e.credentials,{apiUrl:r,baseUrl:o}=ro(e),i=[];e.architecture==="separate"?i.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${r}`,`BASE_URL=${o}`):i.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${o}`),i.push("","# Database"),ct(st(Y[e.databaseProvider].envVars,n),i),i.push("","# Cache"),ct(st(ae[e.cacheProvider].envVars,n),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Qt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Qt(i,"CONTENT_API_KEY",Un(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Qt(i,"INNGEST_EVENT_KEY",Un(32),t),Qt(i,"INNGEST_SIGNING_KEY",Un(32),t),i.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(i.push("","# API Port (standalone backend)","API_PORT=3010"),i.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let a=Oa[e.emailProvider];if(a&&(i.push("","# Email"),ct(st(a,n),i)),e.paymentProvider!=="none"){let s=Da[e.paymentProvider];s&&(i.push("","# Payment"),ct(st(s,n),i))}if(e.socialProviders.length>0){i.push("","# Social auth");for(let s of e.socialProviders)ct(st(Ca(s),n),i)}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),ct(st([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],n),i)),i.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY="),i.push("","# AI base - provider API keys (optional)","# Enable config.ai in packages/config and set the key for your chosen provider.","# OPENROUTER_API_KEY above also works as an AI provider key.","#ANTHROPIC_API_KEY=","#OPENAI_API_KEY="),i.push(""),i.join(`
|
|
574
|
+
`)}function $a(e){let{apiUrl:t}=ro(e),n=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",r=["# API Configuration",`${n}=${t}`],o=Na(e);return o&&e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${n}=${o.backend}`),r.push(""),r.join(`
|
|
575
|
+
`)}async function oo(e){let t=$a(e);await p(`${e.projectDir}/.env`,t+`
|
|
576
|
+
`+no(e,"env")),await p(`${e.projectDir}/.env.example`,t+`
|
|
577
|
+
`+no(e,"example"))}import{join as La}from"path";async function io(e){let t=[...e.dockerServices];if(Y[e.databaseProvider].managed&&(t=t.filter(i=>i!=="postgres")),ae[e.cacheProvider].managed&&(t=t.filter(i=>i!=="redis")),t.length===0)return!1;let n=[],r=[];t.includes("postgres")&&(n.push(` postgres:
|
|
578
578
|
image: postgres:18-alpine
|
|
579
579
|
ports:
|
|
580
580
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -618,8 +618,8 @@ ${n.join(`
|
|
|
618
618
|
volumes:
|
|
619
619
|
${r.join(`
|
|
620
620
|
`)}
|
|
621
|
-
`),await p(
|
|
622
|
-
`)}import{join as
|
|
621
|
+
`),await p(La(e.projectDir,"infra/docker-compose.yml"),o),!0}import{join as Ua}from"path";function ja(e){let t=[];t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}});let n=e.frontend==="nextjs"?"Next.js":"Nuxt";if(t.push({type:"node-terminal",request:"launch",name:n,command:"pnpm dev",cwd:`\${workspaceFolder}/apps/web-${e.frontend==="nextjs"?"next":"nuxt"}`,skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/electron",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Ma(e){let t=e.frontend==="nextjs"?"Next.js":"Nuxt",n=[];return e.architecture==="separate"?n.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):n.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),n}async function ao(e){let t={version:"0.2.0",configurations:ja(e),compounds:Ma(e)};await p(Ua(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
622
|
+
`)}import{join as Va}from"path";async function so(e){if(e.architecture!=="separate")return;await p(Va(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
|
|
623
623
|
import app from "@repo/api";
|
|
624
624
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
625
625
|
|
|
@@ -650,12 +650,12 @@ bootstrap().catch((error) => {
|
|
|
650
650
|
logger.error("[Backend] Fatal error", error);
|
|
651
651
|
process.exit(1);
|
|
652
652
|
});
|
|
653
|
-
`)}import{readFile as
|
|
654
|
-
export const pool = db.$client;`,
|
|
653
|
+
`)}import{readFile as Fa}from"fs/promises";import{join as Ba}from"path";var jn='import { drizzle } from "drizzle-orm/node-postgres";',Mn=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
654
|
+
export const pool = db.$client;`,Ga={postgres:{importLine:jn,instantiation:Mn},neon:{importLine:`import { neon } from "@neondatabase/serverless";
|
|
655
655
|
import { drizzle } from "drizzle-orm/neon-http";`,instantiation:`const sql = neon(parsed.data.DATABASE_URL);
|
|
656
656
|
export const db = drizzle(sql, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
657
657
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
658
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
658
|
+
export const db = drizzle(client, { schema });`}};async function co(e){let t=Ba(e.projectDir,"packages/database/src/index.ts"),n=await Fa(t,"utf-8");if(!n.includes(jn)||!n.includes(Mn))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let r=Ga[e.databaseProvider],o=n.replace(jn,r.importLine).replace(Mn,r.instantiation);await p(t,o)}import{join as en}from"path";async function po(e){switch(e.cacheProvider){case"redis":await Ka(e),await Ha(e);break;case"upstash":await za(e),await Ja(e);break}}async function Ka(e){await p(en(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
659
659
|
import { Redis } from "ioredis";
|
|
660
660
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
661
661
|
import { env } from "./env";
|
|
@@ -784,7 +784,7 @@ export async function closeRedis() {
|
|
|
784
784
|
closed = true;
|
|
785
785
|
}
|
|
786
786
|
}
|
|
787
|
-
`)}async function
|
|
787
|
+
`)}async function Ha(e){await p(en(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
788
788
|
import { redis } from "./redis";
|
|
789
789
|
|
|
790
790
|
export class MutexTimeoutError extends Error {
|
|
@@ -821,7 +821,7 @@ export async function withMutex<T>(
|
|
|
821
821
|
await mutex.release();
|
|
822
822
|
}
|
|
823
823
|
}
|
|
824
|
-
`)}async function
|
|
824
|
+
`)}async function za(e){await p(en(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
825
825
|
import type { Store } from "hono-rate-limiter";
|
|
826
826
|
import { env } from "./env";
|
|
827
827
|
|
|
@@ -939,7 +939,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
939
939
|
|
|
940
940
|
/** No persistent connection to close with Upstash REST. */
|
|
941
941
|
export async function closeRedis(): Promise<void> {}
|
|
942
|
-
`)}async function
|
|
942
|
+
`)}async function Ja(e){await p(en(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
943
943
|
import { redis } from "./redis";
|
|
944
944
|
|
|
945
945
|
export class MutexTimeoutError extends Error {
|
|
@@ -984,7 +984,7 @@ export async function withMutex<T>(
|
|
|
984
984
|
await lock.release();
|
|
985
985
|
}
|
|
986
986
|
}
|
|
987
|
-
`)}async function
|
|
987
|
+
`)}async function lo(e){await p(`${e.projectDir}/packages/runtime/src/env.ts`,qa(e))}function qa(e){return`import { z } from "zod";
|
|
988
988
|
|
|
989
989
|
const EnvSchema = z.object({
|
|
990
990
|
NODE_ENV: z.enum(["development", "production"]).default("development"),
|
|
@@ -1108,13 +1108,13 @@ export const env = (() => {
|
|
|
1108
1108
|
const parsedApiUrl = new URL(env.API_URL);
|
|
1109
1109
|
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1110
1110
|
export const apiOrigin = parsedApiUrl.origin;
|
|
1111
|
-
`}import{readFile as
|
|
1112
|
-
`)}function Rt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function pt(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function
|
|
1113
|
-
`)}var
|
|
1114
|
-
`))}}import{readFile as
|
|
1115
|
-
`);let i=
|
|
1111
|
+
`}import{readFile as Ya}from"fs/promises";import{join as le}from"path";var tn={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function lt(e){let t=await Ya(e,"utf-8");return JSON.parse(t)}async function dt(e,t){await p(e,JSON.stringify(t,null," ")+`
|
|
1112
|
+
`)}function Rt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function pt(e,t,n,r=!1){let o=r?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=n}async function uo(e){await Wa(e),await Xa(e),await Za(e),await Qa(e),e.frontend==="nextjs"?await ts(e):await es(e)}async function Wa(e){let t=le(e.projectDir,"packages/api/package.json"),n=await lt(t);Rt(n,["sharp","@types/sharp"]),await dt(t,n)}async function Xa(e){let t=le(e.projectDir,"packages/runtime/package.json"),n=await lt(t);e.cacheProvider==="upstash"&&(Rt(n,["ioredis","rate-limit-redis","redis-semaphore"]),pt(n,"@upstash/redis",tn["@upstash/redis"]),pt(n,"@upstash/lock",tn["@upstash/lock"])),await dt(t,n)}async function Za(e){let t=le(e.projectDir,"packages/database/package.json"),n=await lt(t);e.databaseProvider==="neon"?(Rt(n,["pg","@types/pg"]),pt(n,"@neondatabase/serverless",tn["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Rt(n,["pg","@types/pg"]),pt(n,"postgres",tn.postgres)),await dt(t,n)}async function Qa(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/backend/package.json"),n=await lt(t);e.deploymentTarget!=="node"&&Rt(n,["@hono/node-server"]),await dt(t,n)}async function es(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-nuxt");await Dn(le(t,"server/api/[...paths].ts"),t);let n=le(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}async function ts(e){if(e.architecture!=="separate")return;let t=le(e.projectDir,"apps/web-next");await Dn(le(t,"app/api/[[...rest]]/route.ts"),t);let n=le(t,"package.json"),r=await lt(n),o=r.dependencies?.["@repo/api"];o&&(delete r.dependencies?.["@repo/api"],pt(r,"@repo/api",o,!0)),await dt(n,r)}import{readFile as fo}from"fs/promises";import{join as go}from"path";async function ho(e){let t=go(e.projectDir,"turbo.json"),n;try{n=await fo(t,"utf-8")}catch{return}let r=JSON.parse(n),o=r.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",a=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),s=!1;if(Array.isArray(o.env)){let u=o.env.filter(g=>g!==i);u.length!==o.env.length&&(o.env=u,s=!0)}if(Array.isArray(o.outputs)){let u=o.outputs.filter(g=>!a.has(g));u.length!==o.outputs.length&&(o.outputs=u,s=!0)}s&&await p(t,JSON.stringify(r,null," ")+`
|
|
1113
|
+
`)}var ns=["base.json","node.json","next.json"],mo="GenerateSaaS ";async function yo(e){if(!e.demo)for(let t of ns){let n=go(e.projectDir,"tooling/typescript",t),r;try{r=await fo(n,"utf-8")}catch{continue}let o=JSON.parse(r);typeof o.display!="string"||!o.display.startsWith(mo)||(o.display=o.display.slice(mo.length),await p(n,JSON.stringify(o,null," ")+`
|
|
1114
|
+
`))}}import{readFile as rs,rm as os}from"fs/promises";import{existsSync as wo}from"fs";import{join as vo}from"path";async function ko(e){if(e.frontend==="nuxt")return;let t=vo(e.projectDir,"packages/i18n/package.json");if(!wo(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await rs(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),o=!1;if(n.exports)for(let a of["./module","./nuxt"])a in n.exports&&(delete n.exports[a],o=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],o=!0),o&&await p(t,JSON.stringify(n,null," ")+`
|
|
1115
|
+
`);let i=vo(e.projectDir,"packages/i18n/nuxt");if(r&&!wo(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await os(i,{recursive:!0,force:!0})}import{readFile as So,rm as is}from"fs/promises";import{join as nn}from"path";async function Eo(e){e.cacheProvider==="upstash"&&await Promise.all([bo(nn(e.projectDir,"packages/runtime/tests/setup.ts")),bo(nn(e.projectDir,"packages/mail/tests/setup.ts")),as(e.projectDir),is(nn(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function bo(e){let t;try{t=await So(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let n=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1116
1116
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1117
|
-
`);n!==t&&await p(e,n)}async function
|
|
1117
|
+
`);n!==t&&await p(e,n)}async function as(e){let t=nn(e,"packages/api/tests/setup.ts"),n;try{n=await So(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let r=n;r=r.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1118
1118
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1119
1119
|
`),r=r.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),r=r.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1120
1120
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
@@ -1135,8 +1135,8 @@ vi.mock("@upstash/lock", () => {
|
|
|
1135
1135
|
return { Lock };
|
|
1136
1136
|
});
|
|
1137
1137
|
|
|
1138
|
-
$1`),r!==n&&await p(t,r)}import{readdir as
|
|
1139
|
-
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await
|
|
1138
|
+
$1`),r!==n&&await p(t,r)}import{readdir as Hn,readFile as M,rm as U}from"fs/promises";import{join as y}from"path";import{readFile as Io,readdir as ss,rm as _e}from"fs/promises";import{join as F}from"path";async function Vn(e){if(e.mcpServer)return;let t=e.projectDir,n="stripMcpServer";await _e(F(t,"packages/api/src/routes/internal/ai/mcp.ts")),await _e(F(t,"packages/api/tests/routes/mcp.test.ts")),await _e(F(t,"packages/auth/src/mcp.ts"));let r=e.frontend==="nextjs",o=F(t,r?"apps/web-next/app/.well-known":"apps/web-nuxt/server/routes/.well-known");await _e(F(o,"oauth-authorization-server"),{recursive:!0}),await _e(F(o,"oauth-protected-resource"),{recursive:!0}),r||(await _e(F(o,"oauth-authorization-server.ts")),await _e(F(o,"oauth-protected-resource.ts"))),(await ss(o)).length===0&&await _e(o,{recursive:!0});let i=F(t,"packages/api/src/routes/internal/index.ts");await I(i,`import mcpRoutes from "./ai/mcp";
|
|
1139
|
+
`,"","internal router mcp import",n),await I(i,'\n// Outward MCP server: the protected `/mcp` JSON-RPC endpoint, gated on `config.mcpServer`. Off by\n// default, so the route is absent entirely when disabled. Its OAuth `.well-known` discovery is NOT\n// here: agents resolve those documents against the site origin, so they mount at the app root (see\n// `mcpDiscoveryRoutes` in `src/index.ts`). It is not chained into the typed router above: external\n// agents (not the typed RPC client) call it, so it needs no `AppType` inference, and gating it\n// keeps the feature truly inert when off.\nif (config.mcpServer?.enabled) {\n app.route("/", mcpRoutes);\n}\n',"","internal router mcp mount",n),await Zt(i);let a=F(t,"packages/api/src/index.ts");await I(a,`import { mcpDiscoveryRoutes } from "./routes/internal/ai/mcp";
|
|
1140
1140
|
`,"","api index mcp discovery import",n),await I(a,`
|
|
1141
1141
|
// The outward MCP server's OAuth discovery documents, mounted at the APP ROOT (not under the API
|
|
1142
1142
|
// base path): an MCP agent resolves \`/.well-known/oauth-*\` against the site origin (RFC 8414 /
|
|
@@ -1156,24 +1156,24 @@ if (config.mcpServer?.enabled) {
|
|
|
1156
1156
|
...(config.mcpServer?.enabled
|
|
1157
1157
|
? [mcp({ loginPage: \`\${config.baseUrl}\${config.routes.auth}/login\` })]
|
|
1158
1158
|
: []),
|
|
1159
|
-
`,"","auth config mcp plugin block",n);let u=F(t,"packages/auth/package.json"),g=JSON.parse(await
|
|
1160
|
-
`);let l=F(t,"packages/api/package.json"),m=JSON.parse(await
|
|
1161
|
-
`);let w=it(e);if(await
|
|
1159
|
+
`,"","auth config mcp plugin block",n);let u=F(t,"packages/auth/package.json"),g=JSON.parse(await Io(u,"utf-8"));if(!g.exports)throw new Error(`${n}: expected an exports map in packages/auth/package.json (boilerplate drift).`);Xt(g.exports,"./mcp",'the "./mcp" export in packages/auth/package.json',n),await p(u,JSON.stringify(g,null," ")+`
|
|
1160
|
+
`);let l=F(t,"packages/api/package.json"),m=JSON.parse(await Io(l,"utf-8"));if(!m.dependencies)throw new Error(`${n}: expected dependencies in packages/api/package.json (boilerplate drift).`);Xt(m.dependencies,"@mastra/mcp","@mastra/mcp in packages/api dependencies",n),Xt(m.dependencies,"@modelcontextprotocol/sdk","@modelcontextprotocol/sdk in packages/api dependencies",n),await p(l,JSON.stringify(m,null," ")+`
|
|
1161
|
+
`);let w=it(e);if(await jr(t,w,"companion-agent-mcp",`/${w}/companion-agent-mcp`,n,"MCP"),await I(F(t,`docs/${w}/configuration.mdx`),`| \`mcpServer.enabled\` | \`false\` (requires \`ai\`) | Outward MCP server URL + the **MCP** settings tab - see [external agent (MCP)](/${w}/companion-agent-mcp) |
|
|
1162
1162
|
`,"","configuration.mdx mcpServer config-table row",n),e.companion){let v=F(t,`docs/${w}/companion/index.mdx`);await I(v,`It is the user-owned counterpart to the [external agent (MCP)](/${w}/companion-agent-mcp): the MCP server lets a third-party agent reach into your app, while the companion daemon runs on the user's own hardware and reaches out to your app over authenticated HTTP.
|
|
1163
1163
|
|
|
1164
1164
|
`,"","companion index.mdx MCP counterpart paragraph",n),await I(v,` <Card title="External Agent (MCP)" href="/${w}/companion-agent-mcp" description="The other side - expose your app's capabilities to an external always-on agent over MCP." />
|
|
1165
|
-
`,"","companion index.mdx MCP card",n)}}import{readFile as
|
|
1165
|
+
`,"","companion index.mdx MCP card",n)}}import{readFile as Po,rm as O}from"fs/promises";import{join as x}from"path";import{readFile as rn}from"fs/promises";import{join as xt}from"path";async function Ao(e,t){let n=xt(e,"packages/api/src/routes/internal/index.ts");await p(n,C(await rn(n,"utf-8"),"internal router","companion",t)),await Zt(n);let r=xt(e,"packages/api/src/ai/schedule-runner.ts");await p(r,C(await rn(r,"utf-8"),"schedule-runner.ts","companion",t));for(let a of["packages/api/src/routes/internal/notifications.ts","packages/api/src/routes/internal/ai/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let s=xt(e,a);await p(s,C(await rn(s,"utf-8"),a,"companion",t))}let o=xt(e,"packages/api/src/ai/settings-store.ts");await I(o,`import { parseCompanionKey } from "../relay/companion-key";
|
|
1166
1166
|
|
|
1167
1167
|
`,"","settings-store.ts relay import",t),await I(o," * - COMPANION (when `config.companion.enabled`): a well-formed companion key\n * `<connectionId>@<deviceId>[@<modelId>]` persists as-is (the run path resolves it, and the\n * daemon handles an offline device).\n","","settings-store.ts COMPANION docstring bullet",t),await I(o,` if (config.companion?.enabled === true && parseCompanionKey(key) !== null) {
|
|
1168
1168
|
return key;
|
|
1169
1169
|
}
|
|
1170
|
-
`,"","settings-store.ts companion-key branch",t);let i=xt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,
|
|
1171
|
-
`,"","configuration.mdx companion config-table row",n)}async function
|
|
1172
|
-
`),await I(
|
|
1173
|
-
`,"","desktop index companion card",n)}async function
|
|
1174
|
-
`),o}async function
|
|
1175
|
-
`))}async function
|
|
1176
|
-
`)}await
|
|
1170
|
+
`,"","settings-store.ts companion-key branch",t);let i=xt(e,"packages/api/tests/ai/settings-store.test.ts");await p(i,C(await rn(i,"utf-8"),"settings-store.test.ts","companion",t))}var cs=["companion:export","companion:verify","companion:publish"];async function Fn(e){if(e.companion)return;let t=e.projectDir,n="stripCompanion";await O(x(t,"packages/api/src/relay"),{recursive:!0}),await O(x(t,"packages/api/src/companion"),{recursive:!0}),await O(x(t,"packages/api/src/ai/companion-model.ts")),await O(x(t,"packages/api/tests/relay"),{recursive:!0}),await O(x(t,"packages/api/tests/companion"),{recursive:!0}),await O(x(t,"packages/api/src/routes/internal/companion.ts")),await O(x(t,"packages/api/src/routes/internal/companion-transport.ts")),await O(x(t,"packages/api/tests/routes/companion.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-harness.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-poll.test.ts")),await O(x(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await O(x(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await O(x(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await O(x(t,"packages/api/tests/ai/companion-model.test.ts")),await O(x(t,"packages/api/tests/ai/companion-chat.test.ts")),await O(x(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await O(x(t,"packages/api/tests/helpers/redis-mock.ts"));let r=x(t,"packages/api/package.json"),o=JSON.parse(await Po(r,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${n}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Wt(r,o," ",n),await Ao(t,n);let i=it(e);await Fr(t,i,"companion",[`/${i}/companion`,`/${i}/companion/publishing`],n,"Companions"),await I(x(t,`docs/${i}/ai.mdx`),`Runs on a paired [companion](/${i}/companion) CLI are never metered either - the user's own subscription executes them. `,"","ai.mdx companion metering sentence",n),await I(x(t,`docs/${i}/configuration.mdx`),`| \`companion.enabled\` | \`false\` (requires \`ai\`) | Companion daemon pairing + the **Companions** settings tab - see [companion](/${i}/companion) |
|
|
1171
|
+
`,"","configuration.mdx companion config-table row",n)}async function Bn(e){if(Ft(e))return;let t=e.projectDir;await O(x(t,"apps/companion"),{recursive:!0}),await O(x(t,"scripts/companion-export"),{recursive:!0}),await ps(t)}async function Gn(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="stripDesktopCompanionDoc";await O(x(t,"docs/desktop/companion.mdx"));let r=x(t,"docs/desktop/meta.json"),o=JSON.parse(await Po(r,"utf-8"));if(!o.pages.includes("companion"))throw new Error(`${n}: expected the desktop meta.json companion nav entry, but it was missing (boilerplate drift).`);o.pages=o.pages.filter(i=>i!=="companion"),await p(r,`${JSON.stringify(o,null,2)}
|
|
1172
|
+
`),await I(x(t,"docs/desktop/index.mdx"),` <Card href="/desktop/companion" title="Companion setup" description="The companion ships inside the app and runs as a local daemon, consent-first - no separate install, and pairing is optional." />
|
|
1173
|
+
`,"","desktop index companion card",n)}async function ps(e){await Kn(e,cs)}var ls=new Set(["ci.yml","desktop-release.yml"]),ds={nextjs:["apps/web-next/app/[locale]/(marketing)/download","apps/web-next/tests/routes/download-page.test.tsx"],nuxt:["apps/web-nuxt/app/pages/download.vue","apps/web-nuxt/app/middleware/desktop.ts","apps/web-nuxt/server/api/desktop-releases.get.ts","apps/web-nuxt/tests/pages/download.test.ts"]},us=["@repo/ai","@repo/agent-core","@repo/agent-core-types","ai","@ai-sdk/react","@homebridge/node-pty-prebuilt-multiarch","@xterm/xterm","@xterm/addon-fit"],ms=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","playground:test:companion","ai:parity"];async function Ro(e){let t=y(e.projectDir,".github/workflows"),n=await Hn(t).catch(()=>[]);for(let r of n)ls.has(r)||await U(y(t,r),{recursive:!0,force:!0})}async function Kn(e,t){let n=y(e,"package.json"),r=JSON.parse(await M(n,"utf-8"));if(!r.scripts)return!1;let o=!1;for(let i of t)i in r.scripts&&(delete r.scripts[i],o=!0);return o&&await p(n,JSON.stringify(r,null," ")+`
|
|
1174
|
+
`),o}async function xo(e){let t=[...ms];jt(e)||t.push("infra","infra:stop"),await Kn(e.projectDir,t)}async function To(e){let t=y(e.projectDir,"package.json"),n=await M(t,"utf-8"),r=JSON.parse(n);!r.scripts||!("dev"in r.scripts)||(r.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await p(t,JSON.stringify(r,null," ")+`
|
|
1175
|
+
`))}async function _o(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await U(y(e.projectDir,t),{recursive:!0,force:!0})}async function Oo(e){e.docs||await U(y(e.projectDir,"apps/docs"),{recursive:!0})}async function Co(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";if(await U(y(e.projectDir,t),{recursive:!0,force:!0}),await U(y(e.projectDir,"docs/index.mdx")),!e.desktop)await U(y(e.projectDir,"docs/desktop"),{recursive:!0,force:!0});else if(!(e.desktop&&e.ai)){await U(y(e.projectDir,"docs/desktop/ai"),{recursive:!0,force:!0});let n=y(e.projectDir,"docs/desktop/meta.json"),r=JSON.parse(await M(n,"utf-8"));r.pages=r.pages.filter(o=>o!=="ai"),await p(n,`${JSON.stringify(r,null,2)}
|
|
1176
|
+
`)}await fs(e)}async function fs(e){let t=e.projectDir,n="stripUnusedDocsSilo",r=it(e),o=y(t,`docs/${r}/configuration.mdx`),i=e.desktop&&e.ai;e.desktop||(await I(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",n),await I(o,"<Callout>\n**Shipping the [desktop app](/desktop)?** It needs no entry in `TRUSTED_ORIGINS`: its main process makes every backend call - dev and packaged alike - with no `Origin` header, so the backend treats it as a native client and never CORS-checks it. `TRUSTED_ORIGINS` governs your web frontends.\n</Callout>\n\n","","configuration.mdx desktop TRUSTED_ORIGINS callout",n),await I(y(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",n)),i||(await I(o,"The desktop app's AI orchestration gates on `config.desktop.agents.enabled`, which a desktop project derives from your AI option (not a separate switch) - see [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",n),e.companion&&(await I(y(t,`docs/${r}/companion/index.mdx`),`## Set up from the desktop app
|
|
1177
1177
|
|
|
1178
1178
|
If your product also ships the [desktop app](/desktop), it runs the companion for each user as a local daemon on their own machine - consent-first, with no terminal, no pairing, and no code to copy. It attaches to any daemon already serving the machine - including the user's own always-on service - and starts its own only when none is running, so one daemon serves both the app and any paired backend. It supervises that daemon while the app is open and, on quit, stops only the one it started - never the user's service. See [Companion setup](/desktop/companion).
|
|
1179
1179
|
|
|
@@ -1182,9 +1182,9 @@ If your product also ships the [desktop app](/desktop), it runs the companion fo
|
|
|
1182
1182
|
If your product ships the [desktop app](/desktop), its **Terminal** side-panel tab is this same session, in an embedded terminal: the app spawns the daemon's \`terminal\` command in a real pty, and its folder picker **grants** the folder it picked (the durable, per-app grant above) before the session opens. See [Terminal and side panel](/desktop/ai/terminal).
|
|
1183
1183
|
|
|
1184
1184
|
`,"","companion terminal.mdx desktop-panel section",n))),e.desktop&&!e.ai&&await I(y(t,"docs/desktop/index.mdx"),` <Card href="/desktop/ai" title="AI agents" description="Turn the user's own AI subscription or API key into a workspace-scoped agent." />
|
|
1185
|
-
`,"","desktop index.mdx AI card",n)}async function
|
|
1186
|
-
`),await
|
|
1187
|
-
`)}}function
|
|
1185
|
+
`,"","desktop index.mdx AI card",n)}async function Do(e){if(e.desktop)return;await U(y(e.projectDir,"apps/electron"),{recursive:!0});let t=y(e.projectDir,"packages/i18n/translations");for(let o of await Hn(t,{withFileTypes:!0}))o.isDirectory()&&await U(y(t,o.name,"desktop.json"),{force:!0});await U(y(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of ds[e.frontend])await U(y(e.projectDir,o),{recursive:!0});await U(y(e.projectDir,"packages/utils/src/desktop-download.ts")),await U(y(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=y(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await M(n,"utf-8"));if(!r.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete r.exports["./desktop-download"],await Wt(n,r," ","stripDesktopApp")}async function No(e){Ft(e)||await U(y(e.projectDir,"packages/agent-core"),{recursive:!0})}function Tt(e,t,n,r){let o=e.indexOf(t);if(o===-1)throw new Error(`stripDesktopAi: expected to find the ${r} seam, but it was missing (boilerplate drift).`);if(e.indexOf(t,o+t.length)!==-1)throw new Error(`stripDesktopAi: the ${r} seam appears more than once (boilerplate drift).`);return e.slice(0,o)+n+e.slice(o+t.length)}async function $o(e){if(!e.desktop||e.ai)return;let t=e.projectDir,n="apps/electron";for(let a of[`${n}/src/renderer/screens/agents`,`${n}/src/renderer/screens/chat.tsx`,`${n}/src/renderer/screens/schedules.tsx`,`${n}/src/renderer/screens/settings/models.tsx`,`${n}/src/renderer/screens/settings/tasks.tsx`,`${n}/src/renderer/screens/settings/mcp.tsx`,`${n}/src/renderer/screens/settings/integrations.tsx`,`${n}/src/renderer/screens/settings/integration-add-dialog.tsx`,`${n}/src/renderer/screens/settings/integration-types.ts`,`${n}/src/renderer/screens/settings/settings-tabs.tsx`,`${n}/src/renderer/screens/settings/settings-tab-ids.ts`,`${n}/src/renderer/screens/settings/connected-cache.ts`,`${n}/src/renderer/components/section-tabs.tsx`,`${n}/src/renderer/hooks/use-ai-terminal.ts`,`${n}/src/renderer/hooks/use-xterm.ts`,`${n}/src/renderer/hooks/use-automation-lifecycle.ts`,`${n}/src/renderer/lib/companion`,`${n}/src/renderer/hooks/use-chat-controller.ts`,`${n}/src/renderer/hooks/use-local-run.ts`,`${n}/src/renderer/hooks/use-local-model-options.ts`,`${n}/src/renderer/lib/drive-chat-store.ts`,`${n}/src/renderer/lib/local-drive.ts`,`${n}/src/renderer/hooks/use-mounted.ts`,`${n}/src/renderer/lib/ai`,`${n}/src/renderer/lib/side-panel-state.ts`,`${n}/src/renderer/components/side-panel-dock.tsx`,`${n}/src/renderer/components/side-panel.tsx`,`${n}/src/renderer/config/side-panels.tsx`,`${n}/src/renderer/components/command-palette/command-palette-ai-commands.tsx`])await U(y(t,a),{recursive:!0});for(let a of[`${n}/src/preload/api-contract.ts`,`${n}/src/main/drive-transport.ts`,`${n}/src/main/companion.ts`,`${n}/src/main/companion-state.ts`,`${n}/src/main/companion-parsers.ts`,`${n}/src/main/companion-paths.ts`,`${n}/src/main/companion-drive.ts`,`${n}/src/main/companion-staging.ts`,`${n}/src/main/companion-stderr-tail.ts`,`${n}/src/main/companion-commands-pure.ts`,`${n}/src/main/companion-shared.ts`,`${n}/src/main/companion-commands.ts`,`${n}/src/main/terminal.ts`,`${n}/src/main/terminal-state.ts`])await U(y(t,a));await U(y(t,`${n}/scripts/stage-companion.mjs`));for(let a of[`${n}/tests/ai-import-boundary.test.ts`,`${n}/tests/renderer/settings-tab-ids.test.ts`,`${n}/tests/renderer/connected-cache.test.ts`,`${n}/tests/renderer/router-redirects.test.ts`,`${n}/tests/renderer/lib/side-panel-state.test.ts`,`${n}/tests/renderer/schedules-view.test.ts`,`${n}/tests/renderer/automation-status.test.ts`,`${n}/tests/renderer/consent-dialog.test.ts`,`${n}/tests/renderer/background-mode.test.ts`,`${n}/tests/renderer/connection-state.test.ts`,`${n}/tests/renderer/models-empty-view.test.ts`,`${n}/tests/renderer/models-default-reset.test.ts`,`${n}/tests/renderer/cli-catalog.test.ts`,`${n}/tests/renderer/connect-flow.test.ts`,`${n}/tests/renderer/terminal-settings-view.test.ts`,`${n}/tests/renderer/mcp-section-i18n.test.ts`,`${n}/tests/renderer/reload-on-companion-ready.test.ts`,`${n}/tests/renderer/schedule-merge.test.ts`,`${n}/tests/renderer/terminal-tools.test.ts`,`${n}/tests/renderer/terminal-hint-interpolation.test.ts`,`${n}/tests/renderer/lib/companion/consent.test.ts`,`${n}/tests/renderer/lib/companion/ensure.test.ts`,`${n}/tests/renderer/lib/companion/pairing.test.ts`,`${n}/tests/renderer/lib/companion/ensure-unpublished-brand.test.ts`,`${n}/tests/renderer/lib/companion/terminal.test.ts`,`${n}/tests/renderer/lib/companion/terminal-unpublished-brand.test.ts`,`${n}/tests/task-overrides.test.ts`,`${n}/tests/local-drive.test.ts`,`${n}/tests/drive-chat-store.test.ts`,`${n}/tests/use-local-run.test.ts`,`${n}/tests/use-local-model-options.test.ts`,`${n}/tests/renderer/chat-controller-local-seed.test.ts`,`${n}/tests/main/companion-state.test.ts`,`${n}/tests/main/companion-commands.test.ts`,`${n}/tests/main/companion-supervisor.test.ts`,`${n}/tests/main/companion-restage.test.ts`,`${n}/tests/main/companion-teardown.process.test.ts`,`${n}/tests/stage-companion.test.ts`,`${n}/tests/main/drive-preload-stream.test.ts`,`${n}/tests/main/drive-transport.test.ts`,`${n}/tests/main/ipc.test.ts`,`${n}/tests/main/terminal-cli-allowlist.test.ts`,`${n}/tests/main/terminal-manager.process.test.ts`,`${n}/tests/main/terminal-state.test.ts`,`${n}/tests/main/terminal-teardown.process.test.ts`,`${n}/tests/renderer/api-consumer-fixture.ts`])await U(y(t,a));let r=y(t,`${n}/package.json`),o=JSON.parse(await M(r,"utf-8"));for(let a of us){if(!o.dependencies||!(a in o.dependencies))throw new Error(`stripDesktopAi: expected ${a} in ${n} dependencies (boilerplate drift).`);delete o.dependencies[a]}if(!o.scripts||!("rebuild:electron"in o.scripts))throw new Error(`stripDesktopAi: expected the rebuild:electron script in ${n} package.json (boilerplate drift).`);delete o.scripts["rebuild:electron"],gs(o,"stage:companion",n),await p(r,JSON.stringify(o,null,2)+`
|
|
1186
|
+
`),await hs(t,n);let i=y(t,"packages/i18n/translations");for(let a of await Hn(i,{withFileTypes:!0})){if(!a.isDirectory())continue;let s=y(i,a.name,"desktop.json"),u=await M(s,"utf-8").catch(()=>null);if(u===null)continue;let g=JSON.parse(u),l=!1;for(let m of["agents","ai_hub","schedules","integrations"])m in g&&(delete g[m],l=!0);l&&await p(s,JSON.stringify(g,null," ")+`
|
|
1187
|
+
`)}}function gs(e,t,n){if(!e.scripts||!(t in e.scripts))throw new Error(`stripDesktopAi: expected the ${t} script in ${n} package.json (boilerplate drift).`);delete e.scripts[t];let r=`pnpm run ${t} && `;for(let o of["build:unpack","build:win","build:mac","build:linux","release"]){let i=e.scripts[o];if(i===void 0||!i.startsWith(r))throw new Error(`stripDesktopAi: expected ${o} to begin with "${r}" in ${n} package.json (boilerplate drift).`);e.scripts[o]=i.slice(r.length)}}async function hs(e,t){let n=y(e,`${t}/src/renderer/components/shell.tsx`);await p(n,C(await M(n,"utf-8"),"components/shell.tsx"));let r=y(e,`${t}/src/renderer/components/auth-gate.tsx`);await p(r,C(await M(r,"utf-8"),"components/auth-gate.tsx")),await I(r,` // The chat shell owns the ONE chat controller above the router, so a run keeps streaming as the user
|
|
1188
1188
|
// moves between the \`/chat\` screen and the side-panel chat tab. Stripped to a bare RouterProvider when
|
|
1189
1189
|
// the agents feature is off.
|
|
1190
1190
|
return (
|
|
@@ -1193,14 +1193,14 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
|
|
|
1193
1193
|
</ChatShellProvider>
|
|
1194
1194
|
)
|
|
1195
1195
|
`,` return <RouterProvider router={router} />
|
|
1196
|
-
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=y(e,`${t}/src/renderer/config/sidebar.ts`),i=
|
|
1196
|
+
`,"auth-gate chat shell wrapper","stripDesktopAi");let o=y(e,`${t}/src/renderer/config/sidebar.ts`),i=C(await M(o,"utf-8"),"config/sidebar.ts");i=Tt(i,`import {
|
|
1197
1197
|
BuildingsIcon,
|
|
1198
1198
|
ChatCircleIcon,
|
|
1199
1199
|
ClockCountdownIcon,
|
|
1200
1200
|
GearIcon,
|
|
1201
1201
|
HouseIcon,
|
|
1202
1202
|
UserCircleIcon
|
|
1203
|
-
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=y(e,`${t}/src/renderer/lib/config.ts`),s=
|
|
1203
|
+
} from '@phosphor-icons/react'`,"import { BuildingsIcon, GearIcon, HouseIcon, UserCircleIcon } from '@phosphor-icons/react'","sidebar icon imports"),await p(o,i);let a=y(e,`${t}/src/renderer/lib/config.ts`),s=C(await M(a,"utf-8"),"lib/config.ts");s=s.replace(/,(\n\} as const)/,"$1"),await p(a,s);let u=y(e,`${t}/src/renderer/lib/sidebar-flags.ts`);await p(u,C(await M(u,"utf-8"),"lib/sidebar-flags.ts"));let g=y(e,`${t}/src/renderer/router.tsx`),l=C(await M(g,"utf-8"),"router.tsx");l=Tt(l,`import { clientConfig } from '@/lib/config'
|
|
1204
1204
|
`,"","router clientConfig import"),l=Tt(l,` createRouter,
|
|
1205
1205
|
redirect
|
|
1206
1206
|
} from '@tanstack/react-router'`,` createRouter
|
|
@@ -1211,24 +1211,24 @@ import { TasksSettingsScreen } from '@/screens/settings/tasks'
|
|
|
1211
1211
|
import { McpSettingsScreen } from '@/screens/settings/mcp'
|
|
1212
1212
|
import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
1213
1213
|
`,"","router AI screen imports"),l=Tt(l,` ...(clientConfig.agentsEnabled ? aiRoutes : []),
|
|
1214
|
-
`,"","router ai route spread"),await p(g,l);let m=y(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(m,
|
|
1214
|
+
`,"","router ai route spread"),await p(g,l);let m=y(e,`${t}/src/renderer/screens/settings/index.tsx`);await p(m,C(await M(m,"utf-8"),"screens/settings/index.tsx"));let w=y(e,`${t}/src/main/ipc.ts`);await p(w,C(await M(w,"utf-8"),"src/main/ipc.ts"));let v=y(e,`${t}/src/main/index.ts`);await p(v,C(await M(v,"utf-8"),"src/main/index.ts"));let R=y(e,`${t}/src/preload/index.ts`);await p(R,C(await M(R,"utf-8"),"src/preload/index.ts"));let q=y(e,`${t}/electron-builder.mjs`);await p(q,C(await M(q,"utf-8"),"electron-builder.mjs"))}import{readFile as ys}from"fs/promises";import{join as ws}from"path";var Lo=`on:
|
|
1215
1215
|
workflow_run:
|
|
1216
1216
|
workflows: ["Tag Release"]
|
|
1217
1217
|
branches: [main]
|
|
1218
1218
|
types: [completed]
|
|
1219
|
-
workflow_dispatch:`,
|
|
1219
|
+
workflow_dispatch:`,vs=`on:
|
|
1220
1220
|
workflow_run:
|
|
1221
1221
|
workflows: ["CI"]
|
|
1222
1222
|
branches: [main]
|
|
1223
1223
|
types: [completed]
|
|
1224
|
-
workflow_dispatch:`,
|
|
1224
|
+
workflow_dispatch:`,ks=`on:
|
|
1225
1225
|
# Automatic release on CI success is disabled for this project to conserve
|
|
1226
1226
|
# GitHub Actions minutes. Re-enable by uncommenting the workflow_run trigger.
|
|
1227
1227
|
# workflow_run:
|
|
1228
1228
|
# workflows: ["CI"]
|
|
1229
1229
|
# branches: [main]
|
|
1230
1230
|
# types: [completed]
|
|
1231
|
-
workflow_dispatch:`;async function
|
|
1231
|
+
workflow_dispatch:`;async function Uo(e){if(!e.desktop)return;let t=ws(e.projectDir,".github/workflows/desktop-release.yml"),n=await ys(t,"utf8");if(!n.includes(Lo))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);let r=e.desktopAutoRelease?vs:ks;await p(t,n.replace(Lo,r))}import{join as bs}from"path";async function jo(e){let t=Ss(e);await p(bs(e.projectDir,".github/workflows/ci.yml"),t)}function Ss(e){let t=Y[e.databaseProvider].managed,n=e.cacheProvider==="upstash",r=e.frontend==="nuxt",o=t?"":` services:
|
|
1232
1232
|
postgres:
|
|
1233
1233
|
image: postgres:18-alpine
|
|
1234
1234
|
env:
|
|
@@ -1248,7 +1248,7 @@ import { IntegrationsSettingsScreen } from '@/screens/settings/integrations'
|
|
|
1248
1248
|
STRIPE_SECRET_KEY: test
|
|
1249
1249
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1250
1250
|
POLAR_ACCESS_TOKEN: test
|
|
1251
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})(),u=e.socialProviders.map(m=>
|
|
1251
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})(),u=e.socialProviders.map(m=>ue[m].envVars.map(w=>`
|
|
1252
1252
|
${w.name}: test`).join("")).join("");return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1253
1253
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1254
1254
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
@@ -1298,48 +1298,48 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1298
1298
|
run: echo "DATABASE_URL=${i}" > .env
|
|
1299
1299
|
|
|
1300
1300
|
- run: pnpm test
|
|
1301
|
-
`}import{readFile as
|
|
1302
|
-
`))}async function
|
|
1303
|
-
`))}async function
|
|
1301
|
+
`}import{readFile as Mo}from"fs/promises";import{existsSync as Es}from"fs";import{join as zn}from"path";var Vo="@repo/database";function Is(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function As(e,t){switch(e){case"fullstack":return t==="nextjs"?"web-next":"web-nuxt";case"separate":return"backend";default:{let n=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(n)}"`)}}}async function Ps(e,t,n){let r=await Mo(e,"utf-8"),o=JSON.parse(r),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(Vo)||(o.scripts={...o.scripts,[t]:`${n} && ${i}`},await p(e,JSON.stringify(o,null," ")+`
|
|
1302
|
+
`))}async function Rs(e,t){let n=Es(e)?JSON.parse(await Mo(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},r=n.buildCommand?.trim()||"pnpm build";r.includes(Vo)||(n.buildCommand=`${t} && ${r}`,await p(e,JSON.stringify(n,null," ")+`
|
|
1303
|
+
`))}async function Fo(e){let t=Is(e.demo===!0),n=As(e.architecture,e.frontend),r=zn(e.projectDir,"apps",n);switch(e.deploymentTarget){case"node":await Ps(zn(r,"package.json"),"start",t);return;case"vercel":await Rs(zn(r,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as xs}from"fs/promises";import{existsSync as Ts}from"fs";import{join as on}from"path";var _s=["stripe","polar"];async function Bo(e){let t=on(e.projectDir,"packages/payments/src"),n=e.paymentProvider,r=`// Active payment provider. To switch, change the path below to
|
|
1304
1304
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1305
1305
|
export { ops } from "./${n}/index";
|
|
1306
|
-
`;await p(
|
|
1306
|
+
`;await p(on(t,"providers/index.ts"),r),await p(on(t,"index.ts"),await Os(t,n))}async function Os(e,t){let n=on(e,"index.ts");if(!Ts(n))throw new Error(`generatePaymentBarrel: expected ${n} to exist - did packages/payments move?`);let r=await xs(n,"utf-8"),o=_s.filter(a=>a!==t);return r.split(`
|
|
1307
1307
|
`).filter(a=>!o.some(s=>a.includes(`./providers/${s}/`))).join(`
|
|
1308
|
-
`)}import{readdir as
|
|
1308
|
+
`)}import{readdir as Cs,readFile as Ds}from"fs/promises";import{join as Go}from"path";async function Ko(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,n=JSON.stringify(t).slice(1,-1),r=Go(e.projectDir,"packages/i18n/translations"),o;try{o=await Cs(r)}catch{return}for(let i of o){let a=Go(r,i,"web.json"),s;try{s=await Ds(a,"utf-8")}catch{continue}let u=s.replaceAll("GenerateSaaS",n);u!==s&&await p(a,u)}}import{readFile as Ns}from"fs/promises";import{join as Ho}from"path";var $s=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Ls=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Jo(e){let n=e.frontend==="nuxt"?Ls:$s;await zo(Ho(e.projectDir,".gitignore"),n),await zo(Ho(e.projectDir,".dockerignore"),n)}async function zo(e,t){let n;try{n=await Ns(e,"utf-8")}catch{return}let r=new Set(t),o=n.split(`
|
|
1309
1309
|
`).filter(i=>!r.has(i.trim()));o.length!==n.split(`
|
|
1310
1310
|
`).length&&await p(e,o.join(`
|
|
1311
|
-
`))}async function
|
|
1312
|
-
`),await p(
|
|
1313
|
-
`)}import{relative as
|
|
1311
|
+
`))}async function an(e){let t=e.projectDir;e.demo||(await Gr(t),await Hr(t),await zr(t),await Jr(t),e.desktop&&await Kr(t)),await qr(t,e.aiTools),await Yr(t,e.frontend),await Xr(e),await Zr(e),await eo(e),await Qr(e),e.demo||await to(e),await oo(e);let n=await io(e);return await ao(e),await so(e),await co(e),await po(e),await lo(e),await uo(e),await ho(e),await yo(e),await ko(e),await Eo(e),await Ro(e),await jo(e),await xo(e),await To(e),await _o(e),await Oo(e),await Co(e),await Do(e),await $o(e),await No(e),await Uo(e),await Vn(e),await Fn(e),await Bn(e),await Gn(e),await Fo(e),await Bo(e),await Ko(e),await Jo(e),{dockerComposeGenerated:n}}import{basename as Yo,join as Wo,relative as js}from"path";import{createHash as qo}from"crypto";import{readFile as Us}from"fs/promises";async function sn(e){let t=await Us(e);return qo("sha256").update(t).digest("hex")}function Jn(e){return qo("sha256").update(e).digest("hex")}var Ms=new Set(["data",z]);function Vs(e){let t=e.split("/");for(let n of t)if(xn.has(n)||Tn.has(n)||Ms.has(n)||n.startsWith(".env")&&!n.includes("example"))return!0;return!1}function Xo(e,t){return{projectName:e.projectName??Yo(t),appName:e.appName??e.projectName??Yo(t),projectDir:t,frontend:e.frontend==="nextjs"?"nextjs":"nuxt",architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,billingScope:e.billingScope??"user",blog:e.blog??!1,emailTracking:e.emailTracking??!0,docs:e.docs??!1,desktop:e.desktop??!1,desktopAutoRelease:e.desktopAutoRelease??!0,ai:e.ai??!1,companion:e.companion??!1,companionSource:W(e),companionRepoUrl:e.companionRepoUrl??Le,companionLocalPath:e.companionLocalPath??"",companionName:e.companionName??ee(e.projectName),mcpServer:e.mcpServer??!1,aiBuiltin:Ie(e)&&(e.aiBuiltin??!0),aiByok:e.aiByok??!0,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,dockerServices:e.dockerServices??[],aiTools:e.aiTools??[],socialProviders:e.socialProviders??[],defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Fs(e,t){return{version:e.version,initialVersion:e.version,repo:"Duzbee/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,billingScope:e.billingScope,blog:e.blog,emailTracking:e.emailTracking,docs:e.docs,desktop:e.desktop,desktopAutoRelease:e.desktopAutoRelease,ai:e.ai,companion:e.companion,mcpServer:e.mcpServer,...e.companionName?{companionName:e.companionName}:{},...e.companionSource?{companionSource:e.companionSource}:{},...e.companionRepoUrl?{companionRepoUrl:e.companionRepoUrl}:{},...e.companionLocalPath!==void 0?{companionLocalPath:e.companionLocalPath}:{},aiBuiltin:e.aiBuiltin,aiByok:e.aiByok,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,dockerServices:e.dockerServices,socialProviders:e.socialProviders,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,aiTools:e.aiTools,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Zo(e,t){let r=(await Ve(e.projectDir,e.projectDir,Vs)).sort(),o=await Promise.all(r.map(async s=>[Me(js(e.projectDir,s)),await sn(s)])),i=Object.fromEntries(o),a=Fs(e,t);await p(Wo(e.projectDir,Ae),JSON.stringify(a,null," ")+`
|
|
1312
|
+
`),await p(Wo(e.projectDir,Tr),JSON.stringify(i,null," ")+`
|
|
1313
|
+
`)}import{relative as Bs}from"path";async function Fe(e){let n=(await Ve(e,e,ot)).sort(),r=await Promise.all(n.map(async o=>[Me(Bs(e,o)),await sn(o)]));return Object.fromEntries(r)}import{copyFile as Gs,mkdir as Ks,rm as Hs}from"fs/promises";import{dirname as zs,join as Qo,relative as Js}from"path";import{existsSync as qs}from"fs";async function qn(e,t){qs(t)&&await Hs(t,{recursive:!0,force:!0});let n=await Ve(e,e,ot);for(let r of n){let o=Me(Js(e,r)),i=Qo(t,o);await Ks(zs(i),{recursive:!0}),await Gs(r,i)}}async function ei(e,t){await qn(e,Qo(t,Ht))}import{existsSync as Ys}from"fs";import{readFile as ti,readdir as Ws}from"fs/promises";import{join as de,dirname as Xs,resolve as Zs,sep as Qs}from"path";import{fileURLToPath as ec}from"url";var _t={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},wm=Object.values(_t),Yn="generatesaas-update",ni=Xs(ec(import.meta.url));function tc(){let e=de(ni,"skill","content");return Ys(e)?e:de(ni,"content")}function Wn(e){return!e||e.length===0?[]:e.map(t=>_t[t])}async function Xn(e,t,n,r){let o=Wn(r);for(let i of o){let a=de(e,i,Yn),s=de(a,"scripts"),u=de(a,"references");await Yt(s),await Yt(u),await p(de(a,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",i)),await p(de(u,".gitkeep"),"");for(let[g,l]of Object.entries(n)){let m=Zs(s,g);m.startsWith(s+Qs)&&await p(m,l)}}}async function ri(e,t){let n=tc(),r=await ti(de(n,"SKILL.md"),"utf-8"),o=de(n,"scripts"),i=await Ws(o),a={};for(let s of i)s!==".gitkeep"&&(a[s]=await ti(de(o,s),"utf-8"));await Xn(e,r,a,t)}import{execFile as nc,execFileSync as rc}from"child_process";import{access as oi,readFile as oc}from"fs/promises";import{join as Zn}from"path";import*as j from"@clack/prompts";function Ge(e){try{let t=process.platform==="win32"?"where":"which";return rc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Be(e,t,n,r=3e5){return new Promise((o,i)=>{nc(e,t,{cwd:n,timeout:r,maxBuffer:50*1024*1024},(a,s,u)=>{if(a){let g=String(s||"").trim(),m=[String(u||"").trim(),g].filter(Boolean).join(`
|
|
1314
1314
|
`);i(new Error(m?`${a.message}
|
|
1315
|
-
${m}`:a.message))}else o()})})}async function
|
|
1316
|
-
`),
|
|
1317
|
-
`),
|
|
1318
|
-
`),
|
|
1319
|
-
`),await
|
|
1320
|
-
`),
|
|
1321
|
-
`);let
|
|
1322
|
-
`)}if(g.stop("Baseline template stored."),!
|
|
1323
|
-
`),g.stop("Baseline hashes computed.")}if(await p(ft(o,
|
|
1324
|
-
`),P.log.info(`Update staged: ${
|
|
1325
|
-
|
|
1326
|
-
This is a decision only you can make, so an unattended update will not guess it. Run ${
|
|
1315
|
+
${m}`:a.message))}else o()})})}async function ii(e){if(!Ge("pnpm"))return j.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Be("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let n=t instanceof Error?t.message:String(t);return j.log.warn(`Lockfile regeneration failed: ${n}`),j.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function ai(e){if(!Ge("pnpm"))return j.log.warn("pnpm not found. Skipping dependency installation."),j.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=j.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Be("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(n){t.stop("Dependency installation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`pnpm install failed: ${r}`),j.log.warn("You can run it manually later."),!1}}async function si(e){if(!Ge("pnpm"))return!1;let t=j.spinner();t.start("Generating baseline database migration...");try{return await Be("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(n){t.stop("Baseline migration generation failed.");let r=n instanceof Error?n.message:String(n);return j.log.warn(`Could not generate baseline migration: ${r}`),j.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function ci(e){try{return await oi(Zn(e,".git")),j.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ge("git"))return j.log.warn("git not found. Skipping repository initialization."),!1;let t=j.spinner();t.start("Initializing git repository...");try{return await Be("git",["init"],e),await Be("git",["add","-A"],e),await Be("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),j.log.warn("You can run git init manually later."),!1}}async function pi(e){if(!Ge("pnpm"))return!1;try{await oi(Zn(e,".git"))}catch{return!1}try{let t=JSON.parse(await oc(Zn(e,"package.json"),"utf-8")),n=!!t.devDependencies?.["simple-git-hooks"],r=!!t["simple-git-hooks"];if(!n||!r)return!1}catch{return!1}try{return await Be("pnpm",["exec","simple-git-hooks"],e),!0}catch{return j.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as ut from"@clack/prompts";import te from"picocolors";function li(e,t){t.dockerComposeGenerated&&!t.dockerAvailable&&ut.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];if(n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),t.dockerComposeGenerated){let i=e.dockerServices.map(a=>qe[a].label).join(", ");n.push(`pnpm infra ${te.dim(`# ${i}`)}`)}if(n.push(`pnpm dev ${te.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(te.dim("Fill in remaining TODO values in .env"))),ut.note(n.join(`
|
|
1316
|
+
`),te.yellow("Start Development")),t.dockerComposeGenerated){let i=[];i.push(`App ${te.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${te.cyan("http://localhost:3010")}`),e.dockerServices.includes("mailpit")&&i.push(`Mailpit ${te.cyan("http://localhost:8025")}`),e.dockerServices.includes("inngest")&&i.push(`Inngest ${te.cyan("http://localhost:8288")}`),ut.note(i.join(`
|
|
1317
|
+
`),te.yellow("Dev Tools"))}let r=[],o=ic(e);o.length>0&&r.push(`Set in production: ${te.dim(o.join(", "))}`),r.push("pnpm db:setup # Apply the database schema"),r.push(ac(e)),ut.note(r.join(`
|
|
1318
|
+
`),te.yellow("Deployment"))}function ic(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function ac(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function mt(e){let n=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return n?[Number(n[1]),Number(n[2]),Number(n[3])]:null}function Ke(e,t){let n=mt(e),r=mt(t);if(!n||!r)return 0;for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}function cn(e,t){return e.versions.find(n=>n.version===t)?.cli}function di(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:mt(e)===null}function pn(e,t,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,e.latest);return!r||mt(r)===null?{ok:!0}:Ke(n,r)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${n}) is too old for template v${e.latest}, which needs CLI v${r} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function ui(e,t,n="2.0.1"){if(di(n))return{ok:!0};let r=cn(e,t);return!r||mt(r)===null?{ok:!0}:Ke(n,r)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${r} exactly (the CLI whose generators produced that release). Run npx generatesaas@${r} init.`}}import uc from"picocolors";var mc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function fc(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),n=[...new Uint8Array(t).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20,32)}`}function mi(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new X("--frontend <type>","frontend framework").choices([...Ne])).addOption(new X("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new X("--payment <provider>","payment provider").choices([...We])).addOption(new X("--email <provider>","email provider").choices([...Xe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").addOption(new X("--billing-scope <scope>","billing scope (requires --org)").choices([...et])).option("--blog","enable blog").option("--no-blog","disable blog").option("--email-tracking","enable email analytics (open/click tracking + admin analytics page)").option("--no-email-tracking","disable email analytics").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--desktop-auto","auto-trigger the desktop release workflow on CI success (default: manual-only)").option("--no-desktop-auto","manual-only desktop releases (workflow_dispatch)").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion + MCP server").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - a daemon your users install to run their own AI subscriptions for this app (shared repo or vendored)").option("--no-companion","exclude the backend companion feature").addOption(new X("--companion-source <source>","companion source: point at an existing shared companion repo, or vendor your own branded daemon").choices([...$e])).option("--companion-repo-url <url>","GitHub URL of the shared companion repo (with --companion-source shared; default: OpenCompanion)").option("--companion-local-path <path>","path to your local checkout of the shared companion (optional, for developing it alongside)").option("--mcp-server","include the outward MCP server (the /mcp route + Better Auth mcp() provider)").option("--no-mcp-server","exclude the outward MCP server").option("--ai-builtin","built-in AI: models under your app's name via OpenRouter, billed from credits (default)").option("--no-ai-builtin","no built-in AI").option("--ai-byok","let end-users connect their own provider API keys (default)").option("--no-ai-byok","no user-supplied API keys").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").option("--docker <services>","comma-separated: postgres,redis,inngest,mailpit").option("--ai-tools <tools>","comma-separated: claude-code,cursor,codex,gemini-cli,windsurf").option("--social-providers <providers>","comma-separated: google,github,facebook,discord,x").addOption(new X("--currency <code>","default currency for billing").choices([...me])).addOption(new X("--deploy <target>","deployment target").choices([...fe])).addOption(new X("--database <provider>","database provider").choices([...ge])).addOption(new X("--cache <provider>","cache provider").choices([...he])).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new X("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new X("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,n)=>{await gc(t?{...n,apiKey:t}:n)})}async function gc(e){let t=performance.now();dr("2.0.1");let n;try{n=Pr(e)}catch(E){A.cancel(T(E)),process.exit(1)}let r=A.spinner(),o;try{o=await rt({apiKey:e.apiKey,prompt:!e.yes})}catch(E){A.cancel(T(E)),process.exit(1)}e.demo&&Jn(o)!==mc&&(A.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=ve(o),a,s=async()=>{a=await xe(i);let E=pn(a,"init");if(!E.ok)throw new Error(E.message);return{latestVersion:a.latest,selectedVersion:a.latest,desktopAllowed:a.entitlements?.desktopAllowed??!0}};r.start("Verifying access...");let u,g,l=!0;try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch(E){if(r.stop("Access verification failed."),E instanceof V&&E.status===401){e.yes&&(A.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),A.log.warning("Invalid API key."),o=await Et(),i=ve(o),r.start("Verifying access...");try{({latestVersion:u,selectedVersion:g,desktopAllowed:l}=await s()),r.stop("Access verified."),je(o)}catch($){r.stop("Access verification failed."),A.cancel($ instanceof V&&$.status===401?"Invalid API key.":T($)),process.exit(1)}}else A.cancel(T(E)),process.exit(1)}A.log.success(`Latest version: ${u}`),n.desktop===!0&&!l&&(A.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let m;e.yes?m=Rr(l?n:{...n,desktop:!1}):m=await xr(n,{desktopAllowed:l});let w;r.start("Activating license...");try{let E=e.demo&&m.baseUrl?await fc(m.baseUrl):crypto.randomUUID(),$=()=>({frontend:m.frontend,version:g,installId:E,projectName:m.projectName,options:Dr(m)}),L;try{L=await Pn(i,$())}catch(Oe){let _=zt(Oe);if(!_?.lastAllowedVersion||!a)throw Oe;r.stop("License activation failed.");let k=ui(a,_.lastAllowedVersion);if(k.ok||(A.cancel(`${_.message} ${k.message}`),process.exit(1)),e.yes){let oe=cn(a,_.lastAllowedVersion);A.cancel(`${_.message} Re-run ${oe?`npx generatesaas@${oe} init`:"init"} without --yes to continue with v${_.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let B=await A.confirm({message:`Your update window has ended. Continue with v${_.lastAllowedVersion} (the last version your license covers)?`});(A.isCancel(B)||!B)&&(A.cancel("Setup cancelled."),process.exit(0)),g=_.lastAllowedVersion,r.start(`Activating license for v${g}...`),L=await Pn(i,$())}w={token:L.token,keyHash:Jn(o),installId:L.installId??E},r.stop("License activated.")}catch(E){r.stop("License activation failed."),A.cancel(T(E)),process.exit(1)}let v=dc(m.projectDir);if(sc(v)&&cc(v).length>0)if(e.yes)A.log.info(`Directory ${v} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let $=await A.select({message:`Directory ${v} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(A.isCancel($)||$==="cancel")&&(A.cancel("Setup cancelled."),process.exit(0)),$==="overwrite"&&pc(v,{recursive:!0,force:!0})}let R={...m,projectDir:v,version:g,...e.demo?{docs:!1}:{}};r.start("Downloading template...");try{await Jt(i,g,v),r.stop("Template downloaded.")}catch(E){r.stop("Download failed."),A.cancel(T(E)),process.exit(1)}let q;r.start("Generating project files...");try{if({dockerComposeGenerated:q}=await an(R),!e.demo){let E=await Fe(v);await p(lc(v,Kt),JSON.stringify(E,null," ")+`
|
|
1319
|
+
`),await ei(v,v)}await ri(v,R.aiTools),await Zo(R,w),r.stop("Project files generated.")}catch(E){r.stop("Generation failed."),A.cancel(T(E)),process.exit(1)}!await ii(v)&&R.demo===!0&&(A.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let Q=await ai(v);Q&&R.demo!==!0&&e.dbMigration!==!1&&await si(v),await ci(v),Q&&await pi(v);let Se=Ge("docker"),Ee=In(R).map(E=>E.key).filter(E=>!R.credentials?.[E]);li(R,{pnpmInstalled:Q,dockerComposeGenerated:q,dockerAvailable:Se,skippedCredentials:Ee}),ur(),A.log.info(uc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as tr}from"fs";import{readFile as nr}from"fs/promises";import{join as ft,resolve as Ec}from"path";import*as P from"@clack/prompts";import J from"picocolors";import{mkdtemp as hc,rm as yc}from"fs/promises";import{tmpdir as wc}from"os";import{join as vc}from"path";async function Qn(e,t,n,r){let o=await hc(vc(wc(),"generatesaas-stage-"));try{await Jt(e,t,o),await an({...n,projectDir:o}),await qn(o,r)}finally{await yc(o,{recursive:!0,force:!0})}}import{readFile as kc,rm as bc}from"fs/promises";import{join as er}from"path";var fi=er(z,"companion-release.json"),Sc=["apps/companion/","packages/companion-protocol/","packages/agent-core-types/","packages/agent-core/","scripts/companion-export/"];async function gi(e){let t;try{t=await kc(er(e,fi),"utf-8")}catch(r){if(typeof r=="object"&&r!==null&&"code"in r&&r.code==="ENOENT")return null;throw r}let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"version"in n&&typeof n.version=="string"&&n.version.length>0?{version:n.version}:null}async function hi(e){try{return await bc(er(e,fi)),!0}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return!1;throw t}}function yi(e){return e.some(t=>Sc.some(n=>t.startsWith(n)))}function vi(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,n)=>{let r=t==="auto"?"auto":void 0,o=Ec(n.cwd??process.cwd()),i=ft(o,Ae),a;try{a=JSON.parse(await nr(i,"utf-8"))}catch{P.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let s;try{s=await rt()}catch(l){P.cancel(T(l)),process.exit(1)}let u=ve(s),g=P.spinner();try{g.start("Verifying access...");let l;try{l=await xe(u)}catch(k){throw k instanceof V&&k.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):k}let m=pn(l,"update");if(!m.ok)throw new Error(m.message);g.stop("Access verified."),je(s),g.start("Fetching latest skill files...");let w=await Cr(u,l.latest);await Xn(o,w.skillMd,w.scripts,a.aiTools);let v=Wn(a.aiTools);if(g.stop("Skills updated."),P.log.success(`Skill files installed to ${J.cyan(v.length.toString())} locations.`),a.version===l.latest){P.log.info(`Already on the latest version (${a.version}).`);return}let R=JSON.stringify(a);Er(a),Ir(a),await Ic(a,Ar(a),r);let q=hr(a),be=yr(a),Q=JSON.stringify(be)!==R;if(a=be,a.licenseToken)try{let k=await Nr(u,{currentToken:a.licenseToken,newVersion:l.latest});a.licenseToken=k.token,k.licenseKeyHash&&(a.licenseKeyHash=k.licenseKeyHash),await p(i,JSON.stringify(a,null," ")+`
|
|
1320
|
+
`),Q=!1,P.log.success("License refreshed.")}catch(k){let B=zt(k);B&&(P.cancel(B.message),process.exit(1)),P.log.warn("License refresh skipped.")}Q&&await p(i,JSON.stringify(a,null," ")+`
|
|
1321
|
+
`);let Se=Xo(a,o),Je=ft(o,_r);g.start(`Staging v${l.latest} (shaped for your config)...`),await Qn(u,l.latest,Se,Je),g.stop("Template staged.");let{text:Ee,title:E}=await Pc(u,l,a.version);Ee&&P.note(Ee,E);let $=ft(o,Kt),L=ft(o,Ht),Oe=!tr(L),_=!tr($);if(Oe){if(g.start("Building baseline template (one-time migration)..."),await Qn(u,a.version,Se,L),_){let k=await Fe(L);await p($,JSON.stringify(k,null," ")+`
|
|
1322
|
+
`)}if(g.stop("Baseline template stored."),!_){let k=await xc($,L);k>0&&P.log.warn(`Rebuilt baseline differs from the original for ${k} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(_){g.start("Computing baseline template hashes...");let k=await Fe(L);await p($,JSON.stringify(k,null," ")+`
|
|
1323
|
+
`),g.stop("Baseline hashes computed.")}if(await p(ft(o,Or),JSON.stringify({currentVersion:a.version,targetVersion:l.latest,changelog:Ee,stagedAt:new Date().toISOString(),...q.length>0?{newOptions:q}:{},...r?{mode:r}:{}},null," ")+`
|
|
1324
|
+
`),P.log.info(`Update staged: ${J.cyan(a.version)} \u2192 ${J.cyan(l.latest)}`),a.aiTools&&a.aiTools.length>0){let k=a.aiTools[0],B=wt[k].label;P.log.info(`Open your project in ${J.cyan(B)} and ask: ${J.cyan("'update my GenerateSaaS project'")}`)}else P.log.info(`Ask your AI coding assistant to ${J.cyan("'update my GenerateSaaS project'")}.`);if(a.companion===!0)try{if(se(a)==="vendored"){let k=await gi(o);if(k){let B=await Rc($,Je);yi(B)&&P.log.warn(`Companion: vendored daemon changed since your published v${k.version} - run pnpm companion:publish (your users auto-update once tagged)`)}}else await hi(o)&&P.log.info("Companion: removed the stale vendored publish state (.generatesaas/companion-release.json) - this project points at a shared companion.")}catch(k){P.log.warn(`Companion re-release check skipped: ${T(k)}`)}a.desktop===!0&&tr(ft(o,"apps/tauri"))&&P.log.warn(`Desktop: the app moved to an Electron shell (${J.cyan("apps/electron")}). Your project still has the old Tauri shell (${J.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${J.cyan("/desktop/updates")}.`)}catch(l){g.stop("Failed."),P.cancel(`Update failed: ${T(l)}`),process.exit(1)}})}async function Ic(e,t,n){if(t.kind==="none")return;if(t.kind==="daemon-materialized"){P.log.info(`Desktop: your app now bundles its own companion daemon. This update adds its source to your repo (${J.cyan("apps/companion")}, branded ${J.cyan(e.companionName??"")}) and about 106MB to each packaged build. Nothing to publish - it ships inside the app.`);return}let r=Ac[t.kind];n==="auto"&&(P.cancel(`${r.message}
|
|
1325
|
+
|
|
1326
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${J.cyan("generatesaas update")} without ${J.cyan("auto")} and answer it.`),process.exit(1));let o=await P.select({message:r.message,options:r.options});P.isCancel(o)&&(P.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e),En(e)}function wi(e){e.desktop=!1,e.desktopAutoRelease=!1}var Ac={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also adds the companion daemon's source to your repo (apps/companion, ~106MB per packaged build) and makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal, no bundled daemon"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack and bundles a companion daemon. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack, the Terminal, and the bundled companion daemon (apps/companion, ~106MB per packaged build)"},{value:{apply:e=>{e.ai=!1,e.companion=!1,e.mcpServer=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion and the MCP server - they both require AI"},{value:{apply:wi},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]},"shared-source-contradiction":{message:"Your desktop app bundles a companion daemon, but your project points its web install flow at a shared companion. A bundled app needs its own daemon. How should this resolve?",options:[{value:{apply:e=>{e.companionSource="vendored"}},label:"Vendor your own companion",hint:"its source moves into your repo (apps/companion) and your web install UI switches to it - your users install yours, not the shared one"},{value:{apply:wi},label:"Drop the desktop app",hint:"your website keeps its AI surface and its shared companion exactly as they are today"}]}};async function Pc(e,t,n){let r=t.latest,o=t.versions.filter(a=>Ke(a.version,n)>0&&Ke(a.version,r)<=0).sort((a,s)=>Ke(a.version,s.version));if(o.length<=1)return{text:await An(e,r),title:`Changelog v${r}`};let i=[];for(let a of o){let s=null;try{s=await An(e,a.version)}catch{s=null}let u=a.date?` (${a.date.slice(0,10)})`:"",g=a.breaking?" [BREAKING]":"";i.push(`# v${a.version}${u}${g}
|
|
1327
1327
|
|
|
1328
1328
|
${s??"_No changelog available for this release._"}`)}return{text:i.join(`
|
|
1329
1329
|
|
|
1330
|
-
`),title:`Changelog v${n} \u2192 v${r}`}}async function
|
|
1331
|
-
`);
|
|
1332
|
-
`),
|
|
1333
|
-
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(
|
|
1330
|
+
`),title:`Changelog v${n} \u2192 v${r}`}}async function Rc(e,t){let n=JSON.parse(await nr(e,"utf-8")),r=await Fe(t),o=[];for(let[i,a]of Object.entries(r))n[i]!==a&&o.push(i);for(let i of Object.keys(n))i in r||o.push(i);return o}async function xc(e,t){let n=JSON.parse(await nr(e,"utf-8")),r=await Fe(t),o=0;for(let[i,a]of Object.entries(n))ot(i)||r[i]!==a&&o++;for(let i of Object.keys(r))i in n||o++;return o}import*as Z from"@clack/prompts";import ne from"picocolors";import{readFile as Tc}from"fs/promises";import{join as _c,resolve as Oc}from"path";function ki(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let n=Oc(t.cwd??process.cwd()),r=_c(n,Ae),o;try{o=JSON.parse(await Tc(r,"utf-8"))}catch{Z.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${ne.cyan(o.version)}`,`Frontend: ${ne.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${ne.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${ne.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${ne.cyan(o.cacheProvider)}`:null,o.aiTools&&o.aiTools.length>0?`AI tools: ${ne.cyan(o.aiTools.join(", "))}`:null].filter(Boolean).join(`
|
|
1331
|
+
`);Z.note(i,ne.bold("Project Status"));let a=Z.spinner();a.start("Checking for updates...");try{let s=await rt(),u=ve(s),l=(await xe(u)).latest;o.version===l?(a.stop("Up to date."),Z.log.success(`Already on the latest version (${ne.green(l)})`)):(a.stop("Update available."),Z.log.warning(`Update available: ${ne.yellow(o.version)} \u2192 ${ne.green(l)}`),Z.log.info(`Open this project in your AI coding agent and ask it to ${ne.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(s){a.stop("Check failed."),s instanceof V&&s.status===401?Z.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):Z.log.warning(`Could not check for updates: ${T(s)}`)}})}import{readFile as Cc}from"fs/promises";import*as N from"@clack/prompts";import D from"picocolors";function Dc(){return process.env.GENERATESAAS_API_KEY??St()}function Nc(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function $c(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Lc(e){switch(e.verdict){case"licensed":return N.log.success(`${D.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return N.log.success(`${D.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return N.log.error(`${D.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return N.log.error(`${D.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${D.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return N.log.error(`${D.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return N.log.warn(`${D.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function bi(e,t){let n=process.env.GENERATESAAS_API_URL??bt,r=Dc();e.start("Cross-referencing license records...");try{let o=r?Nc(await $r(n,r,{lkh:t.lkh,nid:t.nid,domain:t.domain})):$c(await Rn(n,{token:t.token,domain:t.domain}));return e.stop(`${D.green("Checked")} - records cross-referenced`),Lc(o)}catch(o){return e.stop(`${D.yellow("Skipped")} - ${T(o)}`),null}}function Uc(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let n=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(n)}function rr(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function Si(e){N.note([`License ID: ${D.cyan(String(e.lid??"unknown"))}`,`Version: ${D.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${rr(e.pat)}`,`Last updated: ${rr(e.uat)}`,`Expires: ${rr(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1332
|
+
`),D.yellow("License Details"))}function jc(e){let n=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(n.endsWith("/api"))return[`${n}/license`];try{if(new URL(n).pathname!=="/")return[`${n}/license`]}catch{return[`${n}/license`]}return[`${n}/api/license`,`${n}/license`]}async function Ei(e){let t=N.spinner(),n=null,r="no candidates";for(let a of jc(e)){t.start(`Checking ${a}...`);try{let s=await fetch(a);if(!s.ok){r=`${a} returned ${s.status}`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}let u=(await s.text()).trim();if(!u||u.split(".").length!==3){r=`${a} did not return a JWT`,t.stop(`${D.yellow("Not here")} - ${r}`);continue}n=u,t.stop(`${D.green("Found")} - license endpoint responded`);break}catch(s){r=`${a}: ${T(s)}`,t.stop(`${D.yellow("Unreachable")} - ${r}`)}}if(n===null){N.log.warn(`No license endpoint found (last: ${r}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let a=Ii(e);return a?await bi(t,{domain:a})??!1:!1}let o;try{o=Uc(n)}catch{return N.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let a=process.env.GENERATESAAS_API_URL??bt,s=await Rn(a,{token:n});if(s.valid)t.stop(`${D.green("Valid")} - signature verified`);else return t.stop(`${D.red("Invalid")} - ${s.reason}`),!1}catch{return t.stop(`${D.yellow("Skipped")} - could not reach verification service`),N.log.warn("Signature not verified. Displaying unverified claims:"),Si(o),!1}return Si(o),await bi(t,{token:n,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:Ii(e)})??!0}function Ii(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function Ai(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,n)=>{if(!t&&!n.file&&(N.cancel("Provide a URL or --file <path>."),process.exit(1)),n.file){let o=(await Cc(n.file,"utf-8")).split(`
|
|
1333
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#"));o.length===0&&(N.cancel("No URLs found in file."),process.exit(1));let i=0;for(let a of o)await Ei(a)&&i++,N.log.info("");N.log.success(`${i}/${o.length} sites verified.`)}else await Ei(t)||process.exit(1)})}import{existsSync as Mc,rmSync as Vc}from"fs";import*as re from"@clack/prompts";function Pi(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){Mc(we)?(Vc(we),re.log.success("API key removed.")):re.log.info("No API key configured.");return}let n=St();n?re.log.info(`Current API key: ****${n.slice(-4)}`):re.log.info("No API key configured.");let r=await Et(),o=ve(r),i=re.spinner();i.start("Verifying API key...");try{await xe(o),i.stop("API key verified."),je(r),re.log.success("API key saved.")}catch(a){i.stop("Verification failed."),a instanceof V&&a.status===401?re.cancel("Invalid API key."):re.cancel(T(a)),process.exit(1)}})}import{existsSync as ln,rmSync as Fc,readFileSync as ir,writeFileSync as Ri}from"fs";import{join as He}from"path";import*as G from"@clack/prompts";var Bc=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts"],Gc=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1334
1334
|
`,` licenseHeartbeatFunction,
|
|
1335
1335
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1336
1336
|
`,` .route("/license", licenseRoutes)
|
|
1337
|
-
`]}];function
|
|
1337
|
+
`]}];function Kc(e){return(e&&e.length>0?e.map(n=>_t[n]):Object.values(_t)).map(n=>He(n,Yn))}function or(e){return ln(e)?(Fc(e,{recursive:!0}),!0):!1}function Hc(e,t){if(!ln(e))return!1;let n=ir(e,"utf-8"),r=n;for(let o of t)r=r.replace(o,"");return r===n?!1:(Ri(e,r,"utf-8"),!0)}function zc(e){let t=He(e,".gitignore");if(!ln(t))return!1;let n=ir(t,"utf-8"),r=n.split(`
|
|
1338
1338
|
`).filter(o=>!o.includes(".generatesaas")).join(`
|
|
1339
|
-
`);return r===n?!1:(
|
|
1339
|
+
`);return r===n?!1:(Ri(t,r,"utf-8"),!0)}function xi(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),n=He(t,Ae),r;try{r=JSON.parse(ir(n,"utf-8"))}catch{G.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await G.text({message:'Type "eject" to confirm (this cannot be undone):',validate:s=>{if(s!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(G.isCancel(o)&&(G.cancel("Eject cancelled."),process.exit(0)),r.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.licenseToken}`},body:JSON.stringify({event:"eject",version:r.version,frontend:r.frontend}),signal:AbortSignal.timeout(5e3)}),G.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{G.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],a=[];for(let s of Kc(r.aiTools))or(He(t,s))&&i.push(s);for(let s of Bc)or(He(t,s))&&i.push(s);or(He(t,z))&&i.push(z+"/");for(let s of Gc){let u=He(t,s.file);Hc(u,s.removals)?a.push(s.file):ln(u)&&G.log.warn(`Could not auto-modify ${s.file} - manually remove license/heartbeat references.`)}zc(t)&&a.push(".gitignore");for(let s of i)G.log.info(`Deleted ${s}`);for(let s of a)G.log.info(`Modified ${s}`);G.log.success("Ejected successfully. This project is now fully standalone.")})}var ze=new Jc().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.0.1").addHelpText("after",`
|
|
1340
1340
|
Examples:
|
|
1341
1341
|
$ generatesaas init Interactive setup
|
|
1342
1342
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1343
1343
|
$ generatesaas status Check for updates
|
|
1344
1344
|
$ generatesaas auth Set or update API key
|
|
1345
|
-
`);
|
|
1345
|
+
`);mi(ze);vi(ze);ki(ze);Ai(ze);Pi(ze);xi(ze);ze.parseAsync().catch(e=>{Ti.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|