generatesaas 2.4.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,25 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Mp}from"commander";import*as mi from"@clack/prompts";import{existsSync as Wc,readdirSync as qc,rmSync as Xc}from"fs";import{join as Zc,resolve as Qc}from"path";import{Option as z}from"commander";import*as v from"@clack/prompts";import*as vt from"@clack/prompts";import qt from"picocolors";function Dr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";vt.intro(qt.bgYellow(qt.black(t)))}function _r(){vt.outro(qt.yellow("Happy building!"))}import*as m from"@clack/prompts";import g from"picocolors";var et={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},tt={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)"}},kt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},bt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},St={none:{label:"None",hint:"no reporting SDK is generated at all"},sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server only - no Electron SDK, so a desktop build reports nothing"}},Nr={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var be={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var G={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},re={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"}]}},Se={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"}]}},rt=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],nt=[{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)."}],hi=[{feature:"companion",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the companion holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ne(e){return hi.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var Cr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Me(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var Ee=["nextjs","nuxt"],Ue=["fullstack","separate"],Fe=["stripe","polar","none"],Ve=["smtp","ses","resend"];var $r=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ie=["node","vercel"],se=["postgres","neon","supabase"],ae=["redis","upstash"],B=["none","sentry","posthog"];function jr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Et(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Rt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Lr=["companion"];function Xt(e){if(!Lr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--companion requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function Mr(e){return Lr.some(r=>e[r]===!0)&&(e.ai=!0),e}function Ur(e){let t=yi(e,e.desktopAi);return delete e.desktopAi,t}function yi(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Fr(e){let t={};if(e.name!==void 0){if(!Rt(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(!Ee.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${Ee.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.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.companion!==void 0&&(t.companion=e.companion),Xt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ie.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ie.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!se.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${se.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!ae.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${ae.join(", ")}`);t.cacheProvider=e.cache}if(e.errorTracking!==void 0){if(!B.includes(e.errorTracking))throw new Error(`Invalid error tracking provider "${e.errorTracking}". Valid values: ${B.join(", ")}`);t.errorTracking=e.errorTracking}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var Be={projectName:"my-saas",frontend:"nextjs",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,companion:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",errorTracking:"none"};function Vr(e){let t=e.projectName??Be.projectName,r=e.projectDir??`./${t}`,n=e.appName??Et(t),o=e.deploymentTarget??Be.deploymentTarget,i=G[o]?.edgeRuntime??!1,s=e.databaseProvider??(i?"neon":Be.databaseProvider),a=e.cacheProvider??(i?"upstash":Be.cacheProvider),l=e.emailProvider??(i?"resend":Be.emailProvider),u={...Be,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:o,databaseProvider:s,cacheProvider:a,emailProvider:l};u.paymentProvider==="none"&&(u.credits=!1);for(let f of rt){if(u.deploymentTarget!==f.target)continue;let h=u.databaseProvider===f.provider?"database":"cache";if(u.databaseProvider===f.provider||u.cacheProvider===f.provider)throw new Error(`Incompatible: --deploy ${f.target} + --${h} ${f.provider}. ${f.reason}`)}for(let f of nt)if(u.architecture===f.architecture&&u.deploymentTarget===f.target)throw new Error(`Incompatible: --architecture ${f.architecture} + --deploy ${f.target}. ${f.reason}`);let y=ne(u);if(y)throw new Error(`Incompatible: --${y.feature} + --deploy ${y.target}. ${y.reason}`);return u}function I(e){m.isCancel(e)&&(m.cancel("Setup cancelled."),process.exit(0))}function Zt(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Br(e,t){let r=!1;e&&Xt(e),m.log.info(g.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let p=await m.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!Rt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return I(p),p})(),o=e?.appName??await(async()=>{r=!0;let p=await m.text({message:"App name:",initialValue:Et(n),validate:d=>{if(!d?.trim())return"App name is required."}});return I(p),p})(),i=e?.projectDir??await(async()=>{r=!0;let p=await m.text({message:"Project location:",initialValue:`./${n}`});return I(p),p==="."?process.cwd():p})(),s=e?.frontend??await(async()=>{r=!0;let p=Object.keys(et),d=await m.select({message:"Frontend framework:",options:p.map(E=>({value:E,label:et[E].label,hint:et[E].hint}))});return I(d),d})();m.log.info(g.bold("Infrastructure"));let a=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){r=!0;let p=await m.select({message:"Deployment target:",options:ie.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});I(p),a=p}let l=e?.architecture?nt.find(p=>p.architecture===e.architecture&&p.target===a):void 0;if(l)throw new Error(`Incompatible: --architecture ${l.architecture} + --deploy ${l.target}. ${l.reason}`);let u=ne({...e,deploymentTarget:a});if(u)throw new Error(`Incompatible: --${u.feature} + --deploy ${u.target}. ${u.reason}`);let y=ne({companion:!0,deploymentTarget:a})!==void 0,f=new Set(nt.filter(p=>p.target===a).map(p=>p.architecture)),h=Ue.filter(p=>!f.has(p)),$=e?.architecture??await(async()=>{if(h.length===1){let d=h[0];return m.log.info(`Auto-selected ${tt[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let p=await m.select({message:"Architecture:",options:h.map(d=>({value:d,label:tt[d].label,hint:tt[d].hint}))});return I(p),p})(),b=e?.databaseProvider??await(async()=>{r=!0;let p=se.filter(E=>!rt.some(ue=>ue.target===a&&ue.provider===E));if(p.length===1){let E=p[0];return m.log.info(`Auto-selected ${re[E].label} (only compatible option for ${G[a].label}).`),E}let d=await m.select({message:"Database provider:",options:p.map(E=>({value:E,label:re[E].label,hint:re[E].hint}))});return I(d),d})(),U=e?.cacheProvider??await(async()=>{r=!0;let p=ae.filter(E=>!rt.some(ue=>ue.target===a&&ue.provider===E));if(p.length===1){let E=p[0];return m.log.info(`Auto-selected ${Se[E].label} (only compatible option for ${G[a].label}).`),E}let d=await m.select({message:"Cache provider:",options:p.map(E=>({value:E,label:Se[E].label,hint:Se[E].hint}))});return I(d),d})();if(G[a]?.edgeRuntime){let p=Cr.map(d=>` - ${d}`).join(`
3
- `);m.note(p,"Unavailable on edge runtime")}m.log.info(g.bold("Features"));let Q=e?.paymentProvider??await(async()=>{r=!0;let p=await m.select({message:"Payment provider:",options:Fe.map(d=>({value:d,label:kt[d].label,hint:kt[d].hint}))});return I(p),p})(),ee=e?.defaultCurrency??await(async()=>{if(Q==="none")return"USD";r=!0;let p=await m.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:be[d].name}))});return I(p),p})(),le=e?.emailProvider??await(async()=>{r=!0;let p=await m.select({message:"Email provider:",options:Ve.map(d=>({value:d,label:bt[d].label,hint:bt[d].hint}))});return I(p),p})(),ve=e?.errorTracking??await(async()=>{r=!0;let p=await m.select({message:"Error tracking:",options:B.map(d=>({value:d,label:St[d].label,hint:St[d].hint}))});return I(p),p})(),ke=e?.multiTenancy??await(async()=>{r=!0;let p=await m.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return I(p),p})(),w=e?.blog??await(async()=>{r=!0;let p=await m.confirm({message:"Enable blog?",initialValue:!0});return I(p),p})(),N=e?.docs??await(async()=>{r=!0;let p=await m.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return I(p),p})(),de=t?.desktopAllowed!==!1,q=e?.desktop??(de?await(async()=>{r=!0;let p=await m.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return I(p),p})():(m.log.info(g.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),A=e?.ai??await(async()=>{r=!0;let p=await m.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the companion)",initialValue:!1});return I(p),p})(),Le=t?.companionAllowed!==!1,te=!A||y?!1:e?.companion??(Le?await(async()=>{r=!0;let p=await m.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 I(p),p})():(m.log.info(g.dim("Companion: available on the Pro plan and up - skipped.")),!1));A&&y&&m.log.info(g.dim(`Companion: ${G[a].label} cannot hold a connection open - skipped.`));let P=e?.revenueSharing??await(async()=>{r=!0;let p=await m.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return I(p),p})(),Ze=Q==="none"?!1:e?.credits??await(async()=>{r=!0;let p=await m.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return I(p),p})(),Wt=e?.demo,wt=Zt({databaseProvider:b,cacheProvider:U,paymentProvider:Q,emailProvider:le,demo:Wt}),Qe={};if(wt.length>0&&r){m.log.info(g.bold("Credentials")+g.dim(" all optional - press Enter to skip, fill in .env later"));for(let p of wt)if(r=!0,p.secret){let d=await m.password({message:p.message,mask:"*"});I(d),typeof d=="string"&&d.trim()&&(Qe[p.key]=d.trim())}else{let d=await m.text({message:p.message,placeholder:p.placeholder});I(d),typeof d=="string"&&d.trim()&&(Qe[p.key]=d.trim())}}if(r){let p=[` Name: ${g.cyan(n)}`,` App name: ${g.cyan(o)}`,` Location: ${g.cyan(i)}`,` Frontend: ${g.cyan(et[s].label)}`,` Architecture: ${g.cyan(tt[$].label)}`].join(`
4
- `),d=[` Deploy target: ${g.cyan(G[a]?.label??"Node.js / Docker")}`,` Database: ${g.cyan(re[b].label)}`,` Cache: ${g.cyan(Se[U].label)}`].filter(Boolean).join(`
5
- `),E=[Q!=="none"?` Payment: ${g.cyan(kt[Q].label)} (${ee})`:` Payment: ${g.dim("none")}`,` Credits: ${Ze?g.cyan("Yes"):g.dim("No")}`,` AI features: ${A?g.cyan("Yes"):g.dim("No")}`,...A?[` Companion: ${te?g.cyan("Yes"):g.dim("No")}`]:[],` Email: ${g.cyan(bt[le].label)}`,` Error track.: ${ve==="none"?g.dim("none"):g.cyan(St[ve].label)}`,` Multi-tenancy: ${ke?g.cyan("Yes"):g.dim("No")}`,` Blog: ${w?g.cyan("Yes"):g.dim("No")}`,` Docs app: ${N?g.cyan("Yes"):g.dim("No")}`,` Desktop app: ${q?g.cyan("Yes"):g.dim("No")}`,` Rev. sharing: ${P?g.cyan("Yes"):g.dim("No")}`].join(`
6
- `),ue=[g.bold("Project"),p,"",g.bold("Infrastructure"),d,"",g.bold("Features"),E];if(wt.length>0){let fi=wt.map(xr=>{let gi=Qe[xr.key]?g.green("provided"):g.dim("skipped");return` ${xr.key}: ${gi}`}).join(`
7
- `);ue.push("",g.bold("Credentials"),fi)}m.note(ue.join(`
8
- `),"Summary");let Or=await m.confirm({message:"Proceed with these settings?"});(m.isCancel(Or)||!Or)&&(m.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:o,projectDir:i,frontend:s,architecture:$,deploymentTarget:a,databaseProvider:b,cacheProvider:U,paymentProvider:Q,emailProvider:le,errorTracking:ve,multiTenancy:ke,blog:w,docs:N,desktop:q,ai:A,companion:te,revenueSharing:P,credits:Ze,defaultCurrency:ee,...Object.keys(Qe).length>0?{credentials:Qe}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...Wt!==void 0?{demo:Wt}:{}}}import{createReadStream as qr,existsSync as Ai}from"fs";import{mkdir as Oi}from"fs/promises";import{join as xi}from"path";import{Readable as Di}from"stream";import{pipeline as ir}from"stream/promises";import{extract as _i}from"tar";import{join as Re}from"path";import{homedir as wi}from"os";var ot=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",H=".generatesaas",me=Re(H,"manifest.json"),Kr=Re(H,"hashes.json"),Pt=Re(H,"template-hashes.json"),It=Re(H,"template"),Gr=Re(H,"staging"),Hr=Re(H,"staging.json"),ce=Re(wi(),".generatesaas");var C=class extends Error{constructor(r,n,o){super(n);this.status=r;this.body=o}status;body;name="ApiError"};function pe(e){return{apiKey:e,baseUrl:ot}}async function fe(e,t,r){let n=`${e.baseUrl}${t}`,o=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/2.4.0"}});if(!o.ok){let i,s;try{s=await o.json(),i=s.error??`API ${o.status}: ${t}`}catch{i=`API ${o.status}: ${t}`}throw new C(o.status,i,s)}return o}import{existsSync as vi,readFileSync as ki,writeFileSync as bi,mkdirSync as Si}from"fs";import{dirname as Ei}from"path";import*as ge from"@clack/prompts";function it(){if(!vi(ce))return null;try{let e=JSON.parse(ki(ce,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&ge.log.warning(`Found old GitHub token in ${ce}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function Pe(e){Si(Ei(ce),{recursive:!0}),bi(ce,JSON.stringify({apiKey:e},null," ")+`
9
- `,{mode:384})}async function Ke(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=it();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return st()}async function st(){let e=await ge.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return ge.isCancel(e)&&(ge.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as Ri}from"fs/promises";async function he(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await Ri(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 fe(e,"/versions")).json()}async function Qt(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await fe(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof C&&r.status===404)return null;throw r}}async function Yr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
- `,scripts:{}}:await(await fe(e,`/skill/${encodeURIComponent(t)}`)).json()}function Tt(e){if(!(e instanceof C)||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 Jr(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,blog:e.blog,docs:e.docs,desktop:e.desktop,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function er(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await fe(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function zr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await fe(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function tr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function Wr(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let o=await n.json().catch(()=>null);throw new Error(o?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var rr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".nuxt",".output",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),nr=new Set(["pnpm-lock.yaml"]);function Ge(e){if(or(e))return!0;for(let t of e.split("/"))if(nr.has(t))return!0;return!1}var Pi=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),Ii=["scripts/docs-lint.ts"],Ti=["docs/superpowers","packages/cli","packages/cli-api","apps/companion","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 or(e){let t=e.split("/");for(let r of t)if(rr.has(r))return!0;if(Ii.includes(e))return!1;if(Pi.has(t[0]))return!0;for(let r of Ti)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function At(e,t,r){await Oi(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=xi(n,`v${t}.tar.gz`);if(!Ai(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await ir(qr(a),sr(r));return}let o=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(o){await ir(qr(o),sr(r));return}let i=await fe(e,`/template/${encodeURIComponent(t)}`);if(!i.body)throw new Error("Empty response body");let s=Di.fromWeb(i.body);await ir(s,sr(r))}function sr(e){return _i({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!or(r):!0},sync:!1})}import{readdir as Hi,readFile as pt,rm as en,writeFile as lt}from"fs/promises";import{join as we}from"path";import{readFile as ct,rm as Vi}from"fs/promises";import{join as at}from"path";import{mkdir as Ni,readdir as Ci,rm as $i,rmdir as ji,writeFile as Li}from"fs/promises";import{dirname as Ot,join as Mi,relative as Ui,sep as Fi}from"path";function Ie(e){return e.split(Fi).join("/")}async function xt(e){await Ni(e,{recursive:!0})}async function c(e,t){await xt(Ot(e)),await Li(e,t,"utf-8")}async function He(e,t){await $i(e,{force:!0});let r=Ot(e);for(;r!==t&&r!==Ot(r);){try{await ji(r)}catch{return}r=Ot(r)}}async function Te(e,t,r){let n=[],o=await Ci(e,{withFileTypes:!0});for(let i of o){let s=Mi(e,i.name),a=Ie(Ui(t,s));r(a)||(i.isDirectory()?n.push(...await Te(s,t,r)):i.isFile()&&n.push(s))}return n}function Bi(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function ye(e,t,r,n){let o=Bi(r);if(e.match(o)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let i=e.replace(o,"");if(i.includes(`gsaas:${r}-start`)||i.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return i.replace(/\n{3,}/g,`
11
-
12
- `)}async function j(e,t,r,n,o){let i=await ct(e,"utf-8"),s=i.indexOf(t);if(s===-1)throw new Error(`${o}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(i.indexOf(t,s+t.length)!==-1)throw new Error(`${o}: the ${n} seam appears more than once (boilerplate drift).`);await c(e,i.slice(0,s)+r+i.slice(s+t.length))}async function Dt(e,t,r,n){let o=/\n([\t ]+)"/.exec(await ct(e,"utf-8"))?.[1];if(o!==r){let i=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${i(r)}-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 c(e,`${JSON.stringify(t,null,r)}
13
- `)}function _t(e){return e.frontend==="nextjs"?"next":"nuxt"}async function Ki(e,t,r,n){let o=at(e,"ai.mdx"),s=(await ct(o,"utf-8")).split(`
14
- `).find(a=>a.includes(`href="${r}"`));if(s===void 0)throw new Error(`${n}: expected the ai.mdx card linking to ${r} (boilerplate drift).`);await j(o,`${s}
15
- `,"",`${t} ai.mdx ${r} card`,n)}async function Gi(e,t,r,n){let o=at(e,"ai.mdx"),i=`| **${r}** |`,a=(await ct(o,"utf-8")).split(`
16
- `).find(l=>l.startsWith(i));if(a===void 0)throw new Error(`${n}: expected the ai.mdx "${r}" hub-table row (boilerplate drift).`);await j(o,`${a}
17
- `,"",`${t} ai.mdx ${r} hub-table row`,n)}async function Xr(e,t,r,n,o,i){let s=at(e,"docs",t);await Vi(at(s,r),{recursive:!0}),await j(at(s,"meta.json"),` "${r}",
18
- `,"",`${t} meta.json ${r} nav entry`,o);for(let a of n)await Ki(s,t,a,o);i!==void 0&&await Gi(s,t,i,o)}async function Zr(e){let t=`import { config } from "@repo/config";
19
- `,r=await ct(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),o=n.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"").replace(/"(?:\\.|[^"\\])*"/g,'""').replace(/'(?:\\.|[^'\\])*'/g,"''").replace(/`(?:\\.|[^`\\])*`/g,"``");/\bconfig\b/.test(o)||await c(e,n)}var Yi=["apps/web-nuxt/public/images/blog","apps/web-next/public/images/blog","packages/content/en/blog","packages/content/ro/blog"];async function tn(e){await Promise.all(Yi.map(t=>en(we(e,t),{recursive:!0,force:!0})))}var Ji=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function rn(e){let t="removeDesktopDemoScreen";await en(we(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Ji){let n=we(e,r);await lt(n,ye(await pt(n,"utf-8"),r,"demo",t))}}var zi="packages/config/src/blog.ts";async function nn(e){let t=we(e,zi),r=await pt(t,"utf-8"),n=Qr(Qr(r,"blogCategories",t),"blogAuthors",t);await lt(t,n)}function Qr(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function on(e){let t=we(e,"packages/i18n/translations"),r;try{r=await Hi(t)}catch{return}for(let n of r){let o=we(t,n,"web.json"),i;try{i=await pt(o,"utf-8")}catch{continue}let s=JSON.parse(i);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await lt(o,JSON.stringify(s,null," ")+`
20
- `))}}var Wi="packages/config/src/ai/tasks.ts";async function sn(e){let t=we(e,Wi),r=await pt(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);await lt(t,n)}async function an(e,t){let r=we(e,".claude","settings.json"),n;try{n=await pt(r,"utf8")}catch{return}let o=JSON.parse(n);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=>qi(i,t))),await lt(r,JSON.stringify(o,null," ")+`
21
- `)}function qi(e,t){return!(e.startsWith("mcp__")||t!=="nuxt"&&e.includes("nuxt"))}import{join as cn}from"path";var Xi={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},Zi={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},Qi={redis:"Redis",upstash:"Upstash Redis"},es={node:"Node.js / Docker",vercel:"Vercel"},ts={stripe:"Stripe",polar:"Polar"};function rs(e){let t=e.frontend==="nuxt",r=t?"Nuxt 4":"Next.js 16",n=t?"apps/web-nuxt":"apps/web-next",o=t?"`app/` pages + components + composables":"`app/` routes, `components/`, `lib/`",i=e.architecture==="fullstack",s=i?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",a=i?`Mounted inside \`${n}\`. 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.",l=Qi[e.cacheProvider],u=es[e.deploymentTarget],y=e.paymentProvider==="none"?"":`
22
- - **Payments:** ${ts[e.paymentProvider]}`,f=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",h=e.companion?"\n- **Companion daemon** - your users install OpenCompanion on a machine they control and pair it with their account. Everything you own lives in this repo: the `/companion/*` routes, the relay, the Companions page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",$=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`.",b=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
2
+ import{Command as Rl}from"commander";import*as ls from"@clack/prompts";import{existsSync as Lc,readdirSync as jc,rmSync as Mc}from"fs";import{join as Uc,resolve as Vc}from"path";import{Option as ne}from"commander";import*as b from"@clack/prompts";import*as Pt from"@clack/prompts";import tr from"picocolors";function Vr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Pt.intro(tr.bgYellow(tr.black(t)))}function Fr(){Pt.outro(tr.yellow("Happy building!"))}import*as u from"@clack/prompts";import h from"picocolors";var ct={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},It={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Tt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},_t={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Br={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ie={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var G={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Te={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},_e={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},Ke=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],Ge=[{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)."}],ds=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ie(e){return ds.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var se={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},Oe=Object.keys(se);function rr(e){let t=[];for(let r of Ke)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of Ge)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Kr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function He(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var Ye=["fullstack","separate"],We=["stripe","polar","none"],qe=["smtp","ses","resend"];var Gr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],B=["sentry","posthog"];function Hr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ot(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function xt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Yr=["runner"];function nr(e){if(!Yr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function lt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function Wr(e){return Yr.some(r=>e[r]===!0)&&(e.ai=!0),e}function qr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function zr(e){let t=us(e,e.desktopAi);return delete e.desktopAi,t}function us(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Jr(e){let t={};if(e.name!==void 0){if(!xt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),nr(t),lt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ae.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ae.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ce.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ce.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Oe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Oe.join(", ")}`);let r=se[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Xr(e){let t=e.projectName??ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??Ot(t),i=e.deploymentTarget??ze.deploymentTarget,o=G[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":ze.databaseProvider),a=e.cacheProvider??(o?"upstash":ze.cacheProvider),p=e.emailProvider??(o?"resend":ze.emailProvider),m={...ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};m.paymentProvider==="none"&&(m.credits=!1);for(let g of Ke){if(m.deploymentTarget!==g.target)continue;let k=m.databaseProvider===g.provider?"database":"cache";if(m.databaseProvider===g.provider||m.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ge)if(m.architecture===g.architecture&&m.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ie(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return lt(m),m}function S(e){u.isCancel(e)&&(u.cancel("Setup cancelled."),process.exit(0))}function ir(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Zr(e,t){let r=!1;e&&nr(e),e&&lt(e),u.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!xt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Ot(n),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return S(c),c==="."?process.cwd():c})();u.log.info(h.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[...Oe.map(d=>({value:d,label:se[d].label,hint:se[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(S(c),c!=="custom"){let d=se[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,u.log.info(`${se[c].label}: ${se[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});S(c),a=c}let p=e?.architecture?Ge.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let m=ie({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ge.filter(c=>c.target===a).map(c=>c.architecture)),k=Ye.filter(c=>!g.has(c)),A=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return u.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:k.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return S(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ce.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return S(d),d})(),$=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=le.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${_e[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:_e[T].label,hint:_e[T].hint}))});return S(d),d})();if(G[a]?.edgeRuntime){let c=Kr.map(d=>` - ${d}`).join(`
3
+ `);u.note(c,"Unavailable on edge runtime")}u.log.info(h.bold("Features"));let J=e?.paymentProvider??await(async()=>{r=!0;let c=await u.select({message:"Payment provider:",options:We.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return S(c),c})(),fe=e?.defaultCurrency??await(async()=>{if(J==="none")return"USD";r=!0;let c=await u.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Ie[d].name}))});return S(c),c})(),X=e?.emailProvider??await(async()=>{r=!0;let c=await u.select({message:"Email provider:",options:qe.map(d=>({value:d,label:Tt[d].label,hint:Tt[d].hint}))});return S(c),c})(),he=e?.observability??await(async()=>{r=!0;let c=await u.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:B.map(d=>({value:d,label:_t[d].label,hint:_t[d].hint}))});return S(c),c})(),Ee=e?.multiTenancy??await(async()=>{r=!0;let c=await u.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),Se=e?.blog??await(async()=>{r=!0;let c=await u.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),Re=e?.docs??await(async()=>{r=!0;let c=await u.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),v=t?.desktopAllowed!==!1,x=e?.desktop??(v?await(async()=>{r=!0;let c=await u.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return S(c),c})():(u.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),L=e?.ai??await(async()=>{r=!0;let c=await u.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the runner)",initialValue:!1});return S(c),c})(),ge=t?.runnerAllowed!==!1,U=e?.webAi===!1,V=!L||w||U?!1:e?.runner??(ge?await(async()=>{r=!0;let c=await u.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return S(c),c})():(u.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));L&&w?u.log.info(h.dim(`Runner: ${G[a].label} cannot hold a connection open - skipped.`)):L&&U&&u.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let F=e?.webAi??(x&&L&&!V?await(async()=>{r=!0;let c=await u.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return S(c),c})():!0);lt({webAi:F,ai:L,desktop:x,runner:V});let Ae=e?.revenueSharing??await(async()=>{r=!0;let c=await u.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),Be=J==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await u.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),R=e?.demo,Pe=ir({databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,demo:R}),at={};if(Pe.length>0&&r){u.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Pe)if(r=!0,c.secret){let d=await u.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}else{let d=await u.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(o)}`,` Architecture: ${h.cyan(ct[A].label)}`].join(`
4
+ `),d=[` Deploy target: ${h.cyan(G[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Te[f].label)}`,` Cache: ${h.cyan(_e[$].label)}`].filter(Boolean).join(`
5
+ `),T=[J!=="none"?` Payment: ${h.cyan(It[J].label)} (${fe})`:` Payment: ${h.dim("none")}`,` Credits: ${Be?h.cyan("Yes"):h.dim("No")}`,` AI features: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` Runner: ${V?h.cyan("Yes"):h.dim("No")}`]:[],...F?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(Tt[X].label)}`,` Observability: ${he.length===0?h.dim("none"):h.cyan(he.map(er=>_t[er].label).join(", "))}`,` Multi-tenancy: ${Ee?h.cyan("Yes"):h.dim("No")}`,` Blog: ${Se?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${Re?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${x?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${Ae?h.cyan("Yes"):h.dim("No")}`].join(`
6
+ `),ye=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),T];if(Pe.length>0){let er=Pe.map(Ur=>{let ps=at[Ur.key]?h.green("provided"):h.dim("skipped");return` ${Ur.key}: ${ps}`}).join(`
7
+ `);ye.push("",h.bold("Credentials"),er)}u.note(ye.join(`
8
+ `),"Summary");let Mr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(Mr)||!Mr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:A,deploymentTarget:a,databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,observability:he,multiTenancy:Ee,blog:Se,docs:Re,desktop:x,ai:L,webAi:F,runner:V,revenueSharing:Ae,credits:Be,defaultCurrency:fe,...Object.keys(at).length>0?{credentials:at}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...R!==void 0?{demo:R}:{}}}import{createReadStream as pn,existsSync as Es}from"fs";import{mkdir as Ss}from"fs/promises";import{join as Rs}from"path";import{Readable as As}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ps}from"tar";import{join as xe}from"path";import{homedir as ms}from"os";var pt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",H=".generatesaas",ve=xe(H,"manifest.json"),Qr="nextjs",sr="nuxt",or="2.4.1",en=xe(H,"hashes.json"),Dt=xe(H,"template-hashes.json"),Nt=xe(H,"template"),tn=xe(H,"staging"),rn=xe(H,"staging.json"),pe=xe(ms(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function de(e){return{apiKey:e,baseUrl:pt}}async function be(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.0.2"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as fs,readFileSync as hs,writeFileSync as gs,mkdirSync as ys}from"fs";import{dirname as vs}from"path";import*as we from"@clack/prompts";function dt(){if(!fs(pe))return null;try{let e=JSON.parse(hs(pe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&we.log.warning(`Found old GitHub token in ${pe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function De(e){ys(vs(pe),{recursive:!0}),gs(pe,JSON.stringify({apiKey:e},null," ")+`
9
+ `,{mode:384})}async function Je(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=dt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return ut()}async function ut(){let e=await we.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return we.isCancel(e)&&(we.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as bs}from"fs/promises";async function ke(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await bs(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await be(e,"/versions")).json()}async function nn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await be(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function sn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
10
+ `,scripts:{}}:await(await be(e,`/skill/${encodeURIComponent(t)}`)).json()}function Ct(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var ar="nextjs";function on(e){return{frontend:ar,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await be(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function an(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await be(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function lr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function cn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),dr=new Set(["pnpm-lock.yaml"]);function Xe(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var ws=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md","HANDOFF.md"]),ln=["scripts/docs-lint.ts"],ks=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function ur(e){let t=e.split("/");for(let r of t)if(pr.has(r))return!0;if(ln.includes(e)||ln.some(r=>r.startsWith(e+"/")))return!1;if(ws.has(t[0]))return!0;for(let r of ks)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function $t(e,t,r){await Ss(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Rs(n,`v${t}.tar.gz`);if(!Es(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(pn(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(pn(i),fr(r));return}let o=await be(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=As.fromWeb(o.body);await mr(s,fr(r))}function fr(e){return Ps({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as fn,readFile as ht,rm as hr,writeFile as gt}from"fs/promises";import{join as Q}from"path";import{readFile as ft,rm as $s}from"fs/promises";import{join as mt}from"path";import{mkdir as Is,readdir as Ts,rm as _s,rmdir as Os,writeFile as xs}from"fs/promises";import{dirname as Lt,join as Ds,relative as Ns,sep as Cs}from"path";function Ne(e){return e.split(Cs).join("/")}async function jt(e){await Is(e,{recursive:!0})}async function l(e,t){await jt(Lt(e)),await xs(e,t,"utf-8")}async function Mt(e,t){await _s(e,{force:!0});let r=Lt(e);for(;r!==t&&r!==Lt(r);){try{await Os(r)}catch{return}r=Lt(r)}}async function ue(e,t,r,n){let i=[],o=await Ts(e,{withFileTypes:!0});for(let s of o){let a=Ds(e,s.name),p=Ne(Ns(t,a));r(p)||(s.isDirectory()?i.push(...await ue(a,t,r,n)):s.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}function Ls(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Z(e,t,r,n){let i=Ls(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
11
+
12
+ `).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function Y(e,t,r,n,i){let o=await ft(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Ze(e,t,r,n){let i=/\n([\t ]+)"/.exec(await ft(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
13
+ `)}async function js(e,t,r){let n=mt(e,"ai.mdx"),o=(await ft(n,"utf-8")).split(`
14
+ `).find(s=>s.includes(`href="${t}"`));if(o===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await Y(n,`${o}
15
+ `,"",`ai.mdx ${t} card`,r)}async function Ms(e,t,r){let n=mt(e,"ai.mdx"),i=`| **${t}** |`,s=(await ft(n,"utf-8")).split(`
16
+ `).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await Y(n,`${s}
17
+ `,"",`ai.mdx ${t} hub-table row`,r)}async function dn(e,t,r,n,i){let o=mt(e,"docs");await $s(mt(o,t),{recursive:!0}),await Y(mt(o,"meta.json"),` "${t}",
18
+ `,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await js(o,s,n);i!==void 0&&await Ms(o,i,n)}function Us(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
19
+ `;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
20
+ `&&(t+=`
21
+ `),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
22
+ `&&(t+=`
23
+ `),r++;r++;continue}t+=n,r++}return t}async function un(e){let t=`import { config } from "@repo/config";
24
+ `,r=await ft(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Us(n);/\bconfig\b/.test(i)||await l(e,n)}var Vs=["apps/web/public/images/blog"];async function hn(e){let t=Q(e,"packages/content"),r=[];try{r=(await fn(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...Vs.map(n=>hr(Q(e,n),{recursive:!0,force:!0})),...r.map(n=>hr(Q(t,n,"blog"),{recursive:!0,force:!0}))])}var Fs=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function gn(e){let t="removeDesktopDemoScreen";await hr(Q(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Fs){let n=Q(e,r);await gt(n,Z(await ht(n,"utf-8"),r,"demo",t))}}var Bs="packages/config/src/blog.ts";async function yn(e){let t=Q(e,Bs),r=await ht(t,"utf-8"),n=mn(mn(r,"blogCategories",t),"blogAuthors",t);await gt(t,n)}function mn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function vn(e){let t=Q(e,"packages/i18n/translations"),r;try{r=await fn(t)}catch{return}for(let n of r){let i=Q(t,n,"web.json"),o;try{o=await ht(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await gt(i,JSON.stringify(s,null," ")+`
25
+ `))}}var Ks="packages/config/src/ai/tasks.ts",Gs="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Hs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function bn(e){let t=Q(e,Ks),r=await ht(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Gs,Hs);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await gt(t,i)}async function wn(e){let t=Q(e,".claude","settings.json"),r;try{r=await ht(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Ys)),await gt(t,JSON.stringify(n,null," ")+`
26
+ `)}function Ys(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as kn}from"path";var Ws={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},qs={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},zs={redis:"Redis",upstash:"Upstash Redis"},Js={node:"Node.js / Docker",vercel:"Vercel"},Ut="apps/web",En="Next.js 16",Xs="`app/` routes, `components/`, `lib/`",Zs={stripe:"Stripe",polar:"Polar"};function Qs(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Ut}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=zs[e.cacheProvider],o=Js[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
27
+ - **Payments:** ${Zs[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",m=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Ut}/i18n/request.ts\`.`;return`# AGENTS.md
23
28
 
24
29
  Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
25
30
  Keep this file tight: add a rule only when it prevents a recurring mistake - too
@@ -31,9 +36,9 @@ This boilerplate already ships ~30 features, every one config-gated and wired en
31
36
  end. Before writing a new file, route, table, or component, assume it ALREADY EXISTS
32
37
  and go find it:
33
38
 
34
- 1. \`docs/${t?"nuxt":"next"}/index.mdx\` - the catalog of every shipped feature and its config flag.
39
+ 1. \`docs/index.mdx\` - the catalog of every shipped feature and its config flag.
35
40
  2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
36
- 3. Search \`packages/\` and \`${n}/\` for the name before creating anything.
41
+ 3. Search \`packages/\` and \`${Ut}/\` for the name before creating anything.
37
42
 
38
43
  Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
39
44
  billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
@@ -45,13 +50,13 @@ flag, route, or translation is the most common and most costly mistake in this r
45
50
 
46
51
  ## Stack
47
52
 
48
- - **Frontend:** ${r} ${s}
49
- - **API:** Hono, RPC-typed. ${a}
50
- - **Database:** Drizzle ORM + ${Xi[e.databaseProvider]}
51
- - **Cache + jobs:** ${l} + Inngest
52
- - **Auth:** Better Auth${y}
53
- - **Email:** ${Zi[e.emailProvider]}
54
- - **Deploy:** ${u}
53
+ - **Frontend:** ${En} ${r}
54
+ - **API:** Hono, RPC-typed. ${n}
55
+ - **Database:** Drizzle ORM + ${Ws[e.databaseProvider]}
56
+ - **Cache + jobs:** ${i} + Inngest
57
+ - **Auth:** Better Auth${s}
58
+ - **Email:** ${qs[e.emailProvider]}
59
+ - **Deploy:** ${o}
55
60
 
56
61
  ## Where things live (extend these - don't reinvent)
57
62
 
@@ -61,8 +66,8 @@ flag, route, or translation is the most common and most costly mistake in this r
61
66
  - \`packages/auth/src/config.ts\` - Better Auth config.
62
67
  - \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
63
68
  - \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
64
- - \`${n}\` - the ${r} app (${o}).${h}
65
- - \`docs/${t?"nuxt":"next"}/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${f}.
69
+ - \`${Ut}\` - the ${En} app (${Xs}).${p}
70
+ - \`docs/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${a}.
66
71
 
67
72
  ## Code style
68
73
 
@@ -79,8 +84,8 @@ flag, route, or translation is the most common and most costly mistake in this r
79
84
 
80
85
  - **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
81
86
  - **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
82
- - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${$} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
83
- - ${b}
87
+ - **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${m} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
88
+ - **Navigation:** \`next/link\` for links; \`redirect()\` from \`next/navigation\` for programmatic redirects in Server Components.
84
89
  - **Routes:** use \`config.routes.*\`, never hardcoded path strings.
85
90
  - **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
86
91
 
@@ -91,23 +96,23 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
91
96
  ## This project
92
97
 
93
98
  Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
94
- `}async function pn(e){await c(cn(e.projectDir,"AGENTS.md"),rs(e)),await c(cn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
95
- `)}import{join as ns}from"path";var os={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function is(e){let t=e.appName.trim()||e.projectName,r=e.frontend==="nuxt",n=r?"Nuxt 4":"Next.js 16",o=r?"apps/web-nuxt":"apps/web-next",i=os[e.databaseProvider],s=e.architecture==="fullstack"?`${n} 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.`:`${n} app at \`${o}/\` and a separate Hono backend at \`apps/backend/\`.`,a=e.architecture==="fullstack"?`- App + API: http://localhost:3000
99
+ `}async function Sn(e){await l(kn(e.projectDir,"AGENTS.md"),Qs(e)),await l(kn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
100
+ `)}import{join as eo}from"path";var Rn="apps/web",gr="Next.js 16",to={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ro(e){let t=e.appName.trim()||e.projectName,r=to[e.databaseProvider],n=e.architecture==="fullstack"?`${gr} app at \`${Rn}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${gr} app at \`${Rn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
96
101
  - Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
97
102
  - API: http://localhost:3010
98
- - Inngest dev server: http://127.0.0.1:8288`,l=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
99
- `,u=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
103
+ - Inngest dev server: http://127.0.0.1:8288`,o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
104
+ `,s=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
100
105
 
101
- ${s}
106
+ ${n}
102
107
 
103
108
  ## Stack
104
109
 
105
- - **Frontend:** ${n}
110
+ - **Frontend:** ${gr}
106
111
  - **Backend:** Hono (TypeScript, RPC-typed)
107
112
  - **Auth:** Better Auth
108
- - **ORM / DB:** Drizzle + ${i}
113
+ - **ORM / DB:** Drizzle + ${r}
109
114
  - **Background jobs:** Inngest
110
- - **i18n:** ${r?"@nuxtjs/i18n":"next-intl"}
115
+ - **i18n:** next-intl
111
116
 
112
117
  ## Development
113
118
 
@@ -116,11 +121,11 @@ pnpm install
116
121
  # A ready-to-run \`.env\` was generated for you - open it and fill in the
117
122
  # values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
118
123
  # reference. All apps load the single root \`.env\`.
119
- ${l}pnpm db:setup # first run: create the database schema (idempotent)
124
+ ${o}pnpm db:setup # first run: create the database schema (idempotent)
120
125
  pnpm dev
121
126
  \`\`\`
122
127
 
123
- ${a}
128
+ ${i}
124
129
 
125
130
  ## Build your SaaS
126
131
 
@@ -140,7 +145,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
140
145
  pnpm auth:generate # regenerate Better Auth schema after config changes
141
146
  \`\`\`
142
147
 
143
- ${u}
148
+ ${s}
144
149
 
145
150
  ## Removing the GenerateSaaS license
146
151
 
@@ -153,53 +158,55 @@ pnpm dlx generatesaas eject
153
158
  ## Updates
154
159
 
155
160
  To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
156
- `}async function ln(e){await c(ns(e.projectDir,"README.md"),is(e))}import{access as ss,readFile as as}from"fs/promises";import{join as Ae}from"path";async function cs(e,t,r){let n=Ae(e,"apps/electron/dev-app-update.yml");try{await ss(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await c(n,`provider: generic
161
+ `}async function An(e){await l(eo(e.projectDir,"README.md"),ro(e))}import{access as no}from"fs/promises";import{join as Vt}from"path";var Pn="1x00000000000000000000AA",In="1x0000000000000000000000000000000AA",yt="NEXT_PUBLIC_TURNSTILE_SITE_KEY";async function io(e,t,r){let n=Vt(e,"apps/electron/dev-app-update.yml");try{await no(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
157
162
  url: ${t}
158
163
  updaterCacheDirName: ${r}
159
- `)}function ps(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function ls(e,t){let r=jr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var dt={name:"OpenCompanion",binary:"opencompanion",envPrefix:"OPENCOMPANION",repoUrl:"https://github.com/AlexChelan/OpenCompanion",installBase:"https://github.com/AlexChelan/OpenCompanion/releases/latest/download"};function ds(e){return e.companion?["{"," enabled: true,",' clientId: "companion",'," daemon: {",` name: ${JSON.stringify(dt.name)},`,` binary: ${JSON.stringify(dt.binary)},`,` envPrefix: ${JSON.stringify(dt.envPrefix)},`,` repoUrl: ${JSON.stringify(dt.repoUrl)},`,` installBase: ${JSON.stringify(dt.installBase)}`," }"," }"].join(`
160
- `):'{ enabled: false, clientId: "companion" }'}var us="// Off by default and off costs nothing: every surface checks `errorTracking.enabled`\n// and the selected provider's credentials before it dynamically imports an SDK. Turn\n// it on by flipping `enabled`, picking a `provider` and pasting that provider's key.\n// Keep `enabled` a literal - the bundler folds the branch away only when it can see\n// the value, and a computed flag ships the SDK to every visitor.",ms="// `enabled` MUST stay a literal true/false. Every surface checks it before it dynamically\n// imports an SDK, and your bundler drops the whole branch only when it can see the value\n// inline - a computed or imported flag ships the SDK to every visitor instead.",fs=`// Both provider blocks are always written, so toggling \`enabled\` off or switching
161
- // provider never loses a key. The Sentry DSN and the PostHog public key are public by
162
- // design (they only authorize sending events, never reading them), which is why they
163
- // are committed here rather than kept in env - a packaged desktop app has no env to
164
- // read. Server-side, SENTRY_DSN and POSTHOG_API_KEY override the values below.`,gs=` enabled: false,
165
- provider: "sentry",`;function hs(e){return e==="sentry"?`// Paste your project DSN below (Sentry: Settings -> Projects -> Client Keys). The DSN is
166
- // public by design - it only authorizes SENDING events, never reading them - which is why it
167
- // lives here rather than in env, and why a packaged desktop app can carry it. Server-side,
168
- // SENTRY_DSN overrides it.`:e==="posthog"?`// Paste your PostHog project API key below (it starts with \`phc_\`) and set the host of your
169
- // instance. The key is public by design - it only authorizes SENDING events - which is why it
170
- // lives here rather than in env. Server-side, POSTHOG_API_KEY overrides it.
171
- //
172
- // PostHog ships no Electron SDK, so a desktop build reports nothing and says so once at startup.
173
- // PostHog error tracking uses its own client, separate from PostHog analytics, so declining
174
- // cookies stops analytics but never stops error reports.`:"// Your project was generated with error tracking OFF, so no reporting SDK was installed and no\n// provider adapter was generated. Flipping `enabled` here alone reports nothing: set\n// `errorTracking` in `.generatesaas/manifest.json` to the provider you want and run\n// `generatesaas update`, which re-shapes the project and brings that provider's adapter and SDK in.\n// The update stages nothing while you are already on the latest version, so the switch lands with\n// the next release."}async function ys(e,t){let r=Ae(e,"packages/config/src/observability.mjs"),n;try{n=await as(r,"utf-8")}catch{throw new Error("generateConfig: expected packages/config/src/observability.mjs to exist - did the config package move?")}let o=t!=="none",i=[{find:us,replace:ms},{find:fs,replace:hs(t)},{find:gs,replace:` enabled: ${String(o)},
175
- provider: "${o?t:"sentry"}",`}];for(let s of i){if(!n.includes(s.find))throw new Error(`generateConfig: packages/config/src/observability.mjs no longer contains the text this generator rewrites - re-point the anchor. Missing: ${s.find.split(`
176
- `)[0]}`);n=n.replace(s.find,s.replace)}return n}async function dn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",o=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",i=ps(o),s=e.demo?"false":"true",a=e.demo?`{
177
- enableInDev: true,
178
- chatwoot: {
179
- baseUrl: "https://support.alexchelan.com",
180
- websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
181
- }
182
- }`:"{}",l=e.frontend==="nextjs"&&e.architecture==="fullstack"?"false":"true",u=ls(t,i),y=`https://cdn.${i}/desktop`,f=ds(e),h=`import type { AppConfig } from "@repo/config/types";
164
+ `)}function so(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function oo(e,t){let r=Hr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var Qe={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function ao(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(Qe.name)},`,` binary: ${JSON.stringify(Qe.binary)},`,` envPrefix: ${JSON.stringify(Qe.envPrefix)},`,` repoUrl: ${JSON.stringify(Qe.repoUrl)},`,` installBase: ${JSON.stringify(Qe.installBase)},`,` image: ${JSON.stringify(Qe.image)}`," }"," }"].join(`
165
+ `):'{ enabled: false, clientId: "runner" }'}function co(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
166
+ `),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
167
+ `)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
168
+ `):`${t}
169
+ observability: {
170
+ ${r.join(`,
171
+ `)}
172
+ },`}async function Tn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=so(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
173
+ multiTenant: true,
174
+ organizationLimit: 5
175
+ }`:"{ multiTenant: false }",p=co(e.observability),m=e.demo?`{
176
+ enableInDev: true,
177
+ chatwoot: {
178
+ baseUrl: "https://support.alexchelan.com",
179
+ websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
180
+ }
181
+ }`:"{}",w=e.architecture==="fullstack"?"false":"true",g=oo(t,o),k=`https://cdn.${o}/desktop`,A=ao(e),f=`import type { AppConfig } from "@repo/config/types";
183
182
  import { desktopConfig } from "./desktop.mjs";
184
- import { observabilityConfig } from "./observability.mjs";
185
- import { supportConfig } from "./support.mjs";
186
- import { tenancyConfig } from "./tenancy-flags.mjs";
187
-
188
- const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean);
183
+ import { supportConfig } from "./support";
189
184
 
185
+ /**
186
+ * This file is PURE STATIC DATA. No \`process.env\`, no imports that read it.
187
+ *
188
+ * That is load-bearing, not style. A packaged desktop app has no \`.env\` and a sandboxed renderer
189
+ * cannot read one, so a config that touches \`process.env\` either fails or silently resolves to
190
+ * undefined on those surfaces. Keeping it env-free is what lets server, browser, Electron main and
191
+ * Electron renderer all import the SAME module.
192
+ *
193
+ * A value that varies per DEPLOYMENT belongs in \`@repo/runtime\`'s \`env\` instead, which is
194
+ * server-only and validated - \`BASE_URL\` and \`TRUSTED_ORIGINS\` are declared there. What lives here
195
+ * is your project's own identity: edit it directly.
196
+ */
190
197
  export const config: AppConfig = {
191
198
  siteName: "${t}",
192
199
  fullSiteName: "${t}",
193
- domain: "${o}",
194
- baseUrl: process.env.BASE_URL ?? "${n}",
200
+ domain: "${i}",
201
+ baseUrl: "${n}",
195
202
  indexable: ${s},
196
203
  logo: {
197
204
  main: "/images/logo.svg",
198
205
  square: "/images/logo-square.svg"
199
206
  },
200
- origins: trustedOrigins?.length ? trustedOrigins : ["http://localhost:3000", "http://localhost:5173"],
207
+ origins: ["http://localhost:3000", "http://localhost:5173"],
201
208
  waitlist: false,
202
- tenancy: tenancyConfig,
209
+ tenancy: ${a},
203
210
  theme: {
204
211
  default: "system",
205
212
  switcher: true,
@@ -217,16 +224,16 @@ export const config: AppConfig = {
217
224
  limitPerSecond: 3,
218
225
  senders: {
219
226
  transactional: {
220
- email: "noreply@${i}",
227
+ email: "noreply@${o}",
221
228
  senderName: "${t}"
222
229
  },
223
230
  marketing: {
224
- email: "hello@${i}",
231
+ email: "hello@${o}",
225
232
  senderName: "${t}",
226
233
  signatureName: "Alex"
227
234
  },
228
235
  support: {
229
- email: "support@${i}",
236
+ email: "support@${o}",
230
237
  senderName: "${t} Support"
231
238
  }
232
239
  },
@@ -254,8 +261,8 @@ export const config: AppConfig = {
254
261
  prefix: "key_"
255
262
  },
256
263
  apiDocs: true,
257
- performanceMonitor: { enabled: ${l} },
258
- observability: observabilityConfig,
264
+ performanceMonitor: { enabled: ${w} },
265
+ ${p}
259
266
  notifications: {
260
267
  enabled: true,
261
268
  maxPerUser: 100,
@@ -272,7 +279,11 @@ export const config: AppConfig = {
272
279
  captcha: ${e.demo?`{
273
280
  enabled: true,
274
281
  provider: "turnstile",
275
- siteKey: "0x4AAAAAACJo9y9FxH8lqkGu"
282
+ // Cloudflare's always-passes TEST site key. A real one is domain-locked, so it
283
+ // works only for the deployment that owns it - set yours in ${yt}
284
+ // on the deployment, and swap TURNSTILE_SECRET_KEY to its matching secret in the
285
+ // same breath (a test key and a real secret reject each other).
286
+ siteKey: "${Pn}"
276
287
  }`:"{ enabled: false }"},
277
288
  support: supportConfig,
278
289
  currency: ${e.demo?`{
@@ -294,7 +305,7 @@ export const config: AppConfig = {
294
305
  }`:`{
295
306
  base: "${e.defaultCurrency}",
296
307
  list: [
297
- { symbol: "${be[e.defaultCurrency].symbol}", name: "${be[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${be[e.defaultCurrency].place}", space: ${be[e.defaultCurrency].space} }
308
+ { symbol: "${Ie[e.defaultCurrency].symbol}", name: "${Ie[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ie[e.defaultCurrency].place}", space: ${Ie[e.defaultCurrency].space} }
298
309
  ],
299
310
  countryMap: {
300
311
  default: "${e.defaultCurrency}"
@@ -318,10 +329,20 @@ export const config: AppConfig = {
318
329
  },
319
330
  ai: {
320
331
  enabled: ${e.ai},
321
- // Built-in AI: your app offers models under its OWN name, billed from user credits (which need a
322
- // payment provider to buy), so it is generated on exactly when a payment provider exists. Powered by
323
- // OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup. Flip this to change it.
324
- builtin: ${r},
332
+ // Where the AI features SHOW UP. False is the desktop-first shape: the AI pages and their nav
333
+ // entries stay out of this website, which keeps account, login and billing, while the desktop
334
+ // app is the AI product. It gates the web SURFACE only - \`enabled\` above still runs the
335
+ // service, the /api/ai routes still answer, and the desktop app still talks to them.
336
+ webUi: ${e.webAi},
337
+ // Built-in AI: your app offers models under its OWN name, billed from user CREDITS - so it is
338
+ // generated on exactly when metered credits are on (which in turn need a payment provider to buy).
339
+ // Both halves are required, and gating on the payment provider ALONE was a real break: a project
340
+ // with a provider but no credits shipped built-in AI with nothing to meter it, and every built-in
341
+ // request 500'd on the credit pre-flight (\`costToCredits\` refuses to price against a missing
342
+ // scale rather than silently under-billing). Without credits your users bring their own keys -
343
+ // that is what \`byok\` below is. Powered by OpenRouter - set OPENROUTER_API_KEY in your env, that
344
+ // is the whole setup. Flip this to change it.
345
+ builtin: ${r&&e.credits},
325
346
  // Let users connect their own provider API keys; flip to false to disable.
326
347
  byok: true,
327
348
  // What every user starts on (their own choice, once made, always wins). Plain
@@ -342,11 +363,18 @@ export const config: AppConfig = {
342
363
  }
343
364
  },
344
365
  desktop: desktopConfig,
345
- // Companion: the OpenCompanion daemon your users install to run their own subscription CLIs for this app. Off by default.
346
- companion: ${f},
366
+ // Runner: the AgentRunner daemon your users install to run their own subscription CLIs for this app. Off by default.
367
+ runner: ${A},
347
368
  // Outward MCP server exposing the capability layer to external agents. Its code ships with every
348
369
  // project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
349
370
  mcpServer: { enabled: ${e.demo?"true":"false"} },
371
+ // Revenue sharing: your answer at init, and yours to change here at any time. On, the daily
372
+ // license heartbeat self-reports an aggregate revenue estimate (MRR, ARR, total and 30-day
373
+ // revenue, active subscriptions). No customer data, but not anonymous either: the figures travel
374
+ // with your domain and app name on your own license, which is what lists YOU on the
375
+ // generatesaas.com MRR leaderboard. Off, nothing revenue-related is computed or sent, and any
376
+ // figures already reported are cleared on the next heartbeat. It gates nothing else in your app.
377
+ revenueSharing: { enabled: ${e.revenueSharing} },
350
378
  seo: {
351
379
  description: "Production-ready SaaS application",
352
380
  foundingDate: "${new Date().getFullYear()}-01-01"
@@ -363,7 +391,7 @@ export const config: AppConfig = {
363
391
  schedules: "/schedules",
364
392
  settingsModels: "/settings/models",
365
393
  settingsIntegrations: "/settings/integrations",
366
- settingsCompanions: "/settings/companions",
394
+ settingsRunners: "/settings/runners",
367
395
  settingsMcp: "/settings/mcp",
368
396
  notifications: "/notifications",
369
397
  admin: "/admin/users"
@@ -378,7 +406,7 @@ export * from "./billing-fields";
378
406
  export * from "./social-providers";
379
407
  export * from "./blog";
380
408
  export * from "./cache";
381
- export * from "./companion";
409
+ export * from "./runner";
382
410
  export * from "./footer";
383
411
  export * from "./i18n";
384
412
  export * from "./landing";
@@ -387,7 +415,20 @@ export * from "./pricing";
387
415
  export * from "./roles";
388
416
  export * from "./section-tabs";
389
417
  export * from "./tenancy";
390
- `,$=Ae(e.projectDir,"packages/config/src/index.ts");await c($,h),await c(Ae(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
418
+ `,$=Vt(e.projectDir,"packages/config/src/index.ts");await l($,f),await l(Vt(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
419
+
420
+ /**
421
+ * Live-chat (support widget) configuration, re-exported by the config index as
422
+ * \`config.support\`. Presence is the switch: add a \`crisp\` or \`chatwoot\` sub-key and that
423
+ * provider's widget loads on every surface - web and desktop. Configure ONE; both keys
424
+ * active would load two widgets.
425
+ *
426
+ * It lives outside the index because the desktop app's vite config imports it under raw
427
+ * Node, which cannot resolve the index's extensionless relative imports. Keep any relative
428
+ * import here type-only.
429
+ */
430
+ export const supportConfig: SupportConfig = ${m};
431
+ `),await l(Vt(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
391
432
  // TypeScript config index reads it directly: the Electron main + renderer bundles,
392
433
  // the CSP policy builder, and the electron-builder packaging config. Edit these
393
434
  // values once to rebrand - they are the same in dev and production, so they live in
@@ -395,29 +436,35 @@ export * from "./tenancy";
395
436
 
396
437
  export const desktopConfig = {
397
438
  enabled: ${e.desktop},
398
- appId: "${u.appId}",
399
- productName: "${u.productName}",
400
- protocol: "${u.protocol}",
439
+ appId: "${g.appId}",
440
+ productName: "${g.productName}",
441
+ protocol: "${g.protocol}",
401
442
  baseUrl: "${n}",
402
- // Name of the app's data folder (created under the OS app-data dir). Where the app
403
- // and its AI agents persist files - logs, gathered data, generated artifacts. Rename
404
- // it freely; it is a plain folder name, not a path.
405
- dataFolder: "data",
406
443
  // Public base URL the release workflow uploads to; electron-updater polls
407
444
  // \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
408
445
  // the per-installer blockmaps, and the stable installer download links live under it.
409
- autoUpdate: { url: "${y}" },
446
+ autoUpdate: { url: "${k}" },
410
447
  // Whether the support live-chat widget you configured in config.support (Crisp,
411
448
  // Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
412
449
  // every surface. Set false to keep live chat on your website only - the app then
413
450
  // mounts no widget and its CSP never names the provider's origins.
414
451
  supportChat: true,
452
+ // Integrations your users connect inside the app by entering their own credentials.
453
+ // Empty by default, which hides the Integrations tab entirely. Everything stays on the
454
+ // user's machine: credentials are encrypted with the OS keychain and never reach your
455
+ // backend.
456
+ // { id, name, description?, kind: "mcp" | "api", credentials: [{ key, label, secret? }], mcp? }
457
+ // An \`mcp\` entry becomes a local MCP server for chats, schedules and terminal sessions
458
+ // once every credential is set; give it \`mcp: { command, args?, env? }\` and reference a
459
+ // credential in an env VALUE as the whole string "{credential:KEY}". An \`api\` entry only
460
+ // stores the credentials - read them from your own main-process code with
461
+ // \`readIntegrationCredentials(id)\`.
462
+ integrations: [],
415
463
  agents: {
416
- // Feature toggles only. Agents run in the app's main process (companion supervision +
417
- // the daemon transport bridge), driven through the @repo/agent-core seam - typed
418
- // TypeScript wiring next to the markdown prompt files you tune.
464
+ // Feature toggles only. Agents run on the agent runtime the app forks from its own
465
+ // binary, supervised by the main process and driven through the @repo/agent-core
466
+ // seam - typed TypeScript wiring next to the markdown prompt files you tune.
419
467
  enabled: ${e.desktop&&e.ai},
420
- modelRegistry: { enabled: true },
421
468
  // Provider ids that ship in this app (catalog ids like "anthropic", "openai").
422
469
  // Omitted here, which ships them ALL; add \`providers: ["anthropic", ...]\` to trim
423
470
  // the catalog to just the ids you list.
@@ -432,11 +479,6 @@ export const desktopConfig = {
432
479
  // Cap how many chat conversations are kept per agent on the user's machine;
433
480
  // creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
434
481
  maxChatsPerAgent: 20,
435
- // Forbid the bundled companion daemon from connecting to your backend (the buyer
436
- // connection lock). Default false: the app is local-first and connecting is an
437
- // OPTIONAL, explicit user action. Set true for a structurally private product - the
438
- // connect surface never renders AND the daemon refuses pairing.
439
- connectionLock: false,
440
482
  // Whether agent work continues after the window closes. OFF by default: the runtime is a
441
483
  // child process of the app and is killed at quit. Turn it on if your product's value
442
484
  // depends on schedules firing while the app is closed; end users then get a
@@ -444,23 +486,8 @@ export const desktopConfig = {
444
486
  background: false
445
487
  }
446
488
  };
447
- `),await c(Ae(e.projectDir,"packages/config/src/tenancy-flags.mjs"),`// Plain-JS tenancy flags. NO env reads, so tooling that cannot import the
448
- // TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
449
- // desktop.mjs pattern. The config index re-exports this as config.tenancy.
450
-
451
- export const tenancyConfig = ${e.multiTenancy?`{
452
- multiTenant: true,
453
- organizationLimit: 5,
454
- billingScope: "${e.demo?"organization":"user"}"
455
- }`:"{ multiTenant: false }"};
456
- `),await c(Ae(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
457
- // the TypeScript config index reads it directly (the Electron main + renderer and
458
- // the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
459
- // index re-exports this as config.support.
460
-
461
- export const supportConfig = ${a};
462
- `),await c(Ae(e.projectDir,"packages/config/src/observability.mjs"),await ys(e.projectDir,e.errorTracking)),e.desktop&&await cs(e.projectDir,y,`${u.protocol}-updater`)}import{join as ws}from"path";function vs(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function ar(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(`
463
- `)}async function un(e){let t=ws(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let $=`import type { PricingConfig } from "@repo/config/types";
489
+ `),e.desktop&&await io(e.projectDir,k,`${g.protocol}-updater`)}import{join as lo}from"path";function po(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function yr(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(`
490
+ `)}async function _n(e){let t=lo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let A=`import type { PricingConfig } from "@repo/config/types";
464
491
 
465
492
  export const pricingConfig: PricingConfig = {
466
493
  defaultPlan: "free",
@@ -489,21 +516,21 @@ export const pricingConfig: PricingConfig = {
489
516
  credits: { enabled: false },
490
517
  products: { enabled: false, items: [] }
491
518
  };
492
- `;await c(t,$);return}let n=e.paymentProvider,o=vs(n),i=e.credits,s=!!e.ai,a=ar({credits:5,rateLimit:100,withCredits:i,...s&&{maxSchedules:3}}),l=ar({credits:10,rateLimit:1e3,withCredits:i,...s&&{maxSchedules:10}}),u=ar({credits:50,rateLimit:5e3,withCredits:i}),y=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
519
+ `;await l(t,A);return}let n=e.paymentProvider,i=po(n),o=e.credits,s=!!e.ai,a=yr({credits:5,rateLimit:100,withCredits:o,...s&&{maxSchedules:3}}),p=yr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxSchedules:10}}),m=yr({credits:50,rateLimit:5e3,withCredits:o}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
493
520
  // !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
494
521
  // !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
495
522
  // !! 20% markup) - and raise prices or creditsPerUsd if they do not.
496
- `;i&&r!=="USD"&&console.warn(`
523
+ `;o&&r!=="USD"&&console.warn(`
497
524
  !! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
498
525
  !! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
499
526
  !! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
500
527
  !! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
501
- `);let f=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
528
+ `);let g=o?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
502
529
  // 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
503
530
  // external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
504
531
  // the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
505
532
  // full utilization runs you at a loss.
506
- ${y} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",h=`import type { PricingConfig } from "@repo/config/types";
533
+ ${w} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",k=`import type { PricingConfig } from "@repo/config/types";
507
534
 
508
535
  export const pricingConfig: PricingConfig = {
509
536
  defaultPlan: "free",
@@ -542,18 +569,18 @@ ${a}
542
569
  ],
543
570
  prices: [
544
571
  {
545
- ${o}
572
+ ${i}
546
573
  interval: "month",
547
574
  amounts: { ${r}: 9 }
548
575
  },
549
576
  {
550
- ${o}
577
+ ${i}
551
578
  interval: "year",
552
579
  amounts: { ${r}: 90 },
553
580
  anchorAmounts: { ${r}: 109 }
554
581
  }
555
582
  ],
556
- ${l}
583
+ ${p}
557
584
  },
558
585
  {
559
586
  id: "pro",
@@ -571,34 +598,35 @@ ${l}
571
598
  ],
572
599
  prices: [
573
600
  {
574
- ${o}
601
+ ${i}
575
602
  interval: "month",
576
603
  amounts: { ${r}: 29 },
577
604
  anchorAmounts: { ${r}: 39 },
578
605
  featured: true
579
606
  },
580
607
  {
581
- ${o}
608
+ ${i}
582
609
  interval: "year",
583
610
  amounts: { ${r}: 290 },
584
611
  anchorAmounts: { ${r}: 349 }
585
612
  }
586
613
  ],
587
- ${u}
614
+ ${m}
588
615
  }
589
616
  ],
590
- ${f},
617
+ ${g},
591
618
  products: {
592
619
  enabled: false,
593
620
  items: []
594
621
  }
595
622
  };
596
- `;await c(t,h)}var ks={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},bs={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function ut(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function mt(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function cr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function fn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}function Ss(e){let{architecture:t,deploymentTarget:r}=e;return t==="fullstack"?r==="vercel"?{frontend:"https://your-app.vercel.app",backend:"https://your-app.vercel.app"}:r==="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 Nt(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function mn(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:o}=fn(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=${n}`,`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("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"&&e.frontend==="nextjs"?i.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):i.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),i.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),i.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),i.push("","# Database"),mt(ut(re[e.databaseProvider].envVars,r),i),i.push("","# Cache"),mt(ut(Se[e.cacheProvider].envVars,r),i),i.push("","# Authentication"),t==="example"&&i.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Nt(i,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),i.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Nt(i,"CONTENT_API_KEY",cr(32),t),i.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Nt(i,"INNGEST_EVENT_KEY",cr(32),t),Nt(i,"INNGEST_SIGNING_KEY",cr(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 s=ks[e.emailProvider];if(s&&(i.push("","# Email"),mt(ut(s,r),i)),e.paymentProvider!=="none"){let a=bs[e.paymentProvider];a&&(i.push("","# Payment"),mt(ut(a,r),i))}return e.demo&&(i.push("","# Captcha (Cloudflare Turnstile)"),mt(ut([{key:"TURNSTILE_SECRET_KEY",comment:"# TODO: Add your Cloudflare Turnstile secret key"}],r),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 (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only provider API key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database."),i.push(""),i.join(`
597
- `)}function Es(e){let{apiUrl:t}=fn(e),r=e.frontend==="nextjs"?"NEXT_PUBLIC_API_URL":"NUXT_PUBLIC_API_URL",n=["# API Configuration",`${r}=${t}`],o=Ss(e);return o&&e.architecture==="separate"&&n.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${r}=${o.backend}`),n.push(""),n.join(`
598
- `)}async function gn(e){let t=Es(e);await c(`${e.projectDir}/.env`,t+`
599
- `+mn(e,"env")),await c(`${e.projectDir}/.env.example`,t+`
600
- `+mn(e,"example"))}import{join as Rs}from"path";async function hn(e){let t=Me(e),r=[],n=[];t.includes("postgres")&&(r.push(` postgres:
623
+ `;await l(t,k)}var uo={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"}]},mo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function et(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function vr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Dn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var fo="https://your-app.example.com/api";function Ft(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function On(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Dn(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?o.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):o.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),o.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),o.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),o.push("","# Database"),et(vt(Te[e.databaseProvider].envVars,r),o),o.push("","# Cache"),et(vt(_e[e.cacheProvider].envVars,r),o),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Ft(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Ft(o,"CONTENT_API_KEY",vr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Ft(o,"INNGEST_EVENT_KEY",vr(32),t),Ft(o,"INNGEST_SIGNING_KEY",vr(32),t),o.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=uo[e.emailProvider];if(s&&(o.push("","# Email"),et(vt(s,r),o)),e.paymentProvider!=="none"){let p=mo[e.paymentProvider];p&&(o.push("","# Payment"),et(vt(p,r),o))}e.demo&&(o.push("","# Captcha (Cloudflare Turnstile)","# @repo/config ships Cloudflare's always-passes TEST site key, and the matching test","# secret is below - so sign-up and sign-in work with no Cloudflare account.","# THE TWO KEYS MUST MATCH: the test site key only validates against the test secret,","# and a real site key only against its own real secret. A mixed pair rejects every","# solved widget. For production set BOTH - your site key in",`# ${yt} (it overrides the committed config value) and its secret here.`,`#${yt}=`),et(vt([{key:"TURNSTILE_SECRET_KEY",defaultValue:In}],r),o)),o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),o.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),o.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),o.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(o.push("","# Error and product reporting (optional)"),et(a,o)),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only provider API key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database."),o.push(""),o.join(`
624
+ `)}var xn="NEXT_PUBLIC_API_URL";function ho(e){let{apiUrl:t}=Dn(e),r=["# API Configuration",`${xn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${xn}=${fo}`),r.push(""),r.join(`
625
+ `)}async function Nn(e){let t=ho(e);await l(`${e.projectDir}/.env`,t+`
626
+ `+On(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
627
+ `+On(e,"example"))}import{join as go}from"path";async function Cn(e){let t=He(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
601
628
  image: postgres:18-alpine
629
+ restart: unless-stopped
602
630
  ports:
603
631
  - "\${POSTGRES_PORT:-5432}:5432"
604
632
  environment:
@@ -614,6 +642,7 @@ ${f},
614
642
  timeout: 5s
615
643
  retries: 5`),n.push(" postgres_data:")),t.includes("redis")&&(r.push(` redis:
616
644
  image: redis:8-alpine
645
+ restart: unless-stopped
617
646
  ports:
618
647
  - "\${REDIS_PORT:-6379}:6379"
619
648
  volumes:
@@ -624,16 +653,32 @@ ${f},
624
653
  timeout: 5s
625
654
  retries: 5`),n.push(" redis_data:")),t.includes("mailpit")&&r.push(` mailpit:
626
655
  image: axllent/mailpit
656
+ restart: unless-stopped
627
657
  ports:
628
658
  - "\${MAILPIT_SMTP_PORT:-1025}:1025"
629
659
  - "\${MAILPIT_UI_PORT:-8025}:8025"
630
660
  environment:
631
661
  MP_SMTP_AUTH_ACCEPT_ANY: 1
632
- MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")&&r.push(` inngest:
662
+ MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let s=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
633
663
  image: inngest/inngest:v1.17.4
664
+ restart: unless-stopped
634
665
  ports:
635
666
  - "\${INNGEST_PORT:-8288}:8288"
636
- command: inngest dev`);let o=`services:
667
+ # \`-u\` is load-bearing, not tuning. Without it \`inngest dev\` AUTO-DISCOVERS, and it scans its own
668
+ # container's localhost - where nothing is listening. It then registers zero apps and silently
669
+ # runs no functions, so on a stock stack NOTHING that goes through Inngest is ever delivered: no
670
+ # verification email, no password reset, no invite, no notification. Signup still returns 200 and
671
+ # the mailbox simply stays empty, which reads as a mail bug rather than a discovery one.
672
+ #
673
+ # \`host.docker.internal\` is how the container reaches the app on the host. It is not built in on
674
+ # Linux, which is what \`extra_hosts\` supplies.
675
+ command: >-
676
+ inngest dev
677
+ -u ${s}
678
+ extra_hosts:
679
+ - "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
680
+
681
+ services:
637
682
  ${r.join(`
638
683
 
639
684
  `)}
@@ -641,46 +686,16 @@ ${r.join(`
641
686
  volumes:
642
687
  ${n.join(`
643
688
  `)}
644
- `),await c(Rs(e.projectDir,"infra/docker-compose.yml"),o)}import{join as Ps}from"path";function Is(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 r=e.frontend==="nextjs"?"Next.js":"Nuxt";if(t.push({type:"node-terminal",request:"launch",name:r,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 n=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:n}})}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 n=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 ${n}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function Ts(e){let t=e.frontend==="nextjs"?"Next.js":"Nuxt",r=[];return e.architecture==="separate"?r.push({name:`Dev (${t} + Backend + Inngest)`,configurations:["Backend",t,"Inngest"]}):r.push({name:`Dev (${t} + Inngest)`,configurations:[t,"Inngest"]}),r}async function yn(e){let t={version:"0.2.0",configurations:Is(e),compounds:Ts(e)};await c(Ps(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
645
- `)}import{join as As}from"path";async function wn(e){if(e.architecture!=="separate")return;await c(As(e.projectDir,"apps/backend/src/index.ts"),`import { serve } from "@hono/node-server";
646
- import app from "@repo/api";
647
- import { closeRedis, env, logger } from "@repo/runtime";
648
-
649
- async function bootstrap() {
650
- const apiServer = serve({
651
- fetch: app.fetch,
652
- port: env.API_PORT,
653
- });
654
- logger.info(\`[API] Listening on port \${env.API_PORT}\`);
655
-
656
- const shutdown = async (signal: string) => {
657
- logger.info("[Backend] Shutting down", { signal });
658
- try {
659
- await closeRedis();
660
- } catch (err) {
661
- logger.error("[Backend] Redis close error during shutdown", err);
662
- }
663
- apiServer.close(() => {
664
- process.exit(0);
665
- });
666
- };
667
-
668
- process.on("SIGINT", () => void shutdown("SIGINT"));
669
- process.on("SIGTERM", () => void shutdown("SIGTERM"));
670
- }
671
-
672
- bootstrap().catch((error) => {
673
- logger.error("[Backend] Fatal error", error);
674
- process.exit(1);
675
- });
676
- `)}import{readFile as Os}from"fs/promises";import{join as xs}from"path";var pr='import { drizzle } from "drizzle-orm/node-postgres";',lr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
677
- export const pool = db.$client;`,Ds={postgres:{importLine:pr,instantiation:lr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
689
+ `),await l(go(e.projectDir,"infra/docker-compose.yml"),o)}import{join as yo}from"path";var bt="Next.js";function vo(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:bt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/electron",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function bo(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${bt} + Backend + Inngest)`,configurations:["Backend",bt,"Inngest"]}):t.push({name:`Dev (${bt} + Inngest)`,configurations:[bt,"Inngest"]}),t}async function $n(e){let t={version:"0.2.0",configurations:vo(e),compounds:bo(e)};await l(yo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
690
+ `)}import{readFile as wo}from"fs/promises";import{join as ko}from"path";var br='import { drizzle } from "drizzle-orm/node-postgres";',wr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
691
+ export const pool = db.$client;`,Eo={postgres:{importLine:br,instantiation:wr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
678
692
  import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
679
693
  export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
680
694
  import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
681
- export const db = drizzle(client, { schema });`}};async function vn(e){let t=xs(e.projectDir,"packages/database/src/index.ts"),r=await Os(t,"utf-8");if(!r.includes(pr)||!r.includes(lr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Ds[e.databaseProvider],o=r.replace(pr,n.importLine).replace(lr,n.instantiation);await c(t,o)}import{join as Ct}from"path";async function kn(e){switch(e.cacheProvider){case"redis":await _s(e),await Ns(e);break;case"upstash":await Cs(e),await $s(e);break}}async function _s(e){await c(Ct(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
695
+ export const db = drizzle(client, { schema });`}};async function Ln(e){let t=ko(e.projectDir,"packages/database/src/index.ts"),r=await wo(t,"utf-8");if(!r.includes(br)||!r.includes(wr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Eo[e.databaseProvider],i=r.replace(br,n.importLine).replace(wr,n.instantiation);await l(t,i)}import{join as Bt}from"path";async function jn(e){switch(e.cacheProvider){case"redis":await So(e),await Ro(e);break;case"upstash":await Ao(e),await Po(e);break}}async function So(e){await l(Bt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
682
696
  import { Redis } from "ioredis";
683
- import { RedisStore, type RedisReply } from "rate-limit-redis";
697
+ import { RedisStore } from "rate-limit-redis";
698
+ import type { RedisReply } from "rate-limit-redis";
684
699
  import { env } from "./env";
685
700
 
686
701
  /** Options for \`redis.cacheSet\`. */
@@ -705,6 +720,8 @@ export interface BoilerplateRedisHelpers {
705
720
  cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean>;
706
721
  /** GET typed as \`string | null\`. (On Upstash this also disables auto-deserialization for consistent string round-trip.) */
707
722
  cacheGet(key: string): Promise<string | null>;
723
+ /** MGET over an array of keys, typed as \`(string | null)[]\` in the order given. The SDKs' native \`mget\` differ in both arity and return typing. */
724
+ cacheMGet(keys: string[]): Promise<(string | null)[]>;
708
725
  /** Iterate keys matching a glob pattern via SCAN. Yields each key as it's discovered. */
709
726
  cacheScan(opts: { match: string; count?: number }): AsyncIterable<string>;
710
727
  /** Run a Lua script via EVAL with explicit key and argument lists (the SDKs' native \`eval\` signatures differ). Returns the script's raw reply. */
@@ -753,6 +770,10 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(ioredis, {
753
770
  async cacheGet(key: string): Promise<string | null> {
754
771
  return ioredis.get(key);
755
772
  },
773
+ async cacheMGet(keys: string[]): Promise<(string | null)[]> {
774
+ if (keys.length === 0) return [];
775
+ return ioredis.mget(...keys);
776
+ },
756
777
  async *cacheScan(opts: { match: string; count?: number }): AsyncIterable<string> {
757
778
  let cursor = "0";
758
779
  do {
@@ -774,10 +795,23 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(ioredis, {
774
795
  * Wraps RedisStore in an adapter exposing only the methods the middleware uses
775
796
  * so we don't need an unsafe cross-package type cast.
776
797
  */
777
- function createLimiterStore(): Store {
798
+ export function createLimiterStore(): Store {
778
799
  const inner = new RedisStore({
779
- sendCommand: (command: string, ...args: string[]) =>
780
- ioredis.call(command, ...args) as Promise<RedisReply>
800
+ sendCommand: (command: string, ...args: string[]) => {
801
+ const pending = ioredis.call(command, ...args) as Promise<RedisReply>;
802
+ // Mark it handled WITHOUT consuming it. A limiter command outlives the request that
803
+ // issued it: the request fail-opens and returns, and nobody is awaiting this promise any
804
+ // more when the cache blips and ioredis rejects the queued command with "Connection is
805
+ // closed". Node treats an unhandled rejection as fatal, so a cache hiccup could take the
806
+ // process down - and during a Docker build or prerender, where Redis is not reachable
807
+ // yet, the fire-and-forget SCRIPT LOAD aborts the build outright.
808
+ //
809
+ // Attaching a catch marks THIS promise handled; returning the same promise leaves the
810
+ // store free to await it and see the error, so nothing is swallowed from a caller that
811
+ // cares.
812
+ pending.catch(() => undefined);
813
+ return pending;
814
+ }
781
815
  });
782
816
  return {
783
817
  init(options) {
@@ -791,8 +825,6 @@ function createLimiterStore(): Store {
791
825
  };
792
826
  }
793
827
 
794
- export const limiterStore: Store = createLimiterStore();
795
-
796
828
  let closed = false;
797
829
 
798
830
  /** Gracefully close the Redis connection; idempotent. Falls back to disconnect() on error. */
@@ -807,7 +839,7 @@ export async function closeRedis() {
807
839
  closed = true;
808
840
  }
809
841
  }
810
- `)}async function Ns(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
842
+ `)}async function Ro(e){await l(Bt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
811
843
  import { redis } from "./redis";
812
844
 
813
845
  export class MutexTimeoutError extends Error {
@@ -817,20 +849,39 @@ export class MutexTimeoutError extends Error {
817
849
  }
818
850
  }
819
851
 
852
+ /** Delay between acquisition attempts. */
853
+ const RETRY_INTERVAL_MS = 500;
854
+
820
855
  /**
821
856
  * Execute \`fn\` while holding a distributed mutex on \`key\`. Backed by
822
857
  * \`redis-semaphore\`, which uses Lua scripts for atomic compare-and-delete
823
- * on release and supports lock refresh for long-running operations.
858
+ * on release and refreshes the lock while \`fn\` runs.
859
+ *
860
+ * \`acquireTimeout\` is honoured; the attempt budget is derived from it so the two cannot disagree.
861
+ *
862
+ * \`onLockLost\` is supplied because the library's default is \`throw err\`, and it fires from the
863
+ * REFRESH TIMER rather than this call stack - so one failed refresh became an unhandled rejection
864
+ * and, by Node's default, killed the process in the middle of whatever the lock was guarding. The
865
+ * handler logs and lets the work finish: crashing is the defect, and failing a completed operation
866
+ * invites a retry of work that already happened.
824
867
  */
825
868
  export async function withMutex<T>(
826
869
  key: string,
827
870
  fn: () => Promise<T>,
828
871
  options?: { lockTimeout?: number; acquireTimeout?: number }
829
872
  ): Promise<T> {
873
+ const acquireTimeout = options?.acquireTimeout ?? 5_000;
830
874
  const mutex = new Mutex(redis, key, {
831
875
  lockTimeout: options?.lockTimeout ?? 10_000,
832
- acquireAttemptsLimit: 10,
833
- retryInterval: 500
876
+ acquireTimeout,
877
+ acquireAttemptsLimit: Math.max(1, Math.ceil(acquireTimeout / RETRY_INTERVAL_MS)),
878
+ retryInterval: RETRY_INTERVAL_MS,
879
+ onLockLost: (error) => {
880
+ console.error(
881
+ \`[Mutex] Lock lost while the critical section was still running - mutual exclusion has lapsed (key: \${key})\`,
882
+ error
883
+ );
884
+ }
834
885
  });
835
886
 
836
887
  const acquired = await mutex.tryAcquire();
@@ -841,10 +892,14 @@ export async function withMutex<T>(
841
892
  try {
842
893
  return await fn();
843
894
  } finally {
844
- await mutex.release();
895
+ // Releasing a lock that was already lost rejects. Letting that escape from \`finally\` would
896
+ // REPLACE whatever the critical section returned or threw.
897
+ await mutex.release().catch((error: unknown) => {
898
+ console.error(\`[Mutex] Failed to release lock (its TTL will expire it) (key: \${key})\`, error);
899
+ });
845
900
  }
846
901
  }
847
- `)}async function Cs(e){await c(Ct(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
902
+ `)}async function Ao(e){await l(Bt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
848
903
  import type { Store } from "hono-rate-limiter";
849
904
  import { env } from "./env";
850
905
 
@@ -870,6 +925,8 @@ export interface BoilerplateRedisHelpers {
870
925
  cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean>;
871
926
  /** GET typed as \`string | null\`. Pairs with \`automaticDeserialization: false\` for consistent string round-trip. */
872
927
  cacheGet(key: string): Promise<string | null>;
928
+ /** MGET over an array of keys, typed as \`(string | null)[]\` in the order given. The SDKs' native \`mget\` differ in both arity and return typing. */
929
+ cacheMGet(keys: string[]): Promise<(string | null)[]>;
873
930
  /** Iterate keys matching a glob pattern via SCAN. Yields each key as it's discovered. */
874
931
  cacheScan(opts: { match: string; count?: number }): AsyncIterable<string>;
875
932
  /** Run a Lua script via EVAL with explicit key and argument lists (the SDKs' native \`eval\` signatures differ). Returns the script's raw reply. */
@@ -914,6 +971,10 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(upstash, {
914
971
  async cacheGet(key: string): Promise<string | null> {
915
972
  return upstash.get<string>(key);
916
973
  },
974
+ async cacheMGet(keys: string[]): Promise<(string | null)[]> {
975
+ if (keys.length === 0) return [];
976
+ return upstash.mget<(string | null)[]>(...keys);
977
+ },
917
978
  async *cacheScan(opts: { match: string; count?: number }): AsyncIterable<string> {
918
979
  let cursor = "0";
919
980
  do {
@@ -927,23 +988,48 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(upstash, {
927
988
  }
928
989
  });
929
990
 
991
+ /**
992
+ * Counter increment, window expiry and TTL read in ONE round trip.
993
+ *
994
+ * Split across separate INCR / PEXPIRE / PTTL calls this is not safe: with the expiry behind an
995
+ * \`if (totalHits === 1)\` guard, a crash or a failed REST call between the INCR and the PEXPIRE
996
+ * leaves the key at 1 with NO expiry. Every later request then increments a counter that never
997
+ * resets and never re-enters the guard, so that client is rate-limited out of the entire API
998
+ * permanently - and PTTL returning -1 reports \`resetTime\` as now, telling them to retry
999
+ * immediately, so they loop on 429s with no diagnostic. \`rate-limit-redis\` runs the equivalent as
1000
+ * one Lua script on the ioredis build; this keeps both cache backends behaving the same.
1001
+ *
1002
+ * The \`ttl < 0\` branch is a self-heal, not belt-and-braces: it re-arms the window for any key that
1003
+ * has already lost its expiry, so a counter stranded by an earlier failure recovers on its next hit
1004
+ * instead of blocking that client forever.
1005
+ */
1006
+ const INCREMENT_SCRIPT = \`
1007
+ local hits = redis.call('INCR', KEYS[1])
1008
+ local ttl = redis.call('PTTL', KEYS[1])
1009
+ if ttl < 0 then
1010
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
1011
+ ttl = tonumber(ARGV[1])
1012
+ end
1013
+ return {hits, ttl}
1014
+ \`;
1015
+
930
1016
  /**
931
1017
  * Rate-limit store compatible with \`hono-rate-limiter\`, backed by Upstash Redis.
932
1018
  * Uses atomic INCR + PEXPIRE for a simple sliding-window counter. Returned as
933
1019
  * a plain object matching \`Store\` so no unsafe type cast is needed.
934
1020
  */
935
- function createLimiterStore(): Store {
1021
+ export function createLimiterStore(): Store {
936
1022
  let windowMs = 60_000;
937
1023
  return {
938
1024
  init(options: { windowMs: number }): void {
939
1025
  windowMs = options.windowMs;
940
1026
  },
941
1027
  async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {
942
- const totalHits = await upstash.incr(key);
943
- if (totalHits === 1) {
944
- await upstash.pexpire(key, windowMs);
945
- }
946
- const ttl = await upstash.pttl(key);
1028
+ const [totalHits, ttl] = await upstash.eval<[number], [number, number]>(
1029
+ INCREMENT_SCRIPT,
1030
+ [key],
1031
+ [windowMs]
1032
+ );
947
1033
  return {
948
1034
  totalHits,
949
1035
  resetTime: new Date(Date.now() + Math.max(0, ttl))
@@ -958,11 +1044,9 @@ function createLimiterStore(): Store {
958
1044
  };
959
1045
  }
960
1046
 
961
- export const limiterStore: Store = createLimiterStore();
962
-
963
1047
  /** No persistent connection to close with Upstash REST. */
964
1048
  export async function closeRedis(): Promise<void> {}
965
- `)}async function $s(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
1049
+ `)}async function Po(e){await l(Bt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
966
1050
  import { redis } from "./redis";
967
1051
 
968
1052
  export class MutexTimeoutError extends Error {
@@ -972,12 +1056,23 @@ export class MutexTimeoutError extends Error {
972
1056
  }
973
1057
  }
974
1058
 
1059
+ /** Fraction of the lease after which the lock is renewed, matching redis-semaphore's default. */
1060
+ const REFRESH_INTERVAL_COEF = 0.8;
1061
+
975
1062
  /**
976
1063
  * Execute \`fn\` while holding a distributed mutex on \`key\`. Backed by
977
1064
  * \`@upstash/lock\`, Upstash's official distributed-lock library - uses
978
- * Lua EVAL for atomic compare-and-delete on release (no TOCTOU race) and
979
- * exposes \`extend()\` for long-running operations (not wired here; pick a
980
- * generous \`lockTimeout\` if you need it).
1065
+ * Lua EVAL for atomic compare-and-delete on release (no TOCTOU race).
1066
+ *
1067
+ * THE LEASE IS RENEWED WHILE \`fn\` RUNS. Without that the lock simply expires after
1068
+ * \`lockTimeout\` and a second caller acquires it while the first is still inside its critical
1069
+ * section - so the mutex guarding every credit and plan mutation stops guarding anything, silently,
1070
+ * on exactly the long operations that need it most. The ioredis backend gets this for free from
1071
+ * redis-semaphore; wiring it here keeps both cache backends behaving the same, which matters because
1072
+ * a buyer picks one and never sees the other.
1073
+ *
1074
+ * A failed renewal is LOGGED, not thrown: the timer has no caller to reject to, and turning a
1075
+ * completed operation into a failure invites a retry of work that already happened.
981
1076
  */
982
1077
  export async function withMutex<T>(
983
1078
  key: string,
@@ -1001,28 +1096,177 @@ export async function withMutex<T>(
1001
1096
  throw new MutexTimeoutError(key);
1002
1097
  }
1003
1098
 
1099
+ const refresh = setInterval(() => {
1100
+ void lock
1101
+ .extend(lockTimeout)
1102
+ .then((extended) => {
1103
+ if (!extended) {
1104
+ console.error(
1105
+ \`[Mutex] Lock lost while the critical section was still running - mutual exclusion has lapsed (key: \${key})\`
1106
+ );
1107
+ }
1108
+ })
1109
+ .catch((error: unknown) => {
1110
+ console.error(\`[Mutex] Failed to renew lock (key: \${key})\`, error);
1111
+ });
1112
+ }, Math.max(1, Math.round(lockTimeout * REFRESH_INTERVAL_COEF)));
1113
+ // Never let the renewal timer hold the process open on its own.
1114
+ refresh.unref?.();
1115
+
1004
1116
  try {
1005
1117
  return await fn();
1006
1118
  } finally {
1007
- await lock.release();
1119
+ clearInterval(refresh);
1120
+ // Releasing a lock that already expired rejects. Letting that escape from \`finally\` would
1121
+ // REPLACE whatever the critical section returned or threw.
1122
+ await lock.release().catch((error: unknown) => {
1123
+ console.error(\`[Mutex] Failed to release lock (its lease will expire it) (key: \${key})\`, error);
1124
+ });
1008
1125
  }
1009
1126
  }
1010
- `)}import{readFile as js}from"fs/promises";import{join as Ls}from"path";var bn=" REDIS_URL: z.string(),",Ms=` UPSTASH_REDIS_REST_URL: z.string(),
1011
- UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Sn(e){let t=Ls(e.projectDir,"packages/runtime/src/env.ts"),r=await js(t,"utf-8");if(!r.includes(bn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(bn,Ms):r;await c(t,n)}import{readFile as Us}from"fs/promises";import{join as L}from"path";var $t={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Oe(e){let t=await Us(e,"utf-8");return JSON.parse(t)}async function xe(e,t){await c(e,JSON.stringify(t,null," ")+`
1012
- `)}function Ye(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function Je(e,t,r,n=!1){let o=n?"devDependencies":"dependencies";e[o]||(e[o]={}),e[o][t]=r}async function En(e){await Fs(e),await Vs(e),await Gs(e),await Hs(e),await Ys(e),e.frontend==="nextjs"?await Xs(e):await Ws(e)}async function Fs(e){let t=L(e.projectDir,"packages/api/package.json"),r=await Oe(t);Ye(r,["sharp","@types/sharp"]),await xe(t,r)}async function Vs(e){let t=L(e.projectDir,"packages/runtime/package.json"),r=await Oe(t);e.cacheProvider==="upstash"&&(Ye(r,["ioredis","rate-limit-redis","redis-semaphore"]),Je(r,"@upstash/redis",$t["@upstash/redis"]),Je(r,"@upstash/lock",$t["@upstash/lock"])),await xe(t,r)}var dr={none:[],sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},Bs=["@sentry/electron"],Ks=[...dr.sentry,...dr.posthog];async function Gs(e){let t=L(e.projectDir,"packages/observability/package.json"),r=await Oe(t),n=new Set(dr[e.errorTracking]);if(!e.desktop)for(let o of Bs)n.delete(o);Ye(r,Ks.filter(o=>!n.has(o))),await xe(t,r)}async function Hs(e){let t=L(e.projectDir,"packages/database/package.json"),r=await Oe(t);e.databaseProvider==="neon"?(Ye(r,["pg","@types/pg"]),Je(r,"@neondatabase/serverless",$t["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ye(r,["pg","@types/pg"]),Je(r,"postgres",$t.postgres)),await xe(t,r)}async function Ys(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/backend/package.json"),r=await Oe(t);e.deploymentTarget!=="node"&&Ye(r,["@hono/node-server"]),await xe(t,r)}var Js=["server/routes/.well-known/oauth-authorization-server/[...path].ts","server/routes/.well-known/oauth-protected-resource/[...path].ts","server/routes/.well-known/oauth-authorization-server.ts","server/routes/.well-known/oauth-protected-resource.ts"],zs=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Ws(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/web-nuxt");await He(L(t,"server/api/[...paths].ts"),t);for(let i of Js)await He(L(t,i),t);let r=L(t,"package.json"),n=await Oe(r),o=n.dependencies?.["@repo/api"];o&&(delete n.dependencies?.["@repo/api"],Je(n,"@repo/api",o,!0)),await xe(r,n)}var qs=["instrumentation.ts","tests/instrumentation.test.ts"];async function Xs(e){if(e.architecture!=="separate")return;let t=L(e.projectDir,"apps/web-next");await He(L(t,"app/api/[[...rest]]/route.ts"),t);for(let i of zs)await He(L(t,i),t);for(let i of qs)await He(L(t,i),t);let r=L(t,"package.json"),n=await Oe(r),o=n.dependencies?.["@repo/api"];o&&(delete n.dependencies?.["@repo/api"],Je(n,"@repo/api",o,!0)),await xe(r,n)}import{readFile as Pn}from"fs/promises";import{join as In}from"path";async function Tn(e){let t=In(e.projectDir,"turbo.json"),r;try{r=await Pn(t,"utf-8")}catch{return}let n=JSON.parse(r),o=n.tasks?.build;if(!o)return;let i=e.frontend==="nextjs"?"NUXT_PUBLIC_*":"NEXT_PUBLIC_*",s=e.frontend==="nextjs"?new Set([".nuxt/**",".output/**"]):new Set([".next/**","!.next/cache/**"]),a=!1;if(Array.isArray(o.env)){let l=o.env.filter(u=>u!==i);l.length!==o.env.length&&(o.env=l,a=!0)}if(Array.isArray(o.outputs)){let l=o.outputs.filter(u=>!s.has(u));l.length!==o.outputs.length&&(o.outputs=l,a=!0)}a&&await c(t,JSON.stringify(n,null," ")+`
1013
- `)}var Zs=["base.json","node.json","next.json"],Rn="GenerateSaaS ";async function An(e){if(!e.demo)for(let t of Zs){let r=In(e.projectDir,"tooling/typescript",t),n;try{n=await Pn(r,"utf-8")}catch{continue}let o=JSON.parse(n);typeof o.display!="string"||!o.display.startsWith(Rn)||(o.display=o.display.slice(Rn.length),await c(r,JSON.stringify(o,null," ")+`
1014
- `))}}import{readFile as Qs,rm as ea}from"fs/promises";import{existsSync as On}from"fs";import{join as xn}from"path";async function Dn(e){if(e.frontend==="nuxt")return;let t=xn(e.projectDir,"packages/i18n/package.json");if(!On(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let r=JSON.parse(await Qs(t,"utf-8")),n=!!(r.exports?.["./module"]??r.exports?.["./nuxt"]),o=!1;if(r.exports)for(let s of["./module","./nuxt"])s in r.exports&&(delete r.exports[s],o=!0);r.devDependencies&&"@nuxt/kit"in r.devDependencies&&(delete r.devDependencies["@nuxt/kit"],o=!0),o&&await c(t,JSON.stringify(r,null," ")+`
1015
- `);let i=xn(e.projectDir,"packages/i18n/nuxt");if(n&&!On(i))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${i} is missing - did the i18n Nuxt module move?`);await ea(i,{recursive:!0,force:!0})}import{readFile as Nn,rm as ta}from"fs/promises";import{join as jt}from"path";async function Cn(e){e.cacheProvider==="upstash"&&await Promise.all([_n(jt(e.projectDir,"packages/runtime/tests/setup.ts")),_n(jt(e.projectDir,"packages/mail/tests/setup.ts")),ra(e.projectDir),ta(jt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function _n(e){let t;try{t=await Nn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1127
+ `)}import{readFile as Io}from"fs/promises";import{join as To}from"path";var Mn=" REDIS_URL: z.string(),",_o=` UPSTASH_REDIS_REST_URL: z.string(),
1128
+ UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Un(e){let t=To(e.projectDir,"packages/runtime/src/env.ts"),r=await Io(t,"utf-8");if(!r.includes(Mn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Mn,_o):r;await l(t,n)}import{readFile as Vn}from"fs/promises";import{join as ee}from"path";var Kt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function tt(e){let t=await Vn(e,"utf-8");return JSON.parse(t)}async function rt(e,t){let r=/\n([\t ]+)"/.exec(await Vn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
1129
+ `)}function Ce(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function wt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Fn(e){await Oo(e),await xo(e),await Do(e),await $o(e),await Lo(e),await Vo(e)}async function Oo(e){let t=ee(e.projectDir,"packages/api/package.json"),r=await tt(t);Ce(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ce(r,["ioredis"]),await rt(t,r)}async function xo(e){let t=ee(e.projectDir,"apps/web/package.json"),r=await tt(t);Ce(r,["@upstash/ratelimit","@upstash/redis"]),await rt(t,r)}async function Do(e){let t=ee(e.projectDir,"packages/runtime/package.json"),r=await tt(t);e.cacheProvider==="upstash"&&(Ce(r,["ioredis","rate-limit-redis","redis-semaphore"]),wt(r,"@upstash/redis",Kt["@upstash/redis"]),wt(r,"@upstash/lock",Kt["@upstash/lock"])),await rt(t,r)}var kr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},No=["@sentry/electron"],Co=[...kr.sentry,...kr.posthog];async function $o(e){let t=ee(e.projectDir,"packages/observability/package.json"),r=await tt(t),n=new Set(e.observability.flatMap(i=>kr[i]));if(!e.desktop)for(let i of No)n.delete(i);Ce(r,Co.filter(i=>!n.has(i))),await rt(t,r)}async function Lo(e){let t=ee(e.projectDir,"packages/database/package.json"),r=await tt(t);e.databaseProvider==="neon"?(Ce(r,["pg","@types/pg"]),wt(r,"@neondatabase/serverless",Kt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ce(r,["pg","@types/pg"]),wt(r,"postgres",Kt.postgres)),await rt(t,r)}var jo=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Mo(e){let t=await tt(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],wt(t,"@repo/api",r,!0),await rt(e,t))}var Uo=["instrumentation.ts","tests/instrumentation.test.ts"];async function Vo(e){if(e.architecture!=="separate")return;let t=ee(e.projectDir,"apps/web");await Mt(ee(t,"app/api/[[...rest]]/route.ts"),t);for(let r of jo)await Mt(ee(t,r),t);for(let r of Uo)await Mt(ee(t,r),t);await Mo(ee(t,"package.json"))}import{readFile as Fo}from"fs/promises";import{join as Bo}from"path";var Ko=["base.json","node.json","next.json"],Bn="GenerateSaaS ";async function Kn(e){if(!e.demo)for(let t of Ko){let r=Bo(e.projectDir,"tooling/typescript",t),n;try{n=await Fo(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Bn)||(i.display=i.display.slice(Bn.length),await l(r,JSON.stringify(i,null," ")+`
1130
+ `))}}import{readFile as Hn,rm as Go}from"fs/promises";import{join as kt}from"path";async function Yn(e){e.cacheProvider==="upstash"&&(await Promise.all([Gn(kt(e.projectDir,"packages/runtime/tests/setup.ts")),Gn(kt(e.projectDir,"packages/mail/tests/setup.ts")),Yo(e.projectDir),Go(kt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Ho(e.projectDir))}async function Ho(e){await l(kt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
1131
+
1132
+ /**
1133
+ * Regression guards for the Upstash-backed cache layer in src/redis.ts.
1134
+ *
1135
+ * EVERYTHING cache-backend-specific belongs in THIS file, so the rest of the suite never has to
1136
+ * know which client is underneath. \`@upstash/redis\` is mocked at the module boundary by an
1137
+ * in-memory fake, so the suite needs no network and no Upstash account.
1138
+ *
1139
+ * The contract pinned here - TTL units, the NX guard, verbatim string round-trip, multi-key reads
1140
+ * and full SCAN pagination - is what every credit and plan mutation depends on through the mutex
1141
+ * and the rate limiter.
1142
+ */
1143
+
1144
+ interface FakeEntry {
1145
+ value: string;
1146
+ /** Absolute expiry (ms epoch), or null when the key has no TTL. */
1147
+ expiresAt: number | null;
1148
+ }
1149
+
1150
+ const store = new Map<string, FakeEntry>();
1151
+
1152
+ /** Read a key, honouring TTL expiry. */
1153
+ function live(key: string): FakeEntry | null {
1154
+ const entry = store.get(key);
1155
+ if (!entry) return null;
1156
+ if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
1157
+ store.delete(key);
1158
+ return null;
1159
+ }
1160
+ return entry;
1161
+ }
1162
+
1163
+ vi.mock("@upstash/redis", () => {
1164
+ class Redis {
1165
+ async get(key: string): Promise<string | null> {
1166
+ return live(key)?.value ?? null;
1167
+ }
1168
+ async mget(...keys: string[]): Promise<(string | null)[]> {
1169
+ return keys.map((key) => live(key)?.value ?? null);
1170
+ }
1171
+ async set(key: string, value: string, opts?: Record<string, unknown>): Promise<"OK" | null> {
1172
+ if (opts?.nx === true && live(key)) return null;
1173
+ const ttlMs =
1174
+ typeof opts?.px === "number" ? opts.px : typeof opts?.ex === "number" ? opts.ex * 1000 : null;
1175
+ store.set(key, { value, expiresAt: ttlMs === null ? null : Date.now() + ttlMs });
1176
+ return "OK";
1177
+ }
1178
+ async scan(cursor: string, opts: { match: string }): Promise<[string, string[]]> {
1179
+ const pattern = new RegExp(\`^\${opts.match.split("*").join(".*")}$\`);
1180
+ const keys = [...store.keys()].filter((key) => live(key) && pattern.test(key));
1181
+ // One key per page, so a consumer that stops at the first page fails here.
1182
+ const index = Number(cursor);
1183
+ const next = index + 1 >= keys.length ? "0" : String(index + 1);
1184
+ return [next, keys.slice(index, index + 1)];
1185
+ }
1186
+ async eval(): Promise<unknown> {
1187
+ return null;
1188
+ }
1189
+ }
1190
+ return { Redis };
1191
+ });
1192
+
1193
+ // No env mock: \`tests/setup.ts\` already supplies UPSTASH_REDIS_REST_URL / _TOKEN as process-env
1194
+ // defaults, which is what src/env.ts validates at module load.
1195
+ const { redis } = await import("../src/redis");
1196
+
1197
+ beforeEach(() => {
1198
+ store.clear();
1199
+ });
1200
+
1201
+ describe("cacheSet / cacheGet", () => {
1202
+ it("round-trips a value verbatim", async () => {
1203
+ await redis.cacheSet("k", "raw-string");
1204
+ await expect(redis.cacheGet("k")).resolves.toBe("raw-string");
1205
+ });
1206
+
1207
+ it("reports a miss as null rather than undefined", async () => {
1208
+ await expect(redis.cacheGet("absent")).resolves.toBeNull();
1209
+ });
1210
+
1211
+ it("treats ttlSeconds as SECONDS and ttlMilliseconds as MILLISECONDS", async () => {
1212
+ await redis.cacheSet("s", "v", { ttlSeconds: 60 });
1213
+ await redis.cacheSet("m", "v", { ttlMilliseconds: 60 });
1214
+
1215
+ const seconds = store.get("s")?.expiresAt ?? 0;
1216
+ const millis = store.get("m")?.expiresAt ?? 0;
1217
+ // A unit mix-up here expires a lock 1000x early or holds it 1000x too long.
1218
+ expect(seconds - millis).toBeGreaterThan(50_000);
1219
+ });
1220
+
1221
+ it("honours ifNotExists, so two holders can never both win", async () => {
1222
+ await expect(redis.cacheSet("lock", "first", { ifNotExists: true })).resolves.toBe(true);
1223
+ await expect(redis.cacheSet("lock", "second", { ifNotExists: true })).resolves.toBe(false);
1224
+ await expect(redis.cacheGet("lock")).resolves.toBe("first");
1225
+ });
1226
+ });
1227
+
1228
+ describe("cacheMGet", () => {
1229
+ it("returns one entry per key, in the order given, with null for misses", async () => {
1230
+ await redis.cacheSet("a", "A");
1231
+ await redis.cacheSet("c", "C");
1232
+
1233
+ await expect(redis.cacheMGet(["a", "missing", "c"])).resolves.toEqual(["A", null, "C"]);
1234
+ });
1235
+
1236
+ it("round-trips an empty key list without touching Redis", async () => {
1237
+ await expect(redis.cacheMGet([])).resolves.toEqual([]);
1238
+ });
1239
+ });
1240
+
1241
+ describe("cacheScan", () => {
1242
+ it("walks EVERY page, not just the first", async () => {
1243
+ for (const key of ["scan:1", "scan:2", "scan:3"]) await redis.cacheSet(key, "v");
1244
+
1245
+ const seen: string[] = [];
1246
+ for await (const key of redis.cacheScan({ match: "scan:*" })) seen.push(key);
1247
+
1248
+ // The fake pages one key at a time, so stopping at the first cursor loses two keys.
1249
+ expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
1250
+ });
1251
+ });
1252
+ `)}async function Gn(e){let t;try{t=await Hn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1016
1253
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1017
- `);r!==t&&await c(e,r)}async function ra(e){let t=jt(e,"packages/api/tests/setup.ts"),r;try{r=await Nn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1254
+ `);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function Yo(e){let t=kt(e,"packages/api/tests/setup.ts"),r;try{r=await Hn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1018
1255
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1019
1256
  `),n=n.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
1020
1257
  UPSTASH_REDIS_REST_TOKEN: "test-token",
1021
1258
  `),n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`vi.mock("@upstash/redis", () => {
1022
1259
  class Redis {
1023
1260
  get = vi.fn().mockResolvedValue(null);
1261
+ mget = vi.fn().mockResolvedValue([]);
1024
1262
  set = vi.fn().mockResolvedValue("OK");
1025
1263
  del = vi.fn().mockResolvedValue(0);
1264
+ incr = vi.fn().mockResolvedValue(1);
1265
+ decr = vi.fn().mockResolvedValue(0);
1266
+ expire = vi.fn().mockResolvedValue(1);
1267
+ pexpire = vi.fn().mockResolvedValue(1);
1268
+ pttl = vi.fn().mockResolvedValue(-1);
1269
+ scan = vi.fn().mockResolvedValue(["0", []]);
1026
1270
  eval = vi.fn().mockResolvedValue(null);
1027
1271
  }
1028
1272
  return { Redis };
@@ -1030,31 +1274,25 @@ export async function withMutex<T>(
1030
1274
  vi.mock("@upstash/lock", () => {
1031
1275
  class Lock {
1032
1276
  acquire = vi.fn().mockResolvedValue(true);
1033
- release = vi.fn().mockResolvedValue(undefined);
1277
+ extend = vi.fn().mockResolvedValue(true);
1278
+ release = vi.fn().mockResolvedValue(true);
1034
1279
  }
1035
1280
  return { Lock };
1036
1281
  });
1037
1282
 
1038
- $1`),n!==r&&await c(t,n)}import{readdir as Ln,readFile as Lt,rm as F}from"fs/promises";import{join as R}from"path";import{readFile as jn,rm as T}from"fs/promises";import{join as S}from"path";import{readFile as ft}from"fs/promises";import{join as gt}from"path";async function $n(e,t){let r=gt(e,"packages/api/src/routes/internal/index.ts");await c(r,ye(await ft(r,"utf-8"),"internal router","companion",t)),await Zr(r);let n=gt(e,"packages/api/src/ai/schedule-runner.ts");await c(n,ye(await ft(n,"utf-8"),"schedule-runner.ts","companion",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let a=gt(e,s);await c(a,ye(await ft(a,"utf-8"),s,"companion",t))}let o=gt(e,"packages/api/src/ai/settings-store.ts");await c(o,ye(await ft(o,"utf-8"),"settings-store.ts","companion",t));let i=gt(e,"packages/api/tests/ai/settings-store.test.ts");await c(i,ye(await ft(i,"utf-8"),"settings-store.test.ts","companion",t))}async function ur(e){if(e.companion)return;let t=e.projectDir,r="stripCompanion";await T(S(t,"packages/api/src/relay"),{recursive:!0}),await T(S(t,"packages/api/src/companion"),{recursive:!0}),await T(S(t,"packages/api/src/ai/companion-model.ts")),await T(S(t,"packages/api/src/ai/companion-routing.ts")),await T(S(t,"packages/api/tests/relay"),{recursive:!0}),await T(S(t,"packages/api/tests/companion"),{recursive:!0}),await T(S(t,"packages/api/src/routes/internal/companion.ts")),await T(S(t,"packages/api/src/routes/internal/companion-transport.ts")),await T(S(t,"packages/api/src/routes/internal/companion-limits.ts")),await T(S(t,"packages/api/tests/routes/companion.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-harness.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-connect.test.ts")),await T(S(t,"packages/api/tests/routes/companion-transport-events.test.ts")),await T(S(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await T(S(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await T(S(t,"packages/api/tests/ai/companion-model.test.ts")),await T(S(t,"packages/api/tests/unit/companion-offline-routing.test.ts")),await T(S(t,"packages/api/tests/unit/companion-offline-interactive.test.ts")),await T(S(t,"packages/api/tests/ai/companion-chat.test.ts")),await T(S(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await T(S(t,"packages/api/tests/helpers/redis-mock.ts"));let n=S(t,"packages/api/package.json"),o=JSON.parse(await jn(n,"utf-8"));if(!o.exports?.["./companion"])throw new Error(`${r}: expected packages/api/package.json to carry the ./companion export`);delete o.exports["./companion"],await Dt(n,o," ",r),await $n(t,r);let i=_t(e);await Xr(t,i,"companion",[`/${i}/companion`],r,"Companions"),await j(S(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",r),await j(S(t,`docs/${i}/caching.mdx`),` - see [per-companion request budgets](/${i}/companion/install#per-companion-request-budgets)`,"","caching.mdx companion budgets link",r);let s=S(t,`docs/${i}/configuration.mdx`),a="| `companion.enabled` |",l=(await jn(s,"utf-8")).split(`
1039
- `).find(u=>u.startsWith(a));if(l===void 0)throw new Error(`${r}: expected the ${i} configuration.mdx \`companion.enabled\` row (boilerplate drift).`);await j(s,`${l}
1040
- `,"","configuration.mdx companion config-table row",r)}var na=new Set(["ci.yml","desktop-release.yml"]),oa={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"]},ia=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:build","check-types:scripts","ai:parity","companion:export","companion:verify","companion:publish"];async function Mn(e){let t=R(e.projectDir,".github/workflows"),r=await Ln(t).catch(()=>[]);for(let n of r)na.has(n)||await F(R(t,n),{recursive:!0,force:!0})}async function sa(e,t){let r=R(e,"package.json"),n=JSON.parse(await Lt(r,"utf-8"));if(!n.scripts)return!1;let o=!1;for(let i of t)i in n.scripts&&(delete n.scripts[i],o=!0);return o&&await c(r,JSON.stringify(n,null," ")+`
1041
- `),o}async function Un(e){await sa(e.projectDir,[...ia])}async function Fn(e){let t=R(e.projectDir,"package.json"),r=await Lt(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await c(t,JSON.stringify(n,null," ")+`
1042
- `))}async function Vn(e){let t=R(e.projectDir,"package.json"),r=JSON.parse(await Lt(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await c(t,JSON.stringify(r,null," ")+`
1043
- `)}async function Bn(e){let t=e.frontend==="nextjs"?"apps/web-nuxt":"apps/web-next";await F(R(e.projectDir,t),{recursive:!0,force:!0})}async function Kn(e){e.docs||await F(R(e.projectDir,"apps/docs"),{recursive:!0})}async function Gn(e){let t=e.frontend==="nextjs"?"docs/nuxt":"docs/next";await F(R(e.projectDir,t),{recursive:!0,force:!0}),await F(R(e.projectDir,"docs/index.mdx")),e.desktop||await F(R(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await aa(e)}async function aa(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=_t(e),o=R(t,`docs/${n}/configuration.mdx`),i=e.desktop,s=e.desktop&&e.ai;e.desktop||(await j(o,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await j(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",r),await j(R(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r)),i||await j(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). Every desktop project ships the agent runtime the app forks, so flipping the flag on turns the screens back on with no regeneration - what your AI option changes is generated content (the config values, the pricing plan's AI fields), not whether the engine is there. See [desktop AI](/desktop/ai).\n\n","","configuration.mdx desktop-AI paragraph",r),!s&&e.companion&&(await j(R(t,`docs/${n}/companion/index.mdx`),`## Set up from the desktop app
1044
-
1045
- 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).
1046
-
1047
- `,"","companion index.mdx desktop-setup section",r),await j(R(t,`docs/${n}/companion/terminal.mdx`),`## In the desktop app
1048
-
1049
- 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).
1050
-
1051
- `,"","companion terminal.mdx desktop-panel section",r))}async function Hn(e){if(e.desktop)return;await F(R(e.projectDir,"apps/electron"),{recursive:!0});let t=R(e.projectDir,"packages/i18n/translations");for(let o of await Ln(t,{withFileTypes:!0}))o.isDirectory()&&await F(R(t,o.name,"desktop.json"),{force:!0});await F(R(e.projectDir,".github/workflows/desktop-release.yml"));for(let o of oa[e.frontend])await F(R(e.projectDir,o),{recursive:!0});await F(R(e.projectDir,"packages/utils/src/desktop-download.ts")),await F(R(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=R(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await Lt(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Dt(r,n," ","stripDesktopApp")}function ca(e){return e.desktop}async function Yn(e){ca(e)||await F(R(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as pa}from"fs/promises";import{join as la}from"path";var Jn=`on:
1283
+ $1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let o of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(o))throw new Error(`pruneCacheTests: ${t} still contains ${o} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as Wo}from"fs/promises";var qo=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,zo=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Wn=32;function Jo(e){let t=e.lastIndexOf(".");return t>=0&&zo.has(e.slice(t))}async function Xo(e){let t=await Wo(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(qo,"");r!==t&&await l(e,r)}async function qn(e){let t=await ue(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Jo);for(let r=0;r<t.length;r+=Wn)await Promise.all(t.slice(r,r+Wn).map(Xo))}import{readdir as Xn,readFile as nt,rm as te}from"fs/promises";import{join as I}from"path";import{readFile as Jn,rm as P}from"fs/promises";import{join as E}from"path";import{readFile as Et}from"fs/promises";import{join as St}from"path";async function zn(e,t){let r=St(e,"packages/api/src/routes/internal/index.ts");await l(r,Z(await Et(r,"utf-8"),"internal router","runner",t)),await un(r);let n=St(e,"packages/api/src/ai/schedule-runner.ts");await l(n,Z(await Et(n,"utf-8"),"schedule-runner.ts","runner",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let a=St(e,s);await l(a,Z(await Et(a,"utf-8"),s,"runner",t))}let i=St(e,"packages/api/src/ai/settings-store.ts");await l(i,Z(await Et(i,"utf-8"),"settings-store.ts","runner",t));let o=St(e,"packages/api/tests/ai/settings-store.test.ts");await l(o,Z(await Et(o,"utf-8"),"settings-store.test.ts","runner",t))}async function Er(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await P(E(t,"packages/api/src/relay"),{recursive:!0}),await P(E(t,"packages/api/src/runner"),{recursive:!0}),await P(E(t,"packages/api/src/ai/runner-model.ts")),await P(E(t,"packages/api/src/ai/runner-routing.ts")),await P(E(t,"packages/api/tests/relay"),{recursive:!0}),await P(E(t,"packages/api/tests/runner"),{recursive:!0}),await P(E(t,"packages/api/src/routes/internal/runner.ts")),await P(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await P(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await P(E(t,"packages/api/tests/routes/runner.test.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await P(E(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await P(E(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await P(E(t,"packages/api/tests/ai/runner-model.test.ts")),await P(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await P(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await P(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await P(E(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await P(E(t,"packages/api/tests/helpers/redis-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Jn(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Ze(n,i," ",r),await zn(t,r),await dn(t,"runner",["/runner"],r,"Runners"),await Y(E(t,"docs/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await Y(E(t,"docs/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=E(t,"docs/configuration.mdx"),s="| `runner.enabled` |",a=(await Jn(o,"utf-8")).split(`
1284
+ `).find(p=>p.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await Y(o,`${a}
1285
+ `,"","configuration.mdx runner config-table row",r)}var Zo=new Set(["ci.yml","desktop-release.yml"]),Qo=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],ea=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function Zn(e){let t=I(e.projectDir,".github/workflows"),r=await Xn(t).catch(()=>[]);for(let n of r)Zo.has(n)||await te(I(t,n),{recursive:!0,force:!0})}async function ta(e,t){let r=I(e,"package.json"),n=JSON.parse(await nt(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await nt(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,o)+`
1286
+ `)}async function Qn(e){await ta(e.projectDir,[...ea])}async function ei(e){let t=I(e.projectDir,"package.json"),r=await nt(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(n,null," ")+`
1287
+ `))}async function ti(e){let t=I(e.projectDir,"package.json"),r=JSON.parse(await nt(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await l(t,JSON.stringify(r,null," ")+`
1288
+ `)}async function ri(e){e.docs||await te(I(e.projectDir,"apps/docs"),{recursive:!0})}async function ni(e){e.desktop||await te(I(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await ra(e)}async function Gt(e,t,r,n){await l(e,Z(await nt(e,"utf-8"),t,r,n))}async function ra(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=I(t,"docs/configuration.mdx"),i=e.desktop,o=e.desktop&&e.ai;e.desktop||(await Y(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await Gt(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await Y(I(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await Y(I(t,"docs/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
1289
+ `,"","index.mdx desktop app card",r)),i||await Gt(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),!o&&e.runner&&(await Gt(I(t,"docs/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await Gt(I(t,"docs/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ii(e){if(e.desktop)return;await te(I(e.projectDir,"apps/electron"),{recursive:!0});let t=I(e.projectDir,"packages/i18n/translations");for(let i of await Xn(t,{withFileTypes:!0}))i.isDirectory()&&await te(I(t,i.name,"desktop.json"),{force:!0});await te(I(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of Qo)await te(I(e.projectDir,i),{recursive:!0});await te(I(e.projectDir,"packages/utils/src/desktop-download.ts")),await te(I(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=I(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await nt(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ze(r,n," ","stripDesktopApp")}function na(e){return e.desktop}async function si(e){na(e)||await te(I(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ia}from"fs/promises";import{join as sa}from"path";var oi=`on:
1052
1290
  workflow_run:
1053
1291
  workflows: ["Tag Release"]
1054
1292
  branches: [main]
1055
1293
  types: [completed]
1056
- workflow_dispatch:`,da=`on:
1057
- workflow_dispatch:`;async function zn(e){if(!e.desktop)return;let t=la(e.projectDir,".github/workflows/desktop-release.yml"),r=await pa(t,"utf8");if(!r.includes(Jn))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await c(t,r.replace(Jn,da))}import{join as ua}from"path";async function Wn(e){let t=ma(e);await c(ua(e.projectDir,".github/workflows/ci.yml"),t)}function ma(e){let t=re[e.databaseProvider].managed,r=e.cacheProvider==="upstash",n=e.frontend==="nuxt",o=t?"":` services:
1294
+ workflow_dispatch:`,oa=`on:
1295
+ workflow_dispatch:`;async function ai(e){if(!e.desktop)return;let t=sa(e.projectDir,".github/workflows/desktop-release.yml"),r=await ia(t,"utf8");if(!r.includes(oi))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(oi,oa))}import{join as aa}from"path";async function ci(e){let t=ca(e);await l(aa(e.projectDir,".github/workflows/ci.yml"),t)}function ca(e){let t=e.cacheProvider==="upstash",i=` services:
1058
1296
  postgres:
1059
1297
  image: postgres:18-alpine
1060
1298
  env:
@@ -1068,13 +1306,23 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
1068
1306
  --health-interval 10s
1069
1307
  --health-timeout 5s
1070
1308
  --health-retries 5
1071
- `,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=r?`
1309
+ ${t?"":` redis:
1310
+ image: redis:8-alpine
1311
+ ports:
1312
+ - 6379:6379
1313
+ options: >-
1314
+ --health-cmd "redis-cli ping"
1315
+ --health-interval 10s
1316
+ --health-timeout 5s
1317
+ --health-retries 5
1318
+ `}`,o="postgres://postgres:postgres@localhost:5432/saas",s=t?`
1072
1319
  UPSTASH_REDIS_REST_URL: https://test.upstash.io
1073
- UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
1320
+ UPSTASH_REDIS_REST_TOKEN: test-token`:`
1321
+ REDIS_URL: redis://localhost:6379`,a=(()=>{switch(e.paymentProvider){case"stripe":return`
1074
1322
  STRIPE_SECRET_KEY: test
1075
1323
  STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
1076
1324
  POLAR_ACCESS_TOKEN: test
1077
- POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let y=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(y)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1325
+ POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
1078
1326
  # which auto-deploys on push. CI runs in parallel as a quality gate.
1079
1327
  # For PR-based workflows, enable GitHub branch protection to require CI before merging.
1080
1328
 
@@ -1098,7 +1346,7 @@ jobs:
1098
1346
  name: Checks
1099
1347
  runs-on: ubuntu-latest
1100
1348
  timeout-minutes: 20
1101
- ${o} env:
1349
+ ${i} env:
1102
1350
  CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
1103
1351
  STORAGE_REGION: test
1104
1352
  STORAGE_ENDPOINT: http://test
@@ -1112,164 +1360,151 @@ ${o} env:
1112
1360
 
1113
1361
  - run: pnpm lint
1114
1362
 
1115
- ${n?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
1116
- # the type graph (Nuxt + Pinia + vue-i18n + content collections)
1117
- # crosses a threshold. Bump to 6 GB; ubuntu-latest has ~7 GB RAM.
1118
1363
  - run: pnpm check-types
1119
- env:
1120
- NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
1121
1364
 
1122
1365
  - name: Write root env
1123
- run: echo "DATABASE_URL=${i}" > .env
1366
+ run: echo "DATABASE_URL=${o}" > .env
1124
1367
 
1125
1368
  - run: pnpm test
1126
- `}import{readFile as qn}from"fs/promises";import{existsSync as fa}from"fs";import{join as mr}from"path";var Xn="@repo/database";function ga(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function ha(e,t){switch(e){case"fullstack":return t==="nextjs"?"web-next":"web-nuxt";case"separate":return"backend";default:{let r=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(r)}"`)}}}async function ya(e,t,r){let n=await qn(e,"utf-8"),o=JSON.parse(n),i=o.scripts?.[t];if(!i)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);i.includes(Xn)||(o.scripts={...o.scripts,[t]:`${r} && ${i}`},await c(e,JSON.stringify(o,null," ")+`
1127
- `))}async function wa(e,t){let r=fa(e)?JSON.parse(await qn(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(Xn)||(r.buildCommand=`${t} && ${n}`,await c(e,JSON.stringify(r,null," ")+`
1128
- `))}async function Zn(e){let t=ga(e.demo===!0),r=ha(e.architecture,e.frontend),n=mr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ya(mr(n,"package.json"),"start",t);return;case"vercel":await wa(mr(n,"vercel.json"),t);return;default:{let o=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(o)}"`)}}}import{readFile as va}from"fs/promises";import{existsSync as ka}from"fs";import{join as Mt}from"path";var ba=["stripe","polar"];async function Qn(e){let t=Mt(e.projectDir,"packages/payments/src"),r=e.paymentProvider,n=`// Active payment provider. To switch, change the path below to
1129
- // "./polar/index" or "./none/index" (other folders are kept in place).
1369
+ `}import{readFile as li}from"fs/promises";import{existsSync as la}from"fs";import{join as Sr}from"path";var pi="@repo/database";function pa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function da(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function ua(e,t,r){let n=await li(e,"utf-8"),i=JSON.parse(n),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(pi)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,JSON.stringify(i,null," ")+`
1370
+ `))}async function ma(e,t){let r=la(e)?JSON.parse(await li(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(pi)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
1371
+ `))}async function di(e){let t=pa(e.demo===!0),r=da(e.architecture),n=Sr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ua(Sr(n,"package.json"),"start",t);return;case"vercel":await ma(Sr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as fa}from"fs/promises";import{existsSync as ha}from"fs";import{join as Ht}from"path";var ui=["stripe","polar"],ga=[...ui,"none"];async function mi(e){let t=Ht(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
1372
+ // ${ga.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
1130
1373
  export { ops } from "./${r}/index";
1131
- `;await c(Mt(t,"providers/index.ts"),n),await c(Mt(t,"index.ts"),await Sa(t,r))}async function Sa(e,t){let r=Mt(e,"index.ts");if(!ka(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await va(r,"utf-8"),o=ba.filter(s=>s!==t);return n.split(`
1132
- `).filter(s=>!o.some(a=>s.includes(`./providers/${a}/`))).join(`
1133
- `)}import{access as Ea,readFile as Vt,rm as Ut}from"fs/promises";import{join as Y}from"path";var go=["sentry","posthog"],fr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Ft={sentry:"tests/sentry-load-guard.test.ts",posthog:"tests/posthog-load-guard.test.ts"},Ra=["tests/resolution.test.ts","tests/export-isolation.test.ts"],Pa=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],Ia=["./desktop-main","./desktop-renderer"],Ta=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1374
+ `;await l(Ht(t,"providers/index.ts"),i),await l(Ht(t,"index.ts"),await ya(t,r))}async function ya(e,t){let r=Ht(e,"index.ts");if(!ha(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await fa(r,"utf-8"),i=ui.filter(s=>s!==t);return n.split(`
1375
+ `).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
1376
+ `)}import{access as va,readFile as qt,rm as Yt}from"fs/promises";import{join as W}from"path";var vi=["sentry","posthog"],Rr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Wt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},ba=["tests/resolution.test.ts","tests/export-isolation.test.ts"],wa=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],ka=["./desktop-main","./desktop-renderer"],Ea=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
1134
1377
  `,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
1135
- `],Aa=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],eo=`
1378
+ `],Sa=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],fi=`
1136
1379
  });
1137
- `,Oa=" ";async function ho(e){let t=Y(e.projectDir,"packages/observability");await to(t,"packages/observability");let r=e.errorTracking;if(!B.includes(r))throw new Error(`errorTracking is ${JSON.stringify(r)}, which names no reporting provider. Set it to one of: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);r!=="none"&&await to(Y(t,fr[r]),`packages/observability/${fr[r]}`);let n=e.desktop?[...fo,...wc]:fo,o=new Map;for(let i of n)o.set(i.file,await Vt(Y(t,i.file),"utf-8"));for(let i of Ua(r,e.desktop))await Fa(t,i);for(let i of go)i!==r&&(await Ut(Y(t,fr[i]),{recursive:!0,force:!0}),await Ut(Y(t,Ft[i]),{force:!0}));for(let i of Ra)await Ut(Y(t,i),{force:!0});e.desktop||await xa(t,r);for(let i of n){let s=o.get(i.file);s!==void 0&&await c(Y(t,i.file),Na(s,i,r))}}async function to(e,t){try{await Ea(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function xa(e,t){for(let o of Pa)await Ut(Y(e,o),{force:!0});t==="sentry"&&await Da(e);let r=Y(e,"package.json"),n=JSON.parse(await Vt(r,"utf-8"));for(let o of Ia){if(!n.exports?.[o])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${o} export`);delete n.exports[o]}await c(r,JSON.stringify(n,null," ")+`
1138
- `)}async function Da(e){let t=Y(e,Ft.sentry),r=await Vt(t,"utf-8");r=yr(r,Ta.map(n=>({find:n,replace:""})),Ft.sentry);for(let n of Aa)r=_a(r,n,Ft.sentry);await c(t,r)}function _a(e,t,r){let n=e.indexOf(t),o=n===-1?-1:e.indexOf(eo,n);if(n===-1||o===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let i=e.slice(n+t.length,o).split(`
1139
- `).find(a=>a.trim().length>0&&!a.startsWith(`${Oa} `));if(i!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${i.trim()}`);let s=o+eo.length;return e[s]===`
1140
- `&&(s+=1),e.slice(0,n)+e.slice(s)}function Na(e,t,r){let n=go.filter(s=>s!==r),o=e,i=[];for(let s of n){let a=Ca(o,s);o=a.source,i.push(...a.bindings)}o=yr(o,[{find:ja,replace:La(r)}],t.file),o=yr(o,t.edits(r),t.file);for(let s of n)if(o.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of i)if(new RegExp(String.raw`\b${s}\b`).test(o))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return o}function yr(e,t,r){let n=e;for(let o of t){if(!n.includes(o.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${o.find.split(`
1141
- `)[0]}`);n=n.replace(o.find,o.replace)}return n}function Ca(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,i=>(n.push(...$a(i)),"")),bindings:n}}function $a(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let o=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),i=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(o);return i?.[1]?r.push(i[1]):/^[A-Za-z_$][\w$]*$/.test(o)&&r.push(o),r}var ja=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function La(e){return`${e==="none"?` * Your project was generated with error tracking OFF, so no provider adapter and no reporting
1142
- * SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports errors to ${e==="sentry"?"Sentry":"PostHog"}. No other provider's adapter or SDK was generated, so
1380
+ `,Ra=" ";async function bi(e){let t=W(e.projectDir,"packages/observability");await hi(t,"packages/observability");let r=e.observability,n=r.filter(s=>!B.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await hi(W(t,Rr[s]),`packages/observability/${Rr[s]}`);let i=e.desktop?[...yi,...cc]:yi,o=new Map;for(let s of i)o.set(s.file,await qt(W(t,s.file),"utf-8"));for(let s of Ca(r,e.desktop))await $a(t,s);for(let s of vi)if(!r.includes(s)){await Yt(W(t,Rr[s]),{recursive:!0,force:!0});for(let a of Wt[s])await Yt(W(t,a),{force:!0})}for(let s of ba)await Yt(W(t,s),{force:!0});e.desktop||await Aa(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(W(t,s.file),Ta(a,s,r))}}async function hi(e,t){try{await va(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Aa(e,t){for(let i of wa)await Yt(W(e,i),{force:!0});t.includes("sentry")&&await Pa(e);let r=W(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of ka){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ze(r,n," ","generateObservabilityProvider")}async function Pa(e){let t=W(e,Wt.sentry[0]),r=await qt(t,"utf-8");r=Ar(r,Ea.map(n=>({find:n,replace:""})),Wt.sentry[0]);for(let n of Sa)r=Ia(r,n,Wt.sentry[0]);await l(t,r)}function Ia(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(fi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let o=e.slice(n+t.length,i).split(`
1381
+ `).find(a=>a.trim().length>0&&!a.startsWith(`${Ra} `));if(o!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${o.trim()}`);let s=i+fi.length;return e[s]===`
1382
+ `&&(s+=1),e.slice(0,n)+e.slice(s)}function Ta(e,t,r){let n=vi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=_a(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Ar(i,[{find:xa,replace:Da(r)}],t.file)),i=Ar(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Ar(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
1383
+ `)[0]}`);n=n.replace(i.find,i.replace)}return n}function _a(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Oa(o)),"")),bindings:n}}function Oa(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var xa=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Da(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
1384
+ * SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports to ${t}. No other provider's adapter or SDK was generated, so
1143
1385
  * there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
1144
1386
  *
1145
- * To change providers, set \`errorTracking\` in \`.generatesaas/manifest.json\` to the one you want and
1387
+ * To change providers, edit \`observability\` in .generatesaas/manifest.json and
1146
1388
  * run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
1147
1389
  * update stages nothing while you are already on the latest version, so the switch lands with the
1148
- * next release. Editing \`config.observability.errorTracking.provider\` on its own cannot: the code
1149
- * it names is not here.`}function Bt(e){return` remedy: "Set errorTracking in .generatesaas/manifest.json to ${e==="none"?"a provider":"the provider you want"}, then run generatesaas update - it stages nothing until a newer version is out."`}var Kt=' reason: "was never generated - this project was built with error tracking off",',yo=' reason: "has no adapter in this package",',ro={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Ma={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ua(e,t){return e==="sentry"?[]:t?[ro,Ma]:[ro]}async function Fa(e,t){let r=await Vt(Y(e,t.source),"utf-8"),n=`export interface ${t.name} {
1150
- `,o=r.indexOf(n),i=r.indexOf(`
1390
+ * next release. Pasting the other provider's credential into \`config.observability\` on its own
1391
+ * cannot: the adapter it would need is not here.`}var gi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Na={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ca(e,t){return e.includes("sentry")?[]:t?[gi,Na]:[gi]}async function $a(e,t){let r=await qt(W(e,t.source),"utf-8"),n=`export interface ${t.name} {
1392
+ `,i=r.indexOf(n),o=r.indexOf(`
1151
1393
  }
1152
- `,o);if(o===-1||i===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(o+n.length,i).split(`
1153
- `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var wo=" * @param _options - Unused here, and kept so switching providers later costs you no call-site edit.",Va=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",Ba=' * Reachable from a hand-edited config, from a manifest written with a typo, and from a provider\n * added to the union before its adapter lands. All three used to fall through to Sentry, which\n * reported nothing (the Sentry gate refuses a config that names another provider) while\n * `resolveServerOps().id` still claimed `"sentry"`.',no=` if (errorTracking.provider === "sentry") return sentryServerOps;
1154
- `,oo=` if (errorTracking.provider === "posthog") return posthogServerOps;
1155
- `,io=` if (errorTracking.provider === "sentry") {
1156
- await initSentryServer();
1157
- return;
1394
+ `,i);if(i===-1||o===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(i+n.length,o).split(`
1395
+ `).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var La=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",ja=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
1396
+ `,Ma=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
1397
+ ops.push(posthogServerOps);
1158
1398
  }
1159
- `,so=` if (errorTracking.provider === "posthog") return;
1160
- `,gr=" * Call this at module scope. A crash during boot is never reported if the SDK waits for the first\n * captured request error, and it is `init()` that installs the `uncaughtException` and\n * `unhandledRejection` handlers. Safe to call unconditionally: the gate short-circuits before any\n * `import()`, so a project with reporting off still loads nothing.\n *\n * PostHog needs no equivalent. `posthog-node` installs no process-level handlers and builds its\n * client on the first capture, so there is nothing an early call could arm.",Ka=' * Resolution reads `enabled` and `provider` only. Whether the selected provider is USABLE - a\n * non-empty DSN or key - stays the adapter\'s own gate, which every runtime shares, so a provider\n * that is selected but unconfigured still resolves to itself and then reports nothing. Splitting it\n * that way keeps one answer to "which provider did the buyer pick" and one answer to "can it send".',ao=` * Every provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1161
- * warning above - the same direction both desktop runtimes already failed in. A default that picked
1162
- * a real provider would hand a buyer's errors, and the user ids and request context attached to
1163
- * them, to a service they never selected the moment that provider's own gate got any looser.`,Ga=` * Your provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1164
- * warning above. Falling back to a real provider instead would hand your errors, and the user ids
1165
- * and request context attached to them, to a service your config no longer names.`;function vo(e){return e==="none"?" * Reachable from a hand-edited config: your project ships no provider adapter at all, so whatever\n * `config.observability.errorTracking.provider` names has nothing here to resolve to.":" * Reachable from a hand-edited config: your project ships one provider's adapter, so naming any\n * other in `config.observability.errorTracking.provider` leaves nothing here to resolve to."}function Ha(e){let t=[{find:Va,replace:" into every browser bundle."},{find:Ba,replace:vo(e)},{find:ko,replace:Bt(e)},e==="none"?{find:`
1166
- *
1167
- ${ao}`,replace:""}:{find:ao,replace:Ga}];return e==="sentry"?[...t,{find:oo,replace:""},{find:so,replace:""},{find:gr,replace:" * Call this at module scope. A crash during boot is never reported if the SDK waits for the first\n * captured request error, and it is `init()` that installs the `uncaughtException` and\n * `unhandledRejection` handlers. Safe to call unconditionally: the gate short-circuits before any\n * `import()`, so a project with reporting off still loads nothing."}]:e==="posthog"?[...t,{find:no,replace:""},{find:io,replace:""},{find:gr,replace:" * There is nothing to arm in your project: `posthog-node` installs no process-level handlers and\n * builds its client on the first capture, so this settles immediately. The call site is kept so\n * your boot sequence is the same whichever provider you later move to."}]:[...t,{find:yo,replace:Kt},{find:Ka,replace:` * Always the no-op reporter: your project ships no provider adapter at all. Reporting left switched
1168
- * on in config is announced once rather than ignored, so it can never fail silently.`},{find:no,replace:""},{find:oo,replace:""},{find:gr,replace:` * There is nothing to arm in your project, so this settles immediately after announcing the gap
1169
- * once. The call site is kept so turning reporting on later needs no change outside config.`},{find:io,replace:""},{find:so,replace:""}]}var ko=` remedy: 'Set observability.errorTracking.provider to "sentry" or "posthog".'`,Ya=' * Reachable from a hand-edited config, from a manifest written with a typo, and from a provider\n * added to the union before its adapter lands. All three used to fall through to Sentry, which\n * reported nothing (the Sentry gate refuses a config that names another provider) while\n * `resolveBrowserOps().id` still claimed `"sentry"`.',co=` if (errorTracking.provider === "sentry") return sentryBrowserOps;
1170
- `,po=` if (errorTracking.provider === "posthog") return posthogBrowserOps;
1171
- `,lo=` if (errorTracking.provider === "sentry") {
1172
- await initSentryBrowser(options);
1173
- return;
1174
- }
1175
- `,uo=` if (errorTracking.provider === "posthog") return;
1176
- `,Ja="export async function initBrowserReporting(options: BrowserReportingOptions): Promise<void> {",za=" * @param options - How the client tags the events it sends.",Wa="export type BrowserReportingOptions = SentryBrowserInitOptions;",qa='export interface BrowserReportingOptions {\n /** The environment tag, usually `"development"` or `"production"`. */\n environment: string;\n}',hr=" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs, so deferring\n * it would capture only render errors, with no breadcrumbs and no coverage of plain async failures.\n *\n * PostHog has nothing to call here. Its browser client is built on the first capture, which is also\n * when `capture_exceptions` arms the global handlers, so a PostHog project reports every error it\n * is explicitly handed from the start but only starts catching UNHANDLED ones once the first such\n * report has been made. Sentry has no such window.",Xa=' * Resolution reads `enabled` and `provider` only. Whether the selected provider is USABLE - a\n * non-empty DSN or key - stays the adapter\'s own gate, which every runtime shares, so a provider\n * that is selected but unconfigured still resolves to itself and then reports nothing. Splitting it\n * that way keeps one answer to "which provider did the buyer pick" and one to "can it send".',mo=` * Every provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1177
- * warning above - the same direction both desktop runtimes already failed in. A default that picked
1178
- * a real provider would hand a buyer's errors, and the user ids attached to them, to a service they
1179
- * never selected the moment that provider's own gate got any looser.`,Za=` * Your provider is named EXPLICITLY, and anything else falls back to the no-op reporter with the
1180
- * warning above. Falling back to a real provider instead would hand your errors, and the user ids
1181
- * attached to them, to a service your config no longer names.`;function Qa(e){let t=[{find:Ya,replace:vo(e)},{find:ko,replace:Bt(e)},e==="none"?{find:`
1182
- *
1183
- ${mo}`,replace:""}:{find:mo,replace:Za}];if(e==="sentry")return[...t,{find:po,replace:""},{find:uo,replace:""},{find:hr,replace:" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs, so deferring\n * it would capture only render errors, with no breadcrumbs and no coverage of plain async failures."}];let r=[{find:Wa,replace:qa},{find:Ja,replace:"export async function initBrowserReporting(_options: BrowserReportingOptions): Promise<void> {"},{find:za,replace:wo}];return e==="posthog"?[...t,...r,{find:co,replace:""},{find:lo,replace:""},{find:hr,replace:` * There is nothing to start in your project. PostHog's browser client is built on the FIRST
1184
- * capture, which is also when \`capture_exceptions\` arms the global handlers: your app reports every
1185
- * error it is explicitly handed from the start, and only starts catching UNHANDLED ones once the
1186
- * first such report has been made. The call site is kept so your boot sequence is the same
1187
- * whichever provider you later move to.`}]:[...t,...r,{find:yo,replace:Kt},{find:Xa,replace:` * Always the no-op reporter: your project ships no provider adapter at all. Reporting left switched
1188
- * on in config is announced once rather than ignored, so it can never fail silently.`},{find:co,replace:""},{find:po,replace:""},{find:hr,replace:` * There is nothing to start in your project, so this settles immediately after announcing the gap
1189
- * once. The call site is kept so turning reporting on later needs no change outside config.`},{find:lo,replace:""},{find:uo,replace:""}]}var ec=` if (errorTracking.provider !== "sentry") {
1190
- announceMissingDesktopSdk(errorTracking.provider);
1191
- return noneOps;
1399
+ `,Ua=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
1400
+ await initSentryServer();
1192
1401
  }
1193
- return sentryDesktopMainOps;`,tc=` if (errorTracking.provider !== "sentry") {
1194
- announceMissingDesktopSdk(errorTracking.provider);
1195
- return;
1402
+ `,Va=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
1403
+ `,Fa=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
1404
+ `,Ba=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
1405
+ `,wi=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
1406
+ announceMissingDesktopSdk("posthog");
1196
1407
  }
1197
- await initSentryDesktopMain(options);`,rc=" options: DesktopMainReportingOptions",nc=" * @param options - The Electron facts only the app can answer.",oc="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",ic='export interface DesktopMainReportingOptions {\n /** The environment tag, usually `app.isPackaged ? "production" : "development"`. */\n environment: string;\n /** Whether Electron has already fired `ready`, usually `app.isReady()`. */\n appIsReady: boolean;\n}',sc=` * Anything other than Sentry falls back to the no-op reporter, rather than PostHog specifically, so
1198
- * a provider added to the union later fails safe with the warning instead of quietly shipping a
1199
- * desktop build that reports nothing.
1200
- *
1201
- * Whether Sentry is USABLE - a non-empty DSN - stays the adapter's own gate, which every runtime
1202
- * shares, so a selected but unconfigured provider still resolves to itself and then reports nothing.`,ac=" * `init()` is what installs the `uncaughtException` and `unhandledRejection` handlers, arms the\n * native crash reporter, and opens the channel renderer events are routed through, so waiting for\n * the first error would lose every crash before it. Safe to call unconditionally: the gate\n * short-circuits before any `import()`, so a build with reporting off still loads nothing.\n *\n * The gate is the config expression ITSELF, inline, exactly as {@link resolveDesktopMainOps} reads\n * it and exactly as the renderer and browser resolvers do. Gating on `resolveDesktopMainOps().id`\n * instead would put a function call between the flag and the `import()`, and a bundler folds a\n * branch away only when the member expression it tests sits in the same function as the import it\n * guards - measured against Rollup, no `treeshake` setting rescues the call form, and a desktop\n * build with reporting off still emitted the whole Sentry chunk. Calling this is still what\n * surfaces the missing-SDK warning at startup.",cc=` * There is nothing to arm in your project, so this settles immediately after announcing the gap
1203
- * once. The call site is kept so the app's boot sequence is the same whichever provider you later
1204
- * move to.`,pc=" * Call this on boot rather than lazily from an error boundary: it is `init()` that installs the\n * `window.onerror` and `unhandledrejection` handlers and starts recording breadcrumbs. Safe to call\n * unconditionally: the gate short-circuits before any `import()`, so a build with reporting off\n * still loads nothing.\n *\n * The gate is the config expression ITSELF, inline, exactly as {@link resolveDesktopRendererOps}\n * reads it and exactly as every other runtime does. Gating on `resolveDesktopRendererOps().id`\n * instead would put a function call between the flag and the `import()`, and a bundler folds a\n * branch away only when the member expression it tests sits in the same function as the import it\n * guards - measured against Rollup, no `treeshake` setting rescues the call form. Calling this is\n * still what surfaces the missing-SDK warning at startup.",lc=` * There is nothing to start in your project, so this settles immediately after announcing the gap
1205
- * once. The call site is kept so the renderer's boot sequence is the same whichever provider you
1206
- * later move to.`,bo=' remedy: "Select sentry to report errors from the desktop app."',So=' reason: "ships no Electron SDK",';function dc(e){if(e==="sentry")return[];let t=[{find:oc,replace:ic},{find:bo,replace:Bt(e)},{find:sc,replace:Eo(e)},{find:ec,replace:` announceMissingDesktopSdk(errorTracking.provider);
1207
- return noneOps;`},{find:ac,replace:cc},{find:nc,replace:wo},{find:rc,replace:" _options: DesktopMainReportingOptions"},{find:tc,replace:" announceMissingDesktopSdk(errorTracking.provider);"}];return e==="none"&&t.push({find:So,replace:Kt},hc),t}var uc=` if (errorTracking.provider !== "sentry") {
1208
- announceMissingDesktopSdk(errorTracking.provider);
1209
- return noneOps;
1408
+ `,Ka="export type BrowserReportingOptions = SentryBrowserInitOptions;",Ga=`export interface BrowserReportingOptions {
1409
+ /** The deployment environment reports are tagged with. */
1410
+ environment: string;
1411
+ }`,Ha=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
1412
+ `,Ya=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
1413
+ `,Wa="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",qa=`export interface DesktopMainReportingOptions {
1414
+ /** The deployment environment reports are tagged with. */
1415
+ environment: string;
1416
+ /** Whether Electron's \`app\` has emitted \`ready\` yet. */
1417
+ appIsReady: boolean;
1418
+ }`,za=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
1419
+ `,Ja=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
1420
+ `;function ki(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function Xa(e){let t=[{find:La,replace:" into every browser bundle."},...ki(e,{sentry:ja,posthog:Ma})];return e.includes("sentry")||t.push({find:Ua,replace:""}),t}function Za(e){let t=[...ki(e,{sentry:Va,posthog:Fa})];return e.includes("sentry")||t.push({find:Ba,replace:""},Qa),t}var Qa={find:Ka,replace:Ga};function ec(e){let t=[];return e.includes("posthog")||t.push({find:wi,replace:""}),e.includes("sentry")||t.push({find:Ha,replace:` return [];
1421
+ `},{find:Ya,replace:""},{find:Wa,replace:qa}),t}function tc(e){let t=[];return e.includes("posthog")||t.push({find:wi,replace:""}),e.includes("sentry")||t.push({find:za,replace:` return [];
1422
+ `},{find:Ja,replace:""}),t}var rc=` if (!posthogConfigured()) return;
1423
+ try {
1424
+ const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
1425
+ await capture(event);
1426
+ } catch (reportingError) {
1427
+ logReportingFailure("[observability] failed to report an AI generation", reportingError);
1210
1428
  }
1211
- return sentryDesktopRendererOps;`,mc=` if (errorTracking.provider !== "sentry") {
1212
- announceMissingDesktopSdk(errorTracking.provider);
1213
- return;
1429
+ `,nc=` // No PostHog adapter was generated for this project, so there is nothing to report to.
1430
+ `,ic=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
1431
+ `,sc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
1432
+ function posthogConfigured(): boolean {
1433
+ return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
1434
+ }
1435
+
1436
+ `,oc=` if (!posthogConfigured()) return;
1437
+ try {
1438
+ const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
1439
+ await flush();
1440
+ } catch (reportingError) {
1441
+ logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
1214
1442
  }
1215
- await initSentryDesktopRenderer();`,fc=` * Anything other than Sentry falls back to the no-op reporter, rather than PostHog specifically, so
1216
- * a provider added to the union later fails safe with the warning instead of quietly shipping a
1217
- * desktop build that reports nothing.`;function gc(e){if(e==="sentry")return[];let t=[{find:bo,replace:Bt(e)},{find:fc,replace:Eo(e)},{find:uc,replace:` announceMissingDesktopSdk(errorTracking.provider);
1218
- return noneOps;`},{find:pc,replace:lc},{find:mc,replace:" announceMissingDesktopSdk(errorTracking.provider);"}];return e==="none"&&t.push({find:So,replace:Kt},yc),t}function Eo(e){return e==="posthog"?` * Always the no-op reporter, and never in silence. PostHog ships no Electron SDK, so your desktop
1219
- * build reports nothing and says so once at startup; your web and server reporting is unaffected.`:` * Always the no-op reporter, and never in silence. Your project was generated with error tracking
1220
- * off, so there is no adapter and no SDK for the desktop app to reach.`}var hc={find:` * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
1221
- * web must not be blocked from shipping a desktop build over it. Silence would be worse, because
1222
- * the desktop app would simply never report with nothing to explain why, so the gap is surfaced
1223
- * here and again in the observability docs.`,replace:` * A WARNING and never an error: your project must still be able to ship whatever you edited, and a
1224
- * failure to REPORT errors must never itself become an error. Silence would be worse, because the
1225
- * desktop app would simply never report with nothing to explain why.`},yc={find:` * A WARNING and never an error: PostHog ships no Electron SDK, and a buyer running PostHog on the
1226
- * web must not be blocked from shipping a desktop build over it. Main and the renderer are separate`,replace:` * A WARNING and never an error: your project must still be able to ship whatever you edited, and a
1227
- * failure to REPORT errors must never itself become an error. Main and the renderer are separate`},fo=[{file:"src/resolve-server.ts",edits:Ha},{file:"src/resolve-browser.ts",edits:Qa}],wc=[{file:"src/resolve-desktop-main.ts",edits:dc},{file:"src/resolve-desktop-renderer.ts",edits:gc}];import{readdir as vc,readFile as kc}from"fs/promises";import{join as Ro}from"path";async function Po(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ro(e.projectDir,"packages/i18n/translations"),o;try{o=await vc(n)}catch{return}for(let i of o){let s=Ro(n,i,"web.json"),a;try{a=await kc(s,"utf-8")}catch{continue}let l=a.replaceAll("GenerateSaaS",r);l!==a&&await c(s,l)}}import{readFile as bc}from"fs/promises";import{join as Io}from"path";var Sc=[".nuxt/",".nuxt",".nitro/",".nitro",".output/",".output","_locales/"],Ec=[".next/",".next",".svelte-kit/",".svelte-kit",".wrangler/",".wrangler",".dev.vars"];async function Ao(e){let r=e.frontend==="nuxt"?Ec:Sc;await To(Io(e.projectDir,".gitignore"),r),await To(Io(e.projectDir,".dockerignore"),r)}async function To(e,t){let r;try{r=await bc(e,"utf-8")}catch{return}let n=new Set(t),o=r.split(`
1228
- `).filter(i=>!n.has(i.trim()));o.length!==r.split(`
1229
- `).length&&await c(e,o.join(`
1230
- `))}async function Gt(e){let t=e.projectDir;e.demo||(await tn(t),await nn(t),await on(t),await sn(t),e.desktop&&await rn(t)),await an(t,e.frontend),await pn(e),await ln(e),await dn(e),e.demo||await un(e),await gn(e),await hn(e),await yn(e),await wn(e),await vn(e),await kn(e),await Sn(e),await En(e),await Tn(e),await An(e),await Dn(e),await Cn(e),await Mn(e),await Wn(e),await Un(e),await Fn(e),await Vn(e),await Bn(e),await Kn(e),await Gn(e),await Hn(e),await Yn(e),await zn(e),await ur(e),await Zn(e),await Qn(e),await ho(e),await Po(e),await Ao(e)}import{basename as xo,join as Do,relative as Pc}from"path";import{createHash as Oo}from"crypto";import{readFile as Rc}from"fs/promises";async function Ht(e){let t=await Rc(e);return Oo("sha256").update(t).digest("hex")}function wr(e){return Oo("sha256").update(e).digest("hex")}var Ic=new Set(["data",H]);function Tc(e){let t=e.split("/");for(let r of t)if(rr.has(r)||nr.has(r)||Ic.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function _o(e,t){return{projectName:e.projectName??xo(t),appName:e.appName??e.projectName??xo(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,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,companion:e.companion??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",errorTracking:e.errorTracking??"none",version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function Ac(e,t){return{version:e.version,initialVersion:e.version,repo:"AlexChelan/GenerateSaaS",appName:e.appName,projectName:e.projectName,frontend:e.frontend,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,companion:e.companion,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,errorTracking:e.errorTracking,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function No(e,t){let n=(await Te(e.projectDir,e.projectDir,Tc)).sort(),o=await Promise.all(n.map(async a=>[Ie(Pc(e.projectDir,a)),await Ht(a)])),i=Object.fromEntries(o),s=Ac(e,t);await c(Do(e.projectDir,me),JSON.stringify(s,null," ")+`
1231
- `),await c(Do(e.projectDir,Kr),JSON.stringify(i,null," ")+`
1232
- `)}import{relative as Oc}from"path";async function ze(e){let r=(await Te(e,e,Ge)).sort(),n=await Promise.all(r.map(async o=>[Ie(Oc(e,o)),await Ht(o)]));return Object.fromEntries(n)}import{copyFile as xc,mkdir as Dc,rm as _c}from"fs/promises";import{dirname as Nc,join as Co,relative as Cc}from"path";import{existsSync as $c}from"fs";async function vr(e,t){$c(t)&&await _c(t,{recursive:!0,force:!0});let r=await Te(e,e,Ge);for(let n of r){let o=Ie(Cc(e,n)),i=Co(t,o);await Dc(Nc(i),{recursive:!0}),await xc(n,i)}}async function $o(e,t){await vr(e,Co(t,It))}import{existsSync as jc}from"fs";import{readFile as jo,readdir as Lc}from"fs/promises";import{join as X,dirname as Mc,resolve as Uc,sep as Fc}from"path";import{fileURLToPath as Vc}from"url";var Bc={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},De=Object.values(Bc),kr="generatesaas-update",Lo=Mc(Vc(import.meta.url));function Kc(){let e=X(Lo,"skill","content");return jc(e)?e:X(Lo,"content")}async function br(e,t,r){for(let n of De){let o=X(e,n,kr),i=X(o,"scripts"),s=X(o,"references");await xt(i),await xt(s),await c(X(o,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await c(X(s,".gitkeep"),"");for(let[a,l]of Object.entries(r)){let u=Uc(i,a);u.startsWith(i+Fc)&&await c(u,l)}}}async function Mo(e){let t=Kc(),r=await jo(X(t,"SKILL.md"),"utf-8"),n=X(t,"scripts"),o=await Lc(n),i={};for(let s of o)s!==".gitkeep"&&(i[s]=await jo(X(n,s),"utf-8"));await br(e,r,i)}import{execFile as Gc,execFileSync as Hc}from"child_process";import{access as Uo,readFile as Yc}from"fs/promises";import{join as Sr}from"path";import*as _ from"@clack/prompts";function Ne(e){try{let t=process.platform==="win32"?"where":"which";return Hc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function _e(e,t,r,n=3e5){return new Promise((o,i)=>{Gc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,l)=>{if(s){let u=String(a||"").trim(),f=[String(l||"").trim(),u].filter(Boolean).join(`
1233
- `);i(new Error(f?`${s.message}
1234
- ${f}`:s.message))}else o()})})}async function Fo(e){if(!Ne("pnpm"))return _.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await _e("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return _.log.warn(`Lockfile regeneration failed: ${r}`),_.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Vo(e){if(!Ne("pnpm"))return _.log.warn("pnpm not found. Skipping dependency installation."),_.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=_.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await _e("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`pnpm install failed: ${n}`),_.log.warn("You can run it manually later."),!1}}async function Bo(e){if(!Ne("pnpm"))return!1;let t=_.spinner();t.start("Generating baseline database migration...");try{return await _e("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return _.log.warn(`Could not generate baseline migration: ${n}`),_.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Ko(e){try{return await Uo(Sr(e,".git")),_.log.info("Git repository already exists, skipping init."),!0}catch{}if(!Ne("git"))return _.log.warn("git not found. Skipping repository initialization."),!1;let t=_.spinner();t.start("Initializing git repository...");try{return await _e("git",["init"],e),await _e("git",["add","-A"],e),await _e("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),_.log.warn("You can run git init manually later."),!1}}async function Go(e){if(!Ne("pnpm"))return!1;try{await Uo(Sr(e,".git"))}catch{return!1}try{let t=JSON.parse(await Yc(Sr(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await _e("pnpm",["exec","simple-git-hooks"],e),!0}catch{return _.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as We from"@clack/prompts";import J from"picocolors";function Ho(e,t){let r=Me(e);t.dockerAvailable||We.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${J.dim(`# ${r.map(a=>Nr[a].label).join(", ")}`)}`),n.push(`pnpm dev ${J.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(J.dim("Fill in remaining TODO values in .env"))),We.note(n.join(`
1235
- `),J.yellow("Start Development"));let o=[];o.push(`App ${J.cyan("http://localhost:3000")}`),e.architecture==="separate"&&o.push(`API ${J.cyan("http://localhost:3010")}`),r.includes("mailpit")&&o.push(`Mailpit ${J.cyan("http://localhost:8025")}`),r.includes("inngest")&&o.push(`Inngest ${J.cyan("http://localhost:8288")}`),We.note(o.join(`
1236
- `),J.yellow("Dev Tools"));let i=[],s=Jc(e);s.length>0&&i.push(`Set in production: ${J.dim(s.join(", "))}`),i.push("pnpm db:setup # Apply the database schema"),i.push(zc(e)),We.note(i.join(`
1237
- `),J.yellow("Deployment"))}function Jc(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 zc(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 qe(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function Ce(e,t){let r=qe(e),n=qe(t);if(!r||!n)return 0;for(let o=0;o<3;o++)if(r[o]!==n[o])return r[o]-n[o];return 0}function Yt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Yo(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:qe(e)===null}function Jt(e,t,r="2.4.0"){if(Yo(r))return{ok:!0};let n=Yt(e,e.latest);return!n||qe(n)===null?{ok:!0}:Ce(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function Jo(e,t,r="2.4.0"){if(Yo(r))return{ok:!0};let n=Yt(e,t);return!n||qe(n)===null?{ok:!0}:Ce(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import ep from"picocolors";var tp="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function rp(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function zo(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 z("--frontend <type>","frontend framework").choices([...Ee])).addOption(new z("--architecture <type>","fullstack or separate").choices([...Ue])).addOption(new z("--payment <provider>","payment provider").choices([...Fe])).addOption(new z("--email <provider>","email provider").choices([...Ve])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the companion").option("--no-ai","exclude the AI features").option("--companion","include the companion feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-companion","exclude the backend companion feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new z("--currency <code>","default currency for billing").choices([...oe])).addOption(new z("--deploy <target>","deployment target").choices([...ie])).addOption(new z("--database <provider>","database provider").choices([...se])).addOption(new z("--cache <provider>","cache provider").choices([...ae])).addOption(new z("--error-tracking <provider>","error reporting provider (anything unselected ships no SDK)").choices([...B])).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 z("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new z("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await np(t?{...r,apiKey:t}:r)})}async function np(e){let t=performance.now();Dr("2.4.0");let r;try{r=Fr(e)}catch(w){v.cancel(D(w)),process.exit(1)}let n=v.spinner(),o;try{o=await Ke({apiKey:e.apiKey,prompt:!e.yes})}catch(w){v.cancel(D(w)),process.exit(1)}e.demo&&wr(o)!==tp&&(v.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let i=pe(o),s,a=async()=>{s=await he(i);let w=Jt(s,"init");if(!w.ok)throw new Error(w.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,companionAllowed:s.entitlements?.companionAllowed??!0}};n.start("Verifying access...");let l,u,y=!0,f=!0;try{({latestVersion:l,selectedVersion:u,desktopAllowed:y,companionAllowed:f}=await a()),n.stop("Access verified."),Pe(o)}catch(w){if(n.stop("Access verification failed."),w instanceof C&&w.status===401){e.yes&&(v.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),v.log.warning("Invalid API key."),o=await st(),i=pe(o),n.start("Verifying access...");try{({latestVersion:l,selectedVersion:u,desktopAllowed:y,companionAllowed:f}=await a()),n.stop("Access verified."),Pe(o)}catch(N){n.stop("Access verification failed."),v.cancel(N instanceof C&&N.status===401?"Invalid API key.":D(N)),process.exit(1)}}else v.cancel(D(w)),process.exit(1)}v.log.success(`Latest version: ${l}`),r.desktop===!0&&!y&&(v.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.companion===!0&&!f&&(v.cancel("The companion is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let h;e.yes?h=Vr({...r,...y?{}:{desktop:!1},...f?{}:{companion:!1}}):h=await Br(r,{desktopAllowed:y,companionAllowed:f});let $;n.start("Activating license...");try{let w=e.demo&&h.baseUrl?await rp(h.baseUrl):crypto.randomUUID(),N=()=>({frontend:h.frontend,version:u,installId:w,projectName:h.projectName,options:Jr(h)}),de;try{de=await er(i,N())}catch(q){let A=Tt(q);if(!A?.lastAllowedVersion||!s)throw q;n.stop("License activation failed.");let Le=Jo(s,A.lastAllowedVersion);if(Le.ok||(v.cancel(`${A.message} ${Le.message}`),process.exit(1)),e.yes){let P=Yt(s,A.lastAllowedVersion);v.cancel(`${A.message} Re-run ${P?`npx generatesaas@${P} init`:"init"} without --yes to continue with v${A.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let te=await v.confirm({message:`Your update window has ended. Continue with v${A.lastAllowedVersion} (the last version your license covers)?`});(v.isCancel(te)||!te)&&(v.cancel("Setup cancelled."),process.exit(0)),u=A.lastAllowedVersion,n.start(`Activating license for v${u}...`),de=await er(i,N())}$={token:de.token,keyHash:wr(o),installId:de.installId??w},n.stop("License activated.")}catch(w){n.stop("License activation failed."),v.cancel(D(w)),process.exit(1)}let b=Qc(h.projectDir);if(Wc(b)&&qc(b).length>0)if(e.yes)v.log.info(`Directory ${b} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let N=await v.select({message:`Directory ${b} 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"}]});(v.isCancel(N)||N==="cancel")&&(v.cancel("Setup cancelled."),process.exit(0)),N==="overwrite"&&Xc(b,{recursive:!0,force:!0})}let U={...h,projectDir:b,version:u,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await At(i,u,b),n.stop("Template downloaded.")}catch(w){n.stop("Download failed."),v.cancel(D(w)),process.exit(1)}n.start("Generating project files...");try{if(await Gt(U),!e.demo){let w=await ze(b);await c(Zc(b,Pt),JSON.stringify(w,null," ")+`
1238
- `),await $o(b,b)}await Mo(b),await No(U,$),n.stop("Project files generated.")}catch(w){n.stop("Generation failed."),v.cancel(D(w)),process.exit(1)}!await Fo(b)&&U.demo===!0&&(v.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let ee=await Vo(b);ee&&U.demo!==!0&&e.dbMigration!==!1&&await Bo(b),await Ko(b),ee&&await Go(b);let le=Ne("docker"),ke=Zt(U).map(w=>w.key).filter(w=>!U.credentials?.[w]);Ho(U,{pnpmInstalled:ee,dockerAvailable:le,skippedCredentials:ke}),_r(),v.log.info(ep.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Pr}from"fs";import{readFile as ri}from"fs/promises";import{join as Xe,resolve as up}from"path";import*as k from"@clack/prompts";import V from"picocolors";import{mkdtemp as op,rm as ip}from"fs/promises";import{tmpdir as sp}from"os";import{join as ap}from"path";async function Er(e,t,r,n){let o=await op(ap(sp(),"generatesaas-stage-"));try{await At(e,t,o),await Gt({...r,projectDir:o}),await vr(o,n)}finally{await ip(o,{recursive:!0,force:!0})}}function ht(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Rr=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:Ee,adoptable:!1,impact:"structural",shapesTree:!0},{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ue,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ie,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:se,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Fe,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ve,adoptable:!1,impact:"config",shapesTree:!1},{key:"errorTracking",label:"Error tracking",hint:"Which service receives your app's errors: Sentry, PostHog, or none. Anything you do not pick costs nothing - its SDK and its adapter are never generated.",category:"Features",kind:"enum",default:"none",choices:B,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the companion option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"companion",label:"Companion daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install OpenCompanion, the daemon we publish and keep updated - your project ships the pairing, dispatch and Companions surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&ne({...e,companion:!0})===void 0,requiresLabel:"requires AI features and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>ht(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function cp(e,t){return e[t]!==void 0}function Wo(e){return Rr.filter(t=>t.adoptable&&!cp(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 pp(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"text":return typeof t=="string";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function lp(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"text":return"a string";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function qo(e){let t=[];for(let r of Rr){let n=e[r.key];n!==void 0&&(pp(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${lp(r)}.`))}return t}function Xo(e){let t={};for(let r of Rr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Zo(e){return e?"ON":"OFF"}var yt="packages/config/src/index.ts";function Qo(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function ei(e){return[...Me({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var dp=[{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>'Retired option `billingScope`: your project recorded organization-scoped billing, but it is now a plain config value generated as `user`. Applying this update as-is bills the individual member instead of the organization: new checkouts create member-scoped subscriptions and org-level entitlements stop resolving. Put it back with `billingScope: "organization"` in `packages/config/src/tenancy-flags.mjs`. How should this update proceed?'},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${yt} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${yt} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${yt}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===ht(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Zo(e.aiBuiltin)}, but it is now a plain config value generated ${Zo(ht(e))} for a project ${ht(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${yt} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${yt} to keep it off.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local companion checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one companion daemon (OpenCompanion) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` companion source. There is now one companion daemon - OpenCompanion - which we publish and your users install from its own releases. Your project keeps the companion feature and its own pairing, dispatch and Companions page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install OpenCompanion, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at OpenCompanion, the one daemon we publish.`},{key:"dockerServices",severity:"warn",preserved:e=>Qo(e).join(",")===ei(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${Qo(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${ei(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===$r.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${De.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`}];function ti(e){let t=[];for(let r of dp){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function ni(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,o=up(r.cwd??process.cwd()),i=Xe(o,me),s;try{s=JSON.parse(await ri(i,"utf-8"))}catch{k.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let a=qo(s);a.length>0&&(k.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1239
-
1240
- ${a.map(h=>` - ${h}`).join(`
1443
+ `;function ac(e){return e.includes("posthog")?[]:[{find:rc,replace:nc},{find:oc,replace:ic},{find:sc,replace:""},{find:`import { logReportingFailure } from "./logger";
1444
+ `,replace:""},{find:`import { config } from "@repo/config";
1445
+ `,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var yi=[{file:"src/resolve-server.ts",edits:Xa},{file:"src/resolve-browser.ts",edits:Za},{file:"src/llm-analytics.ts",edits:ac,dualMode:!1}],cc=[{file:"src/resolve-desktop-main.ts",edits:ec},{file:"src/resolve-desktop-renderer.ts",edits:tc}];import{readdir as lc,readFile as pc}from"fs/promises";import{join as Ei}from"path";async function Si(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ei(e.projectDir,"packages/i18n/translations"),i;try{i=await lc(n)}catch{return}for(let o of i){let s=Ei(n,o,"web.json"),a;try{a=await pc(s,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(s,p)}}async function zt(e){let t=e.projectDir;e.demo||(await hn(t),await yn(t),await vn(t),await bn(t),e.desktop&&await gn(t)),await wn(t),await Sn(e),await An(e),await Tn(e),e.demo||await _n(e),await Nn(e),await Cn(e),await $n(e),await Ln(e),await jn(e),await Un(e),await Fn(e),await Kn(e),await Yn(e),await Zn(e),await ci(e),await Qn(e),await ei(e),await ti(e),await ri(e),await ni(e),await ii(e),await si(e),await ai(e),await Er(e),await di(e),await mi(e),await bi(e),await Si(e),await qn(e)}import{basename as Ai,join as Pi,relative as uc}from"path";import{createHash as Ri}from"crypto";import{readFile as dc}from"fs/promises";async function Jt(e){let t=await dc(e);return Ri("sha256").update(t).digest("hex")}function Pr(e){return Ri("sha256").update(e).digest("hex")}var mc=new Set(["data",H]);function fc(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||mc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ii(e,t){return{projectName:e.projectName??Ai(t),appName:e.appName??e.projectName??Ai(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,webAi:e.webAi??!0,runner:e.runner??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function hc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:Qr,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,webAi:e.webAi,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ti(e,t){let n=(await ue(e.projectDir,e.projectDir,fc)).sort(),i=await Promise.all(n.map(async a=>[Ne(uc(e.projectDir,a)),await Jt(a)])),o=Object.fromEntries(i),s=hc(e,t);await l(Pi(e.projectDir,ve),JSON.stringify(s,null," ")+`
1446
+ `),await l(Pi(e.projectDir,en),JSON.stringify(o,null," ")+`
1447
+ `)}import{relative as gc}from"path";async function it(e){let r=(await ue(e,e,Xe)).sort(),n=await Promise.all(r.map(async i=>[Ne(gc(e,i)),await Jt(i)]));return Object.fromEntries(n)}import{copyFile as yc,mkdir as vc,rm as bc}from"fs/promises";import{dirname as wc,join as _i,relative as kc}from"path";import{existsSync as Ec}from"fs";async function Ir(e,t){Ec(t)&&await bc(t,{recursive:!0,force:!0});let n=(await ue(e,e,Xe)).map(i=>({file:i,dest:_i(t,Ne(kc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>wc(i)))].map(i=>vc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>yc(i,o)))}async function Oi(e,t){await Ir(e,_i(t,Nt))}import{existsSync as Sc}from"fs";import{readFile as xi,readdir as Rc}from"fs/promises";import{join as re,dirname as Ac,resolve as Pc,sep as Ic}from"path";import{fileURLToPath as Tc}from"url";var _c={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},$e=Object.values(_c),Tr="generatesaas-update",Di=Ac(Tc(import.meta.url));function Oc(){let e=re(Di,"skill","content");return Sc(e)?e:re(Di,"content")}async function _r(e,t,r){for(let n of $e){let i=re(e,n,Tr),o=re(i,"scripts"),s=re(i,"references");await jt(o),await jt(s),await l(re(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(re(s,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let m=Pc(o,a);m.startsWith(o+Ic)&&await l(m,p)}}}async function Ni(e){let t=Oc(),r=await xi(re(t,"SKILL.md"),"utf-8"),n=re(t,"scripts"),i=await Rc(n),o={};for(let s of i)s!==".gitkeep"&&(o[s]=await xi(re(n,s),"utf-8"));await _r(e,r,o)}import{execFile as xc,execFileSync as Dc}from"child_process";import{access as Ci,readFile as Nc}from"fs/promises";import{join as Or}from"path";import*as N from"@clack/prompts";function je(e){try{let t=process.platform==="win32"?"where":"which";return Dc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Le(e,t,r,n=3e5){return new Promise((i,o)=>{xc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,p)=>{if(s){let m=String(a||"").trim(),g=[String(p||"").trim(),m].filter(Boolean).join(`
1448
+ `);o(new Error(g?`${s.message}
1449
+ ${g}`:s.message))}else i()})})}async function $i(e){if(!je("pnpm"))return N.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Le("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return N.log.warn(`Lockfile regeneration failed: ${r}`),N.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Li(e){if(!je("pnpm"))return N.log.warn("pnpm not found. Skipping dependency installation."),N.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=N.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Le("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return N.log.warn(`pnpm install failed: ${n}`),N.log.warn("You can run it manually later."),!1}}async function ji(e){if(!je("pnpm"))return!1;let t=N.spinner();t.start("Generating baseline database migration...");try{return await Le("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return N.log.warn(`Could not generate baseline migration: ${n}`),N.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Mi(e){try{return await Ci(Or(e,".git")),N.log.info("Git repository already exists, skipping init."),!0}catch{}if(!je("git"))return N.log.warn("git not found. Skipping repository initialization."),!1;let t=N.spinner();t.start("Initializing git repository...");try{return await Le("git",["init"],e),await Le("git",["add","-A"],e),await Le("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),N.log.warn("You can run git init manually later."),!1}}async function Ui(e){if(!je("pnpm"))return!1;try{await Ci(Or(e,".git"))}catch{return!1}try{let t=JSON.parse(await Nc(Or(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Le("pnpm",["exec","simple-git-hooks"],e),!0}catch{return N.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Me from"@clack/prompts";import q from"picocolors";function Vi(e,t){let r=He(e);t.dockerAvailable||Me.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Me.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - deploying without it crash-loops the container.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${q.dim(`# ${r.map(a=>Br[a].label).join(", ")}`)}`),n.push(`pnpm dev ${q.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(q.dim("Fill in remaining TODO values in .env"))),Me.note(n.join(`
1450
+ `),q.yellow("Start Development"));let i=[];i.push(`App ${q.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${q.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${q.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${q.cyan("http://localhost:8288")}`),Me.note(i.join(`
1451
+ `),q.yellow("Dev Tools"));let o=[],s=Cc(e);s.length>0&&o.push(`Set in production: ${q.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push($c(e)),Me.note(o.join(`
1452
+ `),q.yellow("Deployment"))}function Cc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function $c(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 st(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function Ue(e,t){let r=st(e),n=st(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function Xt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Fi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:st(e)===null}function Zt(e,t,r="3.0.2"){if(Fi(r))return{ok:!0};let n=Xt(e,e.latest);return!n||st(n)===null?{ok:!0}:Ue(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function Bi(e,t,r="3.0.2"){if(Fi(r))return{ok:!0};let n=Xt(e,t);return!n||st(n)===null?{ok:!0}:Ue(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Fc from"picocolors";var Bc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Kc(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Ki(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ne("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new ne("--payment <provider>","payment provider").choices([...We])).addOption(new ne("--email <provider>","email provider").choices([...qe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the runner").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop app is the AI product. Requires --desktop and --ai, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ne("--currency <code>","default currency for billing").choices([...oe])).addOption(new ne("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...Oe])).addOption(new ne("--deploy <target>","deployment target").choices([...ae])).addOption(new ne("--database <provider>","database provider").choices([...ce])).addOption(new ne("--cache <provider>","cache provider").choices([...le])).option("--observability <providers>",`comma-separated observability providers (${B.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ne("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ne("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Gc(t?{...r,apiKey:t}:r)})}async function Gc(e){let t=performance.now();Vr("3.0.2");let r;try{r=Jr(e)}catch(v){b.cancel(D(v)),process.exit(1)}let n=b.spinner(),i;try{i=await Je({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(D(v)),process.exit(1)}e.demo&&Pr(i)!==Bc&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=de(i),s,a=async()=>{s=await ke(o);let v=Zt(s,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,m,w=!0,g=!0;try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await ut(),o=de(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(x){n.stop("Access verification failed."),b.cancel(x instanceof j&&x.status===401?"Invalid API key.":D(x)),process.exit(1)}}else b.cancel(D(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!w&&(b.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(b.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let k;e.yes?k=Xr({...r,...w?{}:{desktop:!1},...g?{}:{runner:!1}}):k=await Zr(r,{desktopAllowed:w,runnerAllowed:g});let A;n.start("Activating license...");try{let v=e.demo&&k.baseUrl?await Kc(k.baseUrl):crypto.randomUUID(),x=()=>({frontend:ar,version:m,installId:v,projectName:k.projectName,options:on(k)}),L;try{L=await cr(o,x())}catch(ge){let U=Ct(ge);if(!U?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let V=Bi(s,U.lastAllowedVersion);if(V.ok||(b.cancel(`${U.message} ${V.message}`),process.exit(1)),e.yes){let Ae=Xt(s,U.lastAllowedVersion);b.cancel(`${U.message} Re-run ${Ae?`npx generatesaas@${Ae} init`:"init"} without --yes to continue with v${U.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let F=await b.confirm({message:`Your update window has ended. Continue with v${U.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(F)||!F)&&(b.cancel("Setup cancelled."),process.exit(0)),m=U.lastAllowedVersion,n.start(`Activating license for v${m}...`),L=await cr(o,x())}A={token:L.token,keyHash:Pr(i),installId:L.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(D(v)),process.exit(1)}let f=Vc(k.projectDir);if(Lc(f)&&jc(f).length>0)if(e.yes)b.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let x=await b.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(b.isCancel(x)||x==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),x==="overwrite"&&Mc(f,{recursive:!0,force:!0})}let $={...k,projectDir:f,version:m,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await $t(o,m,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(D(v)),process.exit(1)}n.start("Generating project files...");try{if(await zt($),!e.demo){let v=await it(f);await l(Uc(f,Dt),JSON.stringify(v,null," ")+`
1453
+ `),await Oi(f,f)}await Ni(f),await Ti($,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await $i(f)&&$.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Li(f),X=$.demo!==!0&&e.dbMigration!==!1,he=!1;X&&fe&&(await ji(f),he=!0),await Mi(f),fe&&await Ui(f);let Ee=je("docker"),Re=ir($).map(v=>v.key).filter(v=>!$.credentials?.[v]);Vi($,{pnpmInstalled:fe,dockerAvailable:Ee,skippedCredentials:Re,baselineMigrationMissing:X&&!he}),Fr(),b.log.info(Fc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Cr}from"fs";import{readFile as Zi}from"fs/promises";import{join as ot,resolve as Zc}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as Hc,rm as Yc}from"fs/promises";import{tmpdir as Wc}from"os";import{join as qc}from"path";async function xr(e,t,r,n){let i=await Hc(qc(Wc(),"generatesaas-stage-"));try{await $t(e,t,i),await zt({...r,projectDir:i}),await Ir(i,n)}finally{await Yc(i,{recursive:!0,force:!0})}}function Rt(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Dr=[{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",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:qe,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:B,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, schedules, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ie({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>Rt(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function zc(e,t){return e[t]!==void 0}function Gi(e){return Dr.filter(t=>t.adoptable&&!zc(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 Jc(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function Xc(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Hi(e){let t=[];for(let r of Dr){let n=e[r.key];n!==void 0&&(Jc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Xc(r)}.`))}return t}function Yi(e){let t={};for(let r of Dr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Wi(e){return e?"ON":"OFF"}var At="packages/config/src/index.ts";function qi(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function zi(e){return[...He({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Nr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${At} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${At} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${At}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===Rt(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Wi(e.aiBuiltin)}, but it is now a plain config value generated ${Wi(Rt(e))} for a project ${Rt(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${At} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${At} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>qi(e).join(",")===zi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${qi(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${zi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Gr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${$e.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`}],df=Nr.map(e=>e.key);function Ji(e){for(let t of Nr)t.normalize?.(e)}function Xi(e){let t=[];for(let r of Nr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function Qi(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=Zc(r.cwd??process.cwd()),o=ot(i,ve),s;try{s=JSON.parse(await Zi(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===sr&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${sr}"\`).
1454
+
1455
+ v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
1456
+
1457
+ Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Hi(s);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
1458
+
1459
+ ${a.map(f=>` - ${f}`).join(`
1241
1460
  `)}
1242
1461
 
1243
- Correct it there, then run ${V.cyan("generatesaas update")} again.`),process.exit(1));let l=ne(s);l&&(k.cancel(`.generatesaas/manifest.json turns \`${l.feature}\` on with \`deploymentTarget: "${l.target}"\`, which cannot run it.
1462
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),Ji(s);let p=ie(s);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
1463
+
1464
+ ${p.reason}
1465
+
1466
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let m=rr(s);m.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
1244
1467
 
1245
- ${l.reason}
1468
+ ${m.map(f=>` - ${f}`).join(`
1469
+ `)}
1470
+
1471
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let w=qr(s);w.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
1472
+
1473
+ ${w.map(f=>` - ${f}`).join(`
1474
+ `)}
1475
+
1476
+ Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await Je()}catch(f){y.cancel(D(f)),process.exit(1)}let k=de(g),A=y.spinner();try{A.start("Verifying access...");let f;try{f=await ke(k)}catch(R){throw R instanceof j&&R.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):R}let $=Zt(f,"update");if(!$.ok)throw new Error($.message);A.stop("Access verified."),De(g),A.start("Fetching latest skill files...");let J=await sn(k,f.latest);await _r(i,J.skillMd,J.scripts);let fe=$e;if(A.stop("Skills updated."),y.log.success(`Skill files installed to ${C.cyan(fe.length.toString())} locations.`),s.version===f.latest){y.log.info(`Already on the latest version (${s.version}).`);return}let X=f.entitlements;X&&(s.desktop&&!X.desktopAllowed&&(y.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.runner&&!X.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let he=JSON.stringify(s);Wr(s),await Qc(s,zr(s),n),await tl(Xi(s),n);let Ee=Gi(s),Se=Yi(s),Re=rr(Se);Re.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
1477
+
1478
+ ${Re.map(R=>` - ${R}`).join(`
1479
+ `)}
1246
1480
 
1247
- Correct it there, then run ${V.cyan("generatesaas update")} again.`),process.exit(1));let u;try{u=await Ke()}catch(h){k.cancel(D(h)),process.exit(1)}let y=pe(u),f=k.spinner();try{f.start("Verifying access...");let h;try{h=await he(y)}catch(P){throw P instanceof C&&P.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):P}let $=Jt(h,"update");if(!$.ok)throw new Error($.message);f.stop("Access verified."),Pe(u),f.start("Fetching latest skill files...");let b=await Yr(y,h.latest);await br(o,b.skillMd,b.scripts);let U=De;if(f.stop("Skills updated."),k.log.success(`Skill files installed to ${V.cyan(U.length.toString())} locations.`),s.version===h.latest){k.log.info(`Already on the latest version (${s.version}).`);return}let Q=JSON.stringify(s);Mr(s),await mp(s,Ur(s),n),await gp(ti(s),n);let ee=Wo(s),le=Xo(s),ve=JSON.stringify(le)!==Q;if(s=le,s.licenseToken)try{let P=await zr(y,{currentToken:s.licenseToken,newVersion:h.latest});s.licenseToken=P.token,P.licenseKeyHash&&(s.licenseKeyHash=P.licenseKeyHash),await c(i,JSON.stringify(s,null," ")+`
1248
- `),ve=!1,k.log.success("License refreshed.")}catch(P){let Ze=Tt(P);Ze&&(k.cancel(Ze.message),process.exit(1)),k.log.warn("License refresh skipped.")}ve&&await c(i,JSON.stringify(s,null," ")+`
1249
- `);let ke=_o(s,o),w=Xe(o,Gr);f.start(`Staging v${h.latest} (shaped for your config)...`),await Er(y,h.latest,ke,w),f.stop("Template staged.");let{text:N,title:de}=await wp(y,h,s.version);N&&k.note(N,de);let q=Xe(o,Pt),A=Xe(o,It),Le=!Pr(A),te=!Pr(q);if(Le){if(f.start("Building baseline template (one-time migration)..."),await Er(y,s.version,ke,A),te){let P=await ze(A);await c(q,JSON.stringify(P,null," ")+`
1250
- `)}if(f.stop("Baseline template stored."),!te){let P=await vp(q,A);P>0&&k.log.warn(`Rebuilt baseline differs from the original for ${P} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(te){f.start("Computing baseline template hashes...");let P=await ze(A);await c(q,JSON.stringify(P,null," ")+`
1251
- `),f.stop("Baseline hashes computed.")}await c(Xe(o,Hr),JSON.stringify({currentVersion:s.version,targetVersion:h.latest,changelog:N,stagedAt:new Date().toISOString(),...ee.length>0?{newOptions:ee}:{},...n?{mode:n}:{}},null," ")+`
1252
- `),k.log.info(`Update staged: ${V.cyan(s.version)} \u2192 ${V.cyan(h.latest)}`),k.log.info(`Ask your AI coding assistant to ${V.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Pr(Xe(o,"apps/tauri"))&&k.log.warn(`Desktop: the app moved to an Electron shell (${V.cyan("apps/electron")}). Your project still has the old Tauri shell (${V.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${V.cyan("/desktop/updates")}.`)}catch(h){f.stop("Failed."),k.cancel(`Update failed: ${D(h)}`),process.exit(1)}})}async function mp(e,t,r){if(t.kind==="none")return;let n=yp[t.kind];r==="auto"&&(k.cancel(`${n.message}
1481
+ Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let v=JSON.stringify(Se)!==he;if(s=Se,s.licenseToken)try{let R=await an(k,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=R.token,R.licenseKeyHash&&(s.licenseKeyHash=R.licenseKeyHash),await l(o,JSON.stringify(s,null," ")+`
1482
+ `),v=!1,y.log.success("License refreshed.")}catch(R){let Pe=Ct(R);Pe&&(y.cancel(Pe.message),process.exit(1)),y.log.warn("License refresh skipped.")}v&&await l(o,JSON.stringify(s,null," ")+`
1483
+ `);let x=Ii(s,i),L=ot(i,tn);A.start(`Staging v${f.latest} (shaped for your config)...`),await xr(k,f.latest,x,L),A.stop("Template staged.");let{text:ge,title:U}=await il(k,f,s.version);ge&&y.note(ge,U);let V=ot(i,Dt),F=ot(i,Nt),Ae=!Cr(F),Be=!Cr(V);if(Ae){if(A.start("Building baseline template (one-time migration)..."),await xr(k,s.version,x,F),Be){let R=await it(F);await l(V,JSON.stringify(R,null," ")+`
1484
+ `)}if(A.stop("Baseline template stored."),!Be){let R=await sl(V,F);R>0&&y.log.warn(`Rebuilt baseline differs from the original for ${R} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(Be){A.start("Computing baseline template hashes...");let R=await it(F);await l(V,JSON.stringify(R,null," ")+`
1485
+ `),A.stop("Baseline hashes computed.")}await l(ot(i,rn),JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:ge,stagedAt:new Date().toISOString(),...Ee.length>0?{newOptions:Ee}:{},...n?{mode:n}:{}},null," ")+`
1486
+ `),y.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Cr(ot(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${C.cyan("apps/electron")}). Your project still has the old Tauri shell (${C.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${C.cyan("/desktop/updates")}.`)}catch(f){A.stop("Failed."),y.cancel(`Update failed: ${D(f)}`),process.exit(1)}})}async function Qc(e,t,r){if(t.kind==="none")return;let n=nl[t.kind];r==="auto"&&(y.cancel(`${n.message}
1253
1487
 
1254
- This is a decision only you can make, so an unattended update will not guess it. Run ${V.cyan("generatesaas update")} without ${V.cyan("auto")} and answer it.`),process.exit(1));let o=await k.select({message:n.message,options:n.options});k.isCancel(o)&&(k.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),o.apply(e)}var fp={billingScope:[{value:"stage",label:"Stage it - I will put the scope back myself",hint:'set `billingScope: "organization"` in packages/config/src/tenancy-flags.mjs before taking new checkouts'},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/tenancy-flags.mjs first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function gp(e,t){let r=[];for(let n of e){let o=n.severity==="ask"?fp[n.key]:void 0;if(!o){k.log.warn(n.message);continue}r.push({notice:n,answers:o})}for(let{notice:n,answers:o}of r){t==="auto"&&(k.cancel(`${n.message}
1488
+ This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var el={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function tl(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?el[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(y.cancel(`${n.message}
1255
1489
 
1256
- This is a decision only you can make, so an unattended update will not guess it. Run ${V.cyan("generatesaas update")} without ${V.cyan("auto")} and answer it.`),process.exit(1));let i=await k.select({message:n.message,options:o});(k.isCancel(i)||i==="stop")&&(k.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function hp(e){e.desktop=!1}var yp={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.companion=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web companion - it requires AI"},{value:{apply:hp},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function wp(e,t,r){let n=t.latest,o=t.versions.filter(s=>Ce(s.version,r)>0&&Ce(s.version,n)<=0).sort((s,a)=>Ce(s.version,a.version));if(o.length<=1)return{text:await Qt(e,n),title:`Changelog v${n}`};let i=[];for(let s of o){let a=null;try{a=await Qt(e,s.version)}catch{a=null}let l=s.date?` (${s.date.slice(0,10)})`:"",u=s.breaking?" [BREAKING]":"";i.push(`# v${s.version}${l}${u}
1490
+ This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let o=await y.select({message:n.message,options:i});(y.isCancel(o)||o==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function rl(e){e.desktop=!1}var nl={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:rl},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function il(e,t,r){let n=t.latest,i=t.versions.filter(p=>Ue(p.version,r)>0&&Ue(p.version,n)<=0).sort((p,m)=>Ue(p.version,m.version)),o=async p=>{try{return await nn(e,p)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(p=>o(p.version)));return{text:i.map((p,m)=>{let w=p.date?` (${p.date.slice(0,10)})`:"",g=p.breaking?" [BREAKING]":"",k=s[m]??"_No changelog available for this release._";return`# v${p.version}${w}${g}
1257
1491
 
1258
- ${a??"_No changelog available for this release._"}`)}return{text:i.join(`
1492
+ ${k}`}).join(`
1259
1493
 
1260
- `),title:`Changelog v${r} \u2192 v${n}`}}async function vp(e,t){let r=JSON.parse(await ri(e,"utf-8")),n=await ze(t),o=0;for(let[i,s]of Object.entries(r))Ge(i)||n[i]!==s&&o++;for(let i of Object.keys(n))i in r||o++;return o}import*as K from"@clack/prompts";import Z from"picocolors";import{readFile as kp}from"fs/promises";import{join as bp,resolve as Sp}from"path";function oi(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=Sp(t.cwd??process.cwd()),n=bp(r,me),o;try{o=JSON.parse(await kp(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let i=[`Version: ${Z.cyan(o.version)}`,`Frontend: ${Z.cyan(o.frontend)}`,o.deploymentTarget?`Deploy target: ${Z.cyan(o.deploymentTarget)}`:null,o.databaseProvider?`Database: ${Z.cyan(o.databaseProvider)}`:null,o.cacheProvider?`Cache: ${Z.cyan(o.cacheProvider)}`:null].filter(Boolean).join(`
1261
- `);K.note(i,Z.bold("Project Status"));let s=K.spinner();s.start("Checking for updates...");try{let a=await Ke(),l=pe(a),y=(await he(l)).latest;o.version===y?(s.stop("Up to date."),K.log.success(`Already on the latest version (${Z.green(y)})`)):(s.stop("Update available."),K.log.warning(`Update available: ${Z.yellow(o.version)} \u2192 ${Z.green(y)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${Z.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof C&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as Ep}from"fs/promises";import*as x from"@clack/prompts";import O from"picocolors";function Rp(){return process.env.GENERATESAAS_API_KEY??it()}function Pp(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 Ip(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function Tp(e){switch(e.verdict){case"licensed":return x.log.success(`${O.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return x.log.success(`${O.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return x.log.error(`${O.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return x.log.error(`${O.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${O.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return x.log.error(`${O.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return x.log.warn(`${O.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ii(e,t){let r=process.env.GENERATESAAS_API_URL??ot,n=Rp();e.start("Cross-referencing license records...");try{let o=n?Pp(await Wr(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):Ip(await tr(r,{token:t.token,domain:t.domain}));return e.stop(`${O.green("Checked")} - records cross-referenced`),Tp(o)}catch(o){return e.stop(`${O.yellow("Skipped")} - ${D(o)}`),null}}function Ap(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function Ir(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function si(e){x.note([`License ID: ${O.cyan(String(e.lid??"unknown"))}`,`Version: ${O.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${Ir(e.pat)}`,`Last updated: ${Ir(e.uat)}`,`Expires: ${Ir(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1262
- `),O.yellow("License Details"))}function Op(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function ai(e){let t=x.spinner(),r=null,n="no candidates";for(let s of Op(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}let l=(await a.text()).trim();if(!l||l.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${O.yellow("Not here")} - ${n}`);continue}r=l,t.stop(`${O.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${D(a)}`,t.stop(`${O.yellow("Unreachable")} - ${n}`)}}if(r===null){x.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=ci(e);return s?await ii(t,{domain:s})??!1:!1}let o;try{o=Ap(r)}catch{return x.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??ot,a=await tr(s,{token:r});if(a.valid)t.stop(`${O.green("Valid")} - signature verified`);else return t.stop(`${O.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${O.yellow("Skipped")} - could not reach verification service`),x.log.warn("Signature not verified. Displaying unverified claims:"),si(o),!1}return si(o),await ii(t,{token:r,lkh:typeof o.lkh=="string"?o.lkh:void 0,nid:typeof o.nid=="string"?o.nid:void 0,domain:ci(e)})??!0}function ci(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function pi(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(x.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let o=(await Ep(r.file,"utf-8")).split(`
1263
- `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));o.length===0&&(x.cancel("No URLs found in file."),process.exit(1));let i=0;for(let s of o)await ai(s)&&i++,x.log.info("");x.log.success(`${i}/${o.length} sites verified.`)}else await ai(t)||process.exit(1)})}import{existsSync as xp,rmSync as Dp}from"fs";import*as W from"@clack/prompts";function li(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){xp(ce)?(Dp(ce),W.log.success("API key removed.")):W.log.info("No API key configured.");return}let r=it();r?W.log.info(`Current API key: ****${r.slice(-4)}`):W.log.info("No API key configured.");let n=await st(),o=pe(n),i=W.spinner();i.start("Verifying API key...");try{await he(o),i.stop("API key verified."),Pe(n),W.log.success("API key saved.")}catch(s){i.stop("Verification failed."),s instanceof C&&s.status===401?W.cancel("Invalid API key."):W.cancel(D(s)),process.exit(1)}})}import{existsSync as zt,rmSync as _p,readFileSync as Ar,writeFileSync as di}from"fs";import{join as $e}from"path";import*as M from"@clack/prompts";var Np=["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"],Cp=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1494
+ `),title:`Changelog v${r} \u2192 v${n}`}}async function sl(e,t){let r=JSON.parse(await Zi(e,"utf-8")),n=await it(t),i=0;for(let[o,s]of Object.entries(r))Xe(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as K from"@clack/prompts";import me from"picocolors";import{readFile as ol}from"fs/promises";import{join as al,resolve as cl}from"path";function es(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=cl(t.cwd??process.cwd()),n=al(r,ve),i;try{i=JSON.parse(await ol(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${me.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${me.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${me.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${me.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
1495
+ `);K.note(o,me.bold("Project Status"));let s=K.spinner();s.start("Checking for updates...");try{let a=await Je(),p=de(a),w=(await ke(p)).latest;i.version===w?(s.stop("Up to date."),K.log.success(`Already on the latest version (${me.green(w)})`)):(s.stop("Update available."),K.log.warning(`Update available: ${me.yellow(i.version)} \u2192 ${me.green(w)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${me.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof j&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as ll}from"fs/promises";import*as O from"@clack/prompts";import _ from"picocolors";function pl(){return process.env.GENERATESAAS_API_KEY??dt()}function dl(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 ul(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function ml(e){switch(e.verdict){case"licensed":return O.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return O.log.success(`${_.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return O.log.error(`${_.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return O.log.error(`${_.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${_.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return O.log.error(`${_.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return O.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ts(e,t){let r=process.env.GENERATESAAS_API_URL??pt,n=pl();e.start("Cross-referencing license records...");try{let i=n?dl(await cn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):ul(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),ml(i)}catch(i){return e.stop(`${_.yellow("Skipped")} - ${D(i)}`),null}}function fl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function $r(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function rs(e){O.note([`License ID: ${_.cyan(String(e.lid??"unknown"))}`,`Version: ${_.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${$r(e.pat)}`,`Last updated: ${$r(e.uat)}`,`Expires: ${$r(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
1496
+ `),_.yellow("License Details"))}function hl(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function ns(e){let t=O.spinner(),r=null,n="no candidates";for(let s of hl(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${D(a)}`,t.stop(`${_.yellow("Unreachable")} - ${n}`)}}if(r===null){O.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=is(e);return s?await ts(t,{domain:s})??!1:!1}let i;try{i=fl(r)}catch{return O.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??pt,a=await lr(s,{token:r});if(a.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),O.log.warn("Signature not verified. Displaying unverified claims:"),rs(i),!1}return rs(i),await ts(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:is(e)})??!0}function is(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ss(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(O.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await ll(r.file,"utf-8")).split(`
1497
+ `).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(O.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await ns(s)&&o++,O.log.info("");O.log.success(`${o}/${i.length} sites verified.`)}else await ns(t)||process.exit(1)})}import{existsSync as gl,rmSync as yl}from"fs";import*as z from"@clack/prompts";function os(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){gl(pe)?(yl(pe),z.log.success("API key removed.")):z.log.info("No API key configured.");return}let r=dt();r?z.log.info(`Current API key: ****${r.slice(-4)}`):z.log.info("No API key configured.");let n=await ut(),i=de(n),o=z.spinner();o.start("Verifying API key...");try{await ke(i),o.stop("API key verified."),De(n),z.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof j&&s.status===401?z.cancel("Invalid API key."):z.cancel(D(s)),process.exit(1)}})}import{existsSync as Qt,rmSync as vl,readFileSync as jr,writeFileSync as as}from"fs";import{join as Ve}from"path";import*as M from"@clack/prompts";var bl=["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"],wl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
1264
1498
  `,` licenseHeartbeatFunction,
1265
1499
  `]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
1266
1500
  `,` .route("/license", licenseRoutes)
1267
- `]}];function $p(){return De.map(e=>$e(e,kr))}function Tr(e){return zt(e)?(_p(e,{recursive:!0}),!0):!1}function jp(e,t){if(!zt(e))return!1;let r=Ar(e,"utf-8"),n=r;for(let o of t)n=n.replace(o,"");return n===r?!1:(di(e,n,"utf-8"),!0)}function Lp(e){let t=$e(e,".gitignore");if(!zt(t))return!1;let r=Ar(t,"utf-8"),n=r.split(`
1268
- `).filter(o=>!o.includes(".generatesaas")).join(`
1269
- `);return n===r?!1:(di(t,n,"utf-8"),!0)}function ui(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=$e(t,me),n;try{n=JSON.parse(Ar(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let o=await M.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(M.isCancel(o)&&(M.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let i=[],s=[];for(let a of $p())Tr($e(t,a))&&i.push(a);for(let a of Np)Tr($e(t,a))&&i.push(a);Tr($e(t,H))&&i.push(H+"/");for(let a of Cp){let l=$e(t,a.file);jp(l,a.removals)?s.push(a.file):zt(l)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Lp(t)&&s.push(".gitignore");for(let a of i)M.log.info(`Deleted ${a}`);for(let a of s)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var je=new Mp().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("2.4.0").addHelpText("after",`
1501
+ `]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
1502
+ `],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function kl(){return $e.map(e=>Ve(e,Tr))}function Lr(e){return Qt(e)?(vl(e,{recursive:!0}),!0):!1}function El(e,t,r=[]){if(!Qt(e))return!1;let n=jr(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(as(e,i,"utf-8"),!0)}function Sl(e){let t=Ve(e,".gitignore");if(!Qt(t))return!1;let r=jr(t,"utf-8"),n=r.split(`
1503
+ `).filter(i=>!i.includes(".generatesaas")).join(`
1504
+ `);return n===r?!1:(as(t,n,"utf-8"),!0)}function cs(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ve(t,ve),n;try{n=JSON.parse(jr(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(M.isCancel(i)&&(M.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of kl())Lr(Ve(t,a))&&o.push(a);for(let a of bl)Lr(Ve(t,a))&&o.push(a);Lr(Ve(t,H))&&o.push(H+"/");for(let a of wl){let p=Ve(t,a.file);El(p,a.removals,a.replacements)?s.push(a.file):Qt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Sl(t)&&s.push(".gitignore");for(let a of o)M.log.info(`Deleted ${a}`);for(let a of s)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Fe=new Rl().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.0.2").addHelpText("after",`
1270
1505
  Examples:
1271
1506
  $ generatesaas init Interactive setup
1272
1507
  $ generatesaas init -n my-app -y Quick setup with defaults
1273
1508
  $ generatesaas status Check for updates
1274
1509
  $ generatesaas auth Set or update API key
1275
- `);zo(je);ni(je);oi(je);pi(je);li(je);ui(je);je.parseAsync().catch(e=>{mi.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
1510
+ `);Ki(Fe);Qi(Fe);es(Fe);ss(Fe);os(Fe);cs(Fe);Fe.parseAsync().catch(e=>{ls.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});