generatesaas 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +291 -316
- package/dist/skill/content/SKILL.md +21 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as Ua}from"commander";import*as Ai from"@clack/prompts";import{existsSync as Xs,readdirSync as Zs,rmSync as Qs}from"fs";import{join as ea,resolve as ta}from"path";import{Option as q}from"commander";import*as y from"@clack/prompts";import*as ft from"@clack/prompts";import Ut from"picocolors";function fn(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";ft.intro(Ut.bgYellow(Ut.black(t)))}function gn(){ft.outro(Ut.yellow("Happy building!"))}import*as f from"@clack/prompts";import g from"picocolors";var Je={nextjs:{label:"Next.js",hint:"React 19 + Next.js 16"},nuxt:{label:"Nuxt",hint:"Vue 3 + Nuxt 4"}},qe={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)"}},gt={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},ht={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},hn={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 we={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 Y={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}},Q={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"}]}},ve={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"}]}},We=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."}],Xe=[{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)."}],yn=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function Oe(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 ke=["nextjs","nuxt"],De=["fullstack","separate"],Ce=["stripe","polar","none"],Ne=["smtp","ses","resend"];var wn=["claude-code","cursor","codex","gemini-cli","windsurf"],ee=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],te=["node","vercel"],ne=["postgres","neon","supabase"],re=["redis","upstash"];function vn(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function yt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function wt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function O(e){return e instanceof Error?e.message:String(e)}var kn=["companion"];function Mt(e){if(!kn.some(n=>e[n]===!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 bn(e){return kn.some(n=>e[n]===!0)&&(e.ai=!0),e}function Sn(e){let t=Ri(e,e.desktopAi);return delete e.desktopAi,t}function Ri(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 En(e){let t={};if(e.name!==void 0){if(!wt(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(!ke.includes(e.frontend))throw new Error(`Invalid frontend "${e.frontend}". Valid values: ${ke.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),Mt(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(!ee.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${ee.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!te.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${te.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ne.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ne.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!re.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${re.join(", ")}`);t.cacheProvider=e.cache}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let n=e.baseUrl.trim();if(n==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let r;try{r=new URL(n)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${r.protocol}//${r.host}`}return t}var $e={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"};function An(e){let t=e.projectName??$e.projectName,n=e.projectDir??`./${t}`,r=e.appName??yt(t),i=e.deploymentTarget??$e.deploymentTarget,o=Y[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":$e.databaseProvider),a=e.cacheProvider??(o?"upstash":$e.cacheProvider),d=e.emailProvider??(o?"resend":$e.emailProvider),l={...$e,...e,projectName:t,appName:r,projectDir:n,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:d};l.paymentProvider==="none"&&(l.credits=!1);for(let u of We){if(l.deploymentTarget!==u.target)continue;let k=l.databaseProvider===u.provider?"database":"cache";if(l.databaseProvider===u.provider||l.cacheProvider===u.provider)throw new Error(`Incompatible: --deploy ${u.target} + --${k} ${u.provider}. ${u.reason}`)}for(let u of Xe)if(l.architecture===u.architecture&&l.deploymentTarget===u.target)throw new Error(`Incompatible: --architecture ${u.architecture} + --deploy ${u.target}. ${u.reason}`);return l}function P(e){f.isCancel(e)&&(f.cancel("Setup cancelled."),process.exit(0))}function Ft(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 In(e,t){let n=!1;e&&Mt(e),f.log.info(g.bold("Project"));let r=e?.projectName??await(async()=>{n=!0;let p=await f.text({message:"Project name:",placeholder:"my-saas",validate:m=>{if(!m?.trim())return"Project name is required.";if(!wt(m))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return P(p),p})(),i=e?.appName??await(async()=>{n=!0;let p=await f.text({message:"App name:",initialValue:yt(r),validate:m=>{if(!m?.trim())return"App name is required."}});return P(p),p})(),o=e?.projectDir??await(async()=>{n=!0;let p=await f.text({message:"Project location:",initialValue:`./${r}`});return P(p),p==="."?process.cwd():p})(),s=e?.frontend??await(async()=>{n=!0;let p=Object.keys(Je),m=await f.select({message:"Frontend framework:",options:p.map(b=>({value:b,label:Je[b].label,hint:Je[b].hint}))});return P(m),m})();f.log.info(g.bold("Infrastructure"));let a=e?.deploymentTarget??"node";if(e?.deploymentTarget===void 0){n=!0;let p=await f.select({message:"Deployment target:",options:te.map(m=>({value:m,label:Y[m].label,hint:Y[m].hint}))});P(p),a=p}let d=e?.architecture?Xe.find(p=>p.architecture===e.architecture&&p.target===a):void 0;if(d)throw new Error(`Incompatible: --architecture ${d.architecture} + --deploy ${d.target}. ${d.reason}`);let l=new Set(Xe.filter(p=>p.target===a).map(p=>p.architecture)),u=De.filter(p=>!l.has(p)),k=e?.architecture??await(async()=>{if(u.length===1){let m=u[0];return f.log.info(`Auto-selected ${qe[m].label} architecture (only compatible option for ${Y[a].label}).`),m}n=!0;let p=await f.select({message:"Architecture:",options:u.map(m=>({value:m,label:qe[m].label,hint:qe[m].hint}))});return P(p),p})(),A=e?.databaseProvider??await(async()=>{n=!0;let p=ne.filter(b=>!We.some(se=>se.target===a&&se.provider===b));if(p.length===1){let b=p[0];return f.log.info(`Auto-selected ${Q[b].label} (only compatible option for ${Y[a].label}).`),b}let m=await f.select({message:"Database provider:",options:p.map(b=>({value:b,label:Q[b].label,hint:Q[b].hint}))});return P(m),m})(),$=e?.cacheProvider??await(async()=>{n=!0;let p=re.filter(b=>!We.some(se=>se.target===a&&se.provider===b));if(p.length===1){let b=p[0];return f.log.info(`Auto-selected ${ve[b].label} (only compatible option for ${Y[a].label}).`),b}let m=await f.select({message:"Cache provider:",options:p.map(b=>({value:b,label:ve[b].label,hint:ve[b].hint}))});return P(m),m})();if(Y[a]?.edgeRuntime){let p=yn.map(m=>` - ${m}`).join(`
|
|
3
|
-
`);
|
|
4
|
-
`),
|
|
5
|
-
`),
|
|
6
|
-
`),
|
|
7
|
-
`);
|
|
8
|
-
`),"Summary");let
|
|
9
|
-
`,{mode:384})}async function
|
|
10
|
-
`,scripts:{}}:await(await
|
|
11
|
-
|
|
12
|
-
`)}async function
|
|
13
|
-
`)}function
|
|
14
|
-
`).find(a=>a.includes(`href="${
|
|
15
|
-
`,"",`${t} ai.mdx ${
|
|
16
|
-
`).find(
|
|
17
|
-
`,"",`${t} ai.mdx ${
|
|
18
|
-
`,"",`${t} meta.json ${
|
|
19
|
-
`,
|
|
20
|
-
`))}}var
|
|
21
|
-
`)}function
|
|
22
|
-
- **Payments:** ${
|
|
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
|
|
23
23
|
|
|
24
24
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
25
25
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -33,7 +33,7 @@ and go find it:
|
|
|
33
33
|
|
|
34
34
|
1. \`docs/${t?"nuxt":"next"}/index.mdx\` - the catalog of every shipped feature and its config flag.
|
|
35
35
|
2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
|
|
36
|
-
3. Search \`packages/\` and \`${
|
|
36
|
+
3. Search \`packages/\` and \`${n}/\` for the name before creating anything.
|
|
37
37
|
|
|
38
38
|
Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
|
|
39
39
|
billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
|
|
@@ -45,13 +45,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
45
45
|
|
|
46
46
|
## Stack
|
|
47
47
|
|
|
48
|
-
- **Frontend:** ${
|
|
48
|
+
- **Frontend:** ${r} ${s}
|
|
49
49
|
- **API:** Hono, RPC-typed. ${a}
|
|
50
|
-
- **Database:** Drizzle ORM + ${
|
|
51
|
-
- **Cache + jobs:** ${
|
|
52
|
-
- **Auth:** Better Auth${
|
|
53
|
-
- **Email:** ${
|
|
54
|
-
- **Deploy:** ${
|
|
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}
|
|
55
55
|
|
|
56
56
|
## Where things live (extend these - don't reinvent)
|
|
57
57
|
|
|
@@ -61,8 +61,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
61
61
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
62
62
|
- \`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
63
|
- \`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
|
-
- \`${
|
|
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/\`${
|
|
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}.
|
|
66
66
|
|
|
67
67
|
## Code style
|
|
68
68
|
|
|
@@ -80,7 +80,7 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
80
80
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
81
81
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
82
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
|
-
- ${
|
|
83
|
+
- ${b}
|
|
84
84
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
85
85
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
86
86
|
|
|
@@ -91,23 +91,23 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
91
91
|
## This project
|
|
92
92
|
|
|
93
93
|
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
|
|
95
|
-
`)}import{join as
|
|
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
|
|
96
96
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
97
97
|
- API: http://localhost:3010
|
|
98
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
99
|
-
`,
|
|
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}
|
|
100
100
|
|
|
101
101
|
${s}
|
|
102
102
|
|
|
103
103
|
## Stack
|
|
104
104
|
|
|
105
|
-
- **Frontend:** ${
|
|
105
|
+
- **Frontend:** ${n}
|
|
106
106
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
107
107
|
- **Auth:** Better Auth
|
|
108
|
-
- **ORM / DB:** Drizzle + ${
|
|
108
|
+
- **ORM / DB:** Drizzle + ${i}
|
|
109
109
|
- **Background jobs:** Inngest
|
|
110
|
-
- **i18n:** ${
|
|
110
|
+
- **i18n:** ${r?"@nuxtjs/i18n":"next-intl"}
|
|
111
111
|
|
|
112
112
|
## Development
|
|
113
113
|
|
|
@@ -116,7 +116,7 @@ pnpm install
|
|
|
116
116
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
117
117
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
118
118
|
# reference. All apps load the single root \`.env\`.
|
|
119
|
-
${
|
|
119
|
+
${l}pnpm db:setup # first run: create the database schema (idempotent)
|
|
120
120
|
pnpm dev
|
|
121
121
|
\`\`\`
|
|
122
122
|
|
|
@@ -140,7 +140,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
|
|
|
140
140
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
141
141
|
\`\`\`
|
|
142
142
|
|
|
143
|
-
${
|
|
143
|
+
${u}
|
|
144
144
|
|
|
145
145
|
## Removing the GenerateSaaS license
|
|
146
146
|
|
|
@@ -153,17 +153,33 @@ pnpm dlx generatesaas eject
|
|
|
153
153
|
## Updates
|
|
154
154
|
|
|
155
155
|
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
|
|
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
|
|
157
157
|
url: ${t}
|
|
158
|
-
updaterCacheDirName: ${
|
|
159
|
-
`)}function
|
|
160
|
-
`):'{ enabled: false, clientId: "companion" }'}
|
|
158
|
+
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?`{
|
|
161
177
|
enableInDev: true,
|
|
162
178
|
chatwoot: {
|
|
163
179
|
baseUrl: "https://support.alexchelan.com",
|
|
164
180
|
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
165
181
|
}
|
|
166
|
-
}`:"{}",
|
|
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";
|
|
167
183
|
import { desktopConfig } from "./desktop.mjs";
|
|
168
184
|
import { observabilityConfig } from "./observability.mjs";
|
|
169
185
|
import { supportConfig } from "./support.mjs";
|
|
@@ -174,8 +190,8 @@ const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim
|
|
|
174
190
|
export const config: AppConfig = {
|
|
175
191
|
siteName: "${t}",
|
|
176
192
|
fullSiteName: "${t}",
|
|
177
|
-
domain: "${
|
|
178
|
-
baseUrl: process.env.BASE_URL ?? "${
|
|
193
|
+
domain: "${o}",
|
|
194
|
+
baseUrl: process.env.BASE_URL ?? "${n}",
|
|
179
195
|
indexable: ${s},
|
|
180
196
|
logo: {
|
|
181
197
|
main: "/images/logo.svg",
|
|
@@ -201,16 +217,16 @@ export const config: AppConfig = {
|
|
|
201
217
|
limitPerSecond: 3,
|
|
202
218
|
senders: {
|
|
203
219
|
transactional: {
|
|
204
|
-
email: "noreply@${
|
|
220
|
+
email: "noreply@${i}",
|
|
205
221
|
senderName: "${t}"
|
|
206
222
|
},
|
|
207
223
|
marketing: {
|
|
208
|
-
email: "hello@${
|
|
224
|
+
email: "hello@${i}",
|
|
209
225
|
senderName: "${t}",
|
|
210
226
|
signatureName: "Alex"
|
|
211
227
|
},
|
|
212
228
|
support: {
|
|
213
|
-
email: "support@${
|
|
229
|
+
email: "support@${i}",
|
|
214
230
|
senderName: "${t} Support"
|
|
215
231
|
}
|
|
216
232
|
},
|
|
@@ -226,7 +242,7 @@ export const config: AppConfig = {
|
|
|
226
242
|
maxFileSizeMB: 5,
|
|
227
243
|
dailyUploadLimit: 20
|
|
228
244
|
},
|
|
229
|
-
payment: ${
|
|
245
|
+
payment: ${r?`{
|
|
230
246
|
enabled: true,
|
|
231
247
|
provider: "${e.paymentProvider}",
|
|
232
248
|
bannedCountries: ["BY", "CU", "IR", "KP", "RU", "SY"]
|
|
@@ -238,7 +254,7 @@ export const config: AppConfig = {
|
|
|
238
254
|
prefix: "key_"
|
|
239
255
|
},
|
|
240
256
|
apiDocs: true,
|
|
241
|
-
performanceMonitor: { enabled: ${
|
|
257
|
+
performanceMonitor: { enabled: ${l} },
|
|
242
258
|
observability: observabilityConfig,
|
|
243
259
|
notifications: {
|
|
244
260
|
enabled: true,
|
|
@@ -278,7 +294,7 @@ export const config: AppConfig = {
|
|
|
278
294
|
}`:`{
|
|
279
295
|
base: "${e.defaultCurrency}",
|
|
280
296
|
list: [
|
|
281
|
-
{ symbol: "${
|
|
297
|
+
{ symbol: "${be[e.defaultCurrency].symbol}", name: "${be[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${be[e.defaultCurrency].place}", space: ${be[e.defaultCurrency].space} }
|
|
282
298
|
],
|
|
283
299
|
countryMap: {
|
|
284
300
|
default: "${e.defaultCurrency}"
|
|
@@ -305,7 +321,7 @@ export const config: AppConfig = {
|
|
|
305
321
|
// Built-in AI: your app offers models under its OWN name, billed from user credits (which need a
|
|
306
322
|
// payment provider to buy), so it is generated on exactly when a payment provider exists. Powered by
|
|
307
323
|
// OpenRouter - set OPENROUTER_API_KEY in your env, that is the whole setup. Flip this to change it.
|
|
308
|
-
builtin: ${
|
|
324
|
+
builtin: ${r},
|
|
309
325
|
// Let users connect their own provider API keys; flip to false to disable.
|
|
310
326
|
byok: true,
|
|
311
327
|
// What every user starts on (their own choice, once made, always wins). Plain
|
|
@@ -327,7 +343,7 @@ export const config: AppConfig = {
|
|
|
327
343
|
},
|
|
328
344
|
desktop: desktopConfig,
|
|
329
345
|
// Companion: the OpenCompanion daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
330
|
-
companion: ${
|
|
346
|
+
companion: ${f},
|
|
331
347
|
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
332
348
|
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
333
349
|
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
@@ -371,7 +387,7 @@ export * from "./pricing";
|
|
|
371
387
|
export * from "./roles";
|
|
372
388
|
export * from "./section-tabs";
|
|
373
389
|
export * from "./tenancy";
|
|
374
|
-
`,$=
|
|
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
|
|
375
391
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
376
392
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
377
393
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -379,10 +395,10 @@ export * from "./tenancy";
|
|
|
379
395
|
|
|
380
396
|
export const desktopConfig = {
|
|
381
397
|
enabled: ${e.desktop},
|
|
382
|
-
appId: "${
|
|
383
|
-
productName: "${
|
|
384
|
-
protocol: "${
|
|
385
|
-
baseUrl: "${
|
|
398
|
+
appId: "${u.appId}",
|
|
399
|
+
productName: "${u.productName}",
|
|
400
|
+
protocol: "${u.protocol}",
|
|
401
|
+
baseUrl: "${n}",
|
|
386
402
|
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
387
403
|
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
388
404
|
// it freely; it is a plain folder name, not a path.
|
|
@@ -390,7 +406,7 @@ export const desktopConfig = {
|
|
|
390
406
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
391
407
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
392
408
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
393
|
-
autoUpdate: { url: "${
|
|
409
|
+
autoUpdate: { url: "${y}" },
|
|
394
410
|
// Whether the support live-chat widget you configured in config.support (Crisp,
|
|
395
411
|
// Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
|
|
396
412
|
// every surface. Set false to keep live chat on your website only - the app then
|
|
@@ -428,7 +444,7 @@ export const desktopConfig = {
|
|
|
428
444
|
background: false
|
|
429
445
|
}
|
|
430
446
|
};
|
|
431
|
-
`),await c(
|
|
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
|
|
432
448
|
// TypeScript config index reads it directly (the Electron main + renderer). Mirrors the
|
|
433
449
|
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
434
450
|
|
|
@@ -437,32 +453,14 @@ export const tenancyConfig = ${e.multiTenancy?`{
|
|
|
437
453
|
organizationLimit: 5,
|
|
438
454
|
billingScope: "${e.demo?"organization":"user"}"
|
|
439
455
|
}`:"{ multiTenant: false }"};
|
|
440
|
-
`),await c(
|
|
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
|
|
441
457
|
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
442
458
|
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
443
459
|
// index re-exports this as config.support.
|
|
444
460
|
|
|
445
461
|
export const supportConfig = ${a};
|
|
446
|
-
`),await c(
|
|
447
|
-
|
|
448
|
-
// renderer, which have no env at all once packaged). Mirrors the support.mjs
|
|
449
|
-
// pattern. The config index re-exports this as config.observability.
|
|
450
|
-
//
|
|
451
|
-
// Off by default and off costs nothing: every surface checks \`sentry.enabled\` and a
|
|
452
|
-
// non-empty \`dsn\` before it dynamically imports the SDK, so nothing ships to your
|
|
453
|
-
// users' browsers and nothing loads on your server. Turn it on by flipping \`enabled\`
|
|
454
|
-
// and pasting your project DSN (Sentry: Settings -> Projects -> Client Keys) - the DSN
|
|
455
|
-
// is public by design (it only authorizes sending events, never reading them), which is
|
|
456
|
-
// why it lives here rather than in env. Server-side, SENTRY_DSN overrides it.
|
|
457
|
-
|
|
458
|
-
export const observabilityConfig = {
|
|
459
|
-
sentry: {
|
|
460
|
-
enabled: false,
|
|
461
|
-
dsn: ""
|
|
462
|
-
}
|
|
463
|
-
};
|
|
464
|
-
`),e.desktop&&await wo(e.projectDir,u,`${l.protocol}-updater`)}import{join as So}from"path";function Eo(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function qt(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(`
|
|
465
|
-
`)}async function Jn(e){let t=So(e.projectDir,"packages/config/src/pricing.ts"),n=e.defaultCurrency;if(e.paymentProvider==="none"){let $=`import type { PricingConfig } from "@repo/config/types";
|
|
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";
|
|
466
464
|
|
|
467
465
|
export const pricingConfig: PricingConfig = {
|
|
468
466
|
defaultPlan: "free",
|
|
@@ -482,7 +480,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
482
480
|
prices: [
|
|
483
481
|
{
|
|
484
482
|
interval: "lifetime",
|
|
485
|
-
amounts: { ${
|
|
483
|
+
amounts: { ${r}: 0 }
|
|
486
484
|
}
|
|
487
485
|
],
|
|
488
486
|
apiRateLimit: { maxRequests: 100 }
|
|
@@ -491,21 +489,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
491
489
|
credits: { enabled: false },
|
|
492
490
|
products: { enabled: false, items: [] }
|
|
493
491
|
};
|
|
494
|
-
`;await c(t,$);return}let
|
|
495
|
-
// !! USD), but your plan prices and credit purchases are denominated in ${
|
|
496
|
-
// !! ${
|
|
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
|
|
493
|
+
// !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
|
|
494
|
+
// !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
497
495
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
498
|
-
`;
|
|
499
|
-
!! ${
|
|
500
|
-
!! plan prices and credit purchases are denominated in ${
|
|
501
|
-
!! carries ~0.42 USD of AI cost - verify every ${
|
|
496
|
+
`;i&&r!=="USD"&&console.warn(`
|
|
497
|
+
!! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
498
|
+
!! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
|
|
499
|
+
!! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
|
|
502
500
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
503
|
-
`);let
|
|
501
|
+
`);let f=i?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
504
502
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
505
503
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
506
504
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
507
505
|
// full utilization runs you at a loss.
|
|
508
|
-
${
|
|
506
|
+
${y} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",h=`import type { PricingConfig } from "@repo/config/types";
|
|
509
507
|
|
|
510
508
|
export const pricingConfig: PricingConfig = {
|
|
511
509
|
defaultPlan: "free",
|
|
@@ -526,7 +524,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
526
524
|
prices: [
|
|
527
525
|
{
|
|
528
526
|
interval: "lifetime",
|
|
529
|
-
amounts: { ${
|
|
527
|
+
amounts: { ${r}: 0 }
|
|
530
528
|
}
|
|
531
529
|
],
|
|
532
530
|
${a}
|
|
@@ -544,18 +542,18 @@ ${a}
|
|
|
544
542
|
],
|
|
545
543
|
prices: [
|
|
546
544
|
{
|
|
547
|
-
${
|
|
545
|
+
${o}
|
|
548
546
|
interval: "month",
|
|
549
|
-
amounts: { ${
|
|
547
|
+
amounts: { ${r}: 9 }
|
|
550
548
|
},
|
|
551
549
|
{
|
|
552
|
-
${
|
|
550
|
+
${o}
|
|
553
551
|
interval: "year",
|
|
554
|
-
amounts: { ${
|
|
555
|
-
anchorAmounts: { ${
|
|
552
|
+
amounts: { ${r}: 90 },
|
|
553
|
+
anchorAmounts: { ${r}: 109 }
|
|
556
554
|
}
|
|
557
555
|
],
|
|
558
|
-
${
|
|
556
|
+
${l}
|
|
559
557
|
},
|
|
560
558
|
{
|
|
561
559
|
id: "pro",
|
|
@@ -573,33 +571,33 @@ ${d}
|
|
|
573
571
|
],
|
|
574
572
|
prices: [
|
|
575
573
|
{
|
|
576
|
-
${
|
|
574
|
+
${o}
|
|
577
575
|
interval: "month",
|
|
578
|
-
amounts: { ${
|
|
579
|
-
anchorAmounts: { ${
|
|
576
|
+
amounts: { ${r}: 29 },
|
|
577
|
+
anchorAmounts: { ${r}: 39 },
|
|
580
578
|
featured: true
|
|
581
579
|
},
|
|
582
580
|
{
|
|
583
|
-
${
|
|
581
|
+
${o}
|
|
584
582
|
interval: "year",
|
|
585
|
-
amounts: { ${
|
|
586
|
-
anchorAmounts: { ${
|
|
583
|
+
amounts: { ${r}: 290 },
|
|
584
|
+
anchorAmounts: { ${r}: 349 }
|
|
587
585
|
}
|
|
588
586
|
],
|
|
589
|
-
${
|
|
587
|
+
${u}
|
|
590
588
|
}
|
|
591
589
|
],
|
|
592
|
-
${
|
|
590
|
+
${f},
|
|
593
591
|
products: {
|
|
594
592
|
enabled: false,
|
|
595
593
|
items: []
|
|
596
594
|
}
|
|
597
595
|
};
|
|
598
|
-
`;await c(t,
|
|
599
|
-
`)}function
|
|
600
|
-
`)}async function
|
|
601
|
-
`+
|
|
602
|
-
`+
|
|
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:
|
|
603
601
|
image: postgres:18-alpine
|
|
604
602
|
ports:
|
|
605
603
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
@@ -614,7 +612,7 @@ ${k},
|
|
|
614
612
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
|
615
613
|
interval: 5s
|
|
616
614
|
timeout: 5s
|
|
617
|
-
retries: 5`),
|
|
615
|
+
retries: 5`),n.push(" postgres_data:")),t.includes("redis")&&(r.push(` redis:
|
|
618
616
|
image: redis:8-alpine
|
|
619
617
|
ports:
|
|
620
618
|
- "\${REDIS_PORT:-6379}:6379"
|
|
@@ -624,27 +622,27 @@ ${k},
|
|
|
624
622
|
test: ["CMD", "redis-cli", "ping"]
|
|
625
623
|
interval: 5s
|
|
626
624
|
timeout: 5s
|
|
627
|
-
retries: 5`),
|
|
625
|
+
retries: 5`),n.push(" redis_data:")),t.includes("mailpit")&&r.push(` mailpit:
|
|
628
626
|
image: axllent/mailpit
|
|
629
627
|
ports:
|
|
630
628
|
- "\${MAILPIT_SMTP_PORT:-1025}:1025"
|
|
631
629
|
- "\${MAILPIT_UI_PORT:-8025}:8025"
|
|
632
630
|
environment:
|
|
633
631
|
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
|
634
|
-
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")&&
|
|
632
|
+
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")&&r.push(` inngest:
|
|
635
633
|
image: inngest/inngest:v1.17.4
|
|
636
634
|
ports:
|
|
637
635
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
638
|
-
command: inngest dev`);let
|
|
639
|
-
${
|
|
636
|
+
command: inngest dev`);let o=`services:
|
|
637
|
+
${r.join(`
|
|
640
638
|
|
|
641
639
|
`)}
|
|
642
|
-
`;
|
|
640
|
+
`;n.length>0&&(o+=`
|
|
643
641
|
volumes:
|
|
644
|
-
${
|
|
642
|
+
${n.join(`
|
|
645
643
|
`)}
|
|
646
|
-
`),await c(
|
|
647
|
-
`)}import{join as
|
|
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";
|
|
648
646
|
import app from "@repo/api";
|
|
649
647
|
import { closeRedis, env, logger } from "@repo/runtime";
|
|
650
648
|
|
|
@@ -675,12 +673,12 @@ bootstrap().catch((error) => {
|
|
|
675
673
|
logger.error("[Backend] Fatal error", error);
|
|
676
674
|
process.exit(1);
|
|
677
675
|
});
|
|
678
|
-
`)}import{readFile as
|
|
679
|
-
export const pool = db.$client
|
|
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";
|
|
680
678
|
import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
|
|
681
679
|
export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
682
680
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
683
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
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";
|
|
684
682
|
import { Redis } from "ioredis";
|
|
685
683
|
import { RedisStore, type RedisReply } from "rate-limit-redis";
|
|
686
684
|
import { env } from "./env";
|
|
@@ -809,7 +807,7 @@ export async function closeRedis() {
|
|
|
809
807
|
closed = true;
|
|
810
808
|
}
|
|
811
809
|
}
|
|
812
|
-
`)}async function
|
|
810
|
+
`)}async function Ns(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
813
811
|
import { redis } from "./redis";
|
|
814
812
|
|
|
815
813
|
export class MutexTimeoutError extends Error {
|
|
@@ -846,7 +844,7 @@ export async function withMutex<T>(
|
|
|
846
844
|
await mutex.release();
|
|
847
845
|
}
|
|
848
846
|
}
|
|
849
|
-
`)}async function
|
|
847
|
+
`)}async function Cs(e){await c(Ct(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
850
848
|
import type { Store } from "hono-rate-limiter";
|
|
851
849
|
import { env } from "./env";
|
|
852
850
|
|
|
@@ -964,7 +962,7 @@ export const limiterStore: Store = createLimiterStore();
|
|
|
964
962
|
|
|
965
963
|
/** No persistent connection to close with Upstash REST. */
|
|
966
964
|
export async function closeRedis(): Promise<void> {}
|
|
967
|
-
`)}async function
|
|
965
|
+
`)}async function $s(e){await c(Ct(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
968
966
|
import { redis } from "./redis";
|
|
969
967
|
|
|
970
968
|
export class MutexTimeoutError extends Error {
|
|
@@ -1009,144 +1007,18 @@ export async function withMutex<T>(
|
|
|
1009
1007
|
await lock.release();
|
|
1010
1008
|
}
|
|
1011
1009
|
}
|
|
1012
|
-
`)}
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
API_URL: z.url(),
|
|
1019
|
-
BASE_URL: z.url().optional(),
|
|
1020
|
-
TRUSTED_ORIGINS: z.string().optional(),
|
|
1021
|
-
AUTH_COOKIE_DOMAIN: z.string().optional(),
|
|
1022
|
-
|
|
1023
|
-
DATABASE_URL: z.url(),
|
|
1024
|
-
${e.cacheProvider==="upstash"?` UPSTASH_REDIS_REST_URL: z.string(),
|
|
1025
|
-
UPSTASH_REDIS_REST_TOKEN: z.string(),`:" REDIS_URL: z.string(),"}
|
|
1026
|
-
|
|
1027
|
-
BETTER_AUTH_SECRET: z.string().min(32),
|
|
1028
|
-
|
|
1029
|
-
GOOGLE_CLIENT_ID: z.string().optional(),
|
|
1030
|
-
GOOGLE_CLIENT_SECRET: z.string().optional(),
|
|
1031
|
-
|
|
1032
|
-
GITHUB_CLIENT_ID: z.string().optional(),
|
|
1033
|
-
GITHUB_CLIENT_SECRET: z.string().optional(),
|
|
1034
|
-
|
|
1035
|
-
FACEBOOK_CLIENT_ID: z.string().optional(),
|
|
1036
|
-
FACEBOOK_CLIENT_SECRET: z.string().optional(),
|
|
1037
|
-
|
|
1038
|
-
DISCORD_CLIENT_ID: z.string().optional(),
|
|
1039
|
-
DISCORD_CLIENT_SECRET: z.string().optional(),
|
|
1040
|
-
|
|
1041
|
-
TWITTER_CLIENT_ID: z.string().optional(),
|
|
1042
|
-
TWITTER_CLIENT_SECRET: z.string().optional(),
|
|
1043
|
-
|
|
1044
|
-
INNGEST_APP_ID: z.string(),
|
|
1045
|
-
INNGEST_EVENT_KEY: z.string(),
|
|
1046
|
-
INNGEST_BASE_URL: z.url(),
|
|
1047
|
-
|
|
1048
|
-
AMAZON_SES_REGION: z.string().optional(),
|
|
1049
|
-
AMAZON_SES_KEY: z.string().optional(),
|
|
1050
|
-
AMAZON_SES_SECRET: z.string().optional(),
|
|
1051
|
-
|
|
1052
|
-
RESEND_API_KEY: z.string().optional(),
|
|
1053
|
-
RESEND_AUDIENCE_ID: z.string().optional(),
|
|
1054
|
-
|
|
1055
|
-
LISTMONK_URL: z.url().optional(),
|
|
1056
|
-
LISTMONK_API_USER: z.string().optional(),
|
|
1057
|
-
LISTMONK_API_TOKEN: z.string().optional(),
|
|
1058
|
-
LISTMONK_LIST_ID: z.coerce.number().int().positive().optional(),
|
|
1059
|
-
|
|
1060
|
-
SMTP_HOST: z.string().optional(),
|
|
1061
|
-
SMTP_PORT: z.coerce.number().int().positive().optional(),
|
|
1062
|
-
SMTP_USER: z.string().optional(),
|
|
1063
|
-
SMTP_PASSWORD: z.string().optional(),
|
|
1064
|
-
|
|
1065
|
-
TWILIO_ACCOUNT_SID: z.string().optional(),
|
|
1066
|
-
TWILIO_AUTH_TOKEN: z.string().optional(),
|
|
1067
|
-
TWILIO_PHONE_NUMBER: z.string().optional(),
|
|
1068
|
-
|
|
1069
|
-
AMAZON_SNS_REGION: z.string().optional(),
|
|
1070
|
-
AMAZON_SNS_KEY: z.string().optional(),
|
|
1071
|
-
AMAZON_SNS_SECRET: z.string().optional(),
|
|
1072
|
-
AMAZON_SNS_SENDER_ID: z.string().optional(),
|
|
1073
|
-
AMAZON_SNS_ORIGINATION_NUMBER: z.string().optional(),
|
|
1074
|
-
|
|
1075
|
-
STRIPE_SECRET_KEY: z.string().optional(),
|
|
1076
|
-
STRIPE_WEBHOOK_SECRET: z.string().optional(),
|
|
1077
|
-
|
|
1078
|
-
POLAR_ACCESS_TOKEN: z.string().optional(),
|
|
1079
|
-
POLAR_WEBHOOK_SECRET: z.string().optional(),
|
|
1080
|
-
|
|
1081
|
-
STORAGE_REGION: z.string().optional(),
|
|
1082
|
-
STORAGE_ENDPOINT: z.string().optional(),
|
|
1083
|
-
STORAGE_ACCESS_KEY_ID: z.string().optional(),
|
|
1084
|
-
STORAGE_SECRET_ACCESS_KEY: z.string().optional(),
|
|
1085
|
-
STORAGE_PUBLIC_BUCKET: z.string().optional(),
|
|
1086
|
-
STORAGE_PRIVATE_BUCKET: z.string().optional(),
|
|
1087
|
-
STORAGE_PUBLIC_URL: z.string().optional(),
|
|
1088
|
-
|
|
1089
|
-
STORAGE_LOCAL_PATH: z.string().optional(),
|
|
1090
|
-
STORAGE_LOCAL_PUBLIC_URL: z.string().optional(),
|
|
1091
|
-
|
|
1092
|
-
DISCORD_WEBHOOK_URL: z.url().optional(),
|
|
1093
|
-
SLACK_WEBHOOK_URL: z.url().optional(),
|
|
1094
|
-
TELEGRAM_BOT_TOKEN: z
|
|
1095
|
-
.string()
|
|
1096
|
-
.regex(/^\\d+:[A-Za-z0-9_-]+$/, "Invalid Telegram bot token format")
|
|
1097
|
-
.optional(),
|
|
1098
|
-
TELEGRAM_CHAT_ID: z.string().optional(),
|
|
1099
|
-
TELEGRAM_TOPIC_ID: z.string().optional(),
|
|
1100
|
-
|
|
1101
|
-
TURNSTILE_SECRET_KEY: z.string().optional(),
|
|
1102
|
-
|
|
1103
|
-
CONTENT_API_KEY: z.string().min(16).optional(),
|
|
1104
|
-
|
|
1105
|
-
ANTHROPIC_API_KEY: z.string().optional(),
|
|
1106
|
-
OPENAI_API_KEY: z.string().optional(),
|
|
1107
|
-
OPENROUTER_API_KEY: z.string().optional(),
|
|
1108
|
-
|
|
1109
|
-
MASTRA_TELEMETRY_DISABLED: z.string().optional(),
|
|
1110
|
-
|
|
1111
|
-
/** Server-side override for \`config.observability.sentry.dsn\`. Optional: the committed config value is the default. */
|
|
1112
|
-
SENTRY_DSN: z.string().optional()
|
|
1113
|
-
});
|
|
1114
|
-
|
|
1115
|
-
export const env = (() => {
|
|
1116
|
-
// Compute API_URL fallback BEFORE Zod sees the input. Zod 4.4 ignores
|
|
1117
|
-
// \`z.preprocess\` output when the input key is absent from the parent
|
|
1118
|
-
// object - this guarantees the key is always present and avoids the regression.
|
|
1119
|
-
const rawEnv = { ...process.env };
|
|
1120
|
-
rawEnv.API_URL =
|
|
1121
|
-
rawEnv.API_URL ||
|
|
1122
|
-
rawEnv.NUXT_PUBLIC_API_URL ||
|
|
1123
|
-
rawEnv.NEXT_PUBLIC_API_URL ||
|
|
1124
|
-
rawEnv.PUBLIC_API_URL;
|
|
1125
|
-
const parsed = EnvSchema.safeParse(rawEnv);
|
|
1126
|
-
|
|
1127
|
-
if (!parsed.success) {
|
|
1128
|
-
const message = parsed.error.issues
|
|
1129
|
-
.map((issue) => \`\${issue.path.join(".") || "unknown"}: \${issue.message}\`)
|
|
1130
|
-
.join(", ");
|
|
1131
|
-
throw new Error(\`Invalid runtime package environment: \${message}\`);
|
|
1132
|
-
}
|
|
1133
|
-
return parsed.data;
|
|
1134
|
-
})();
|
|
1135
|
-
|
|
1136
|
-
const parsedApiUrl = new URL(env.API_URL);
|
|
1137
|
-
export const apiBasePath = parsedApiUrl.pathname === "/" ? "" : parsedApiUrl.pathname;
|
|
1138
|
-
export const apiOrigin = parsedApiUrl.origin;
|
|
1139
|
-
`}import{readFile as Vo}from"fs/promises";import{join as V}from"path";var xt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function Fe(e){let t=await Vo(e,"utf-8");return JSON.parse(t)}async function Ve(e,t){await c(e,JSON.stringify(t,null," ")+`
|
|
1140
|
-
`)}function pt(e,t){for(let n of t)delete e.dependencies?.[n],delete e.devDependencies?.[n]}function Me(e,t,n,r=!1){let i=r?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=n}async function ir(e){await Bo(e),await Ko(e),await Go(e),await zo(e),e.frontend==="nextjs"?await qo(e):await Jo(e)}async function Bo(e){let t=V(e.projectDir,"packages/api/package.json"),n=await Fe(t);pt(n,["sharp","@types/sharp"]),await Ve(t,n)}async function Ko(e){let t=V(e.projectDir,"packages/runtime/package.json"),n=await Fe(t);e.cacheProvider==="upstash"&&(pt(n,["ioredis","rate-limit-redis","redis-semaphore"]),Me(n,"@upstash/redis",xt["@upstash/redis"]),Me(n,"@upstash/lock",xt["@upstash/lock"])),await Ve(t,n)}async function Go(e){let t=V(e.projectDir,"packages/database/package.json"),n=await Fe(t);e.databaseProvider==="neon"?(pt(n,["pg","@types/pg"]),Me(n,"@neondatabase/serverless",xt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(pt(n,["pg","@types/pg"]),Me(n,"postgres",xt.postgres)),await Ve(t,n)}async function zo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/backend/package.json"),n=await Fe(t);e.deploymentTarget!=="node"&&pt(n,["@hono/node-server"]),await Ve(t,n)}var Ho=["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"],Yo=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Jo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web-nuxt");await tt(V(t,"server/api/[...paths].ts"),t);for(let o of Ho)await tt(V(t,o),t);let n=V(t,"package.json"),r=await Fe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Me(r,"@repo/api",i,!0)),await Ve(n,r)}async function qo(e){if(e.architecture!=="separate")return;let t=V(e.projectDir,"apps/web-next");await tt(V(t,"app/api/[[...rest]]/route.ts"),t);for(let o of Yo)await tt(V(t,o),t);let n=V(t,"package.json"),r=await Fe(n),i=r.dependencies?.["@repo/api"];i&&(delete r.dependencies?.["@repo/api"],Me(r,"@repo/api",i,!0)),await Ve(n,r)}import{readFile as sr}from"fs/promises";import{join as ar}from"path";async function cr(e){let t=ar(e.projectDir,"turbo.json"),n;try{n=await sr(t,"utf-8")}catch{return}let r=JSON.parse(n),i=r.tasks?.build;if(!i)return;let o=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(i.env)){let d=i.env.filter(l=>l!==o);d.length!==i.env.length&&(i.env=d,a=!0)}if(Array.isArray(i.outputs)){let d=i.outputs.filter(l=>!s.has(l));d.length!==i.outputs.length&&(i.outputs=d,a=!0)}a&&await c(t,JSON.stringify(r,null," ")+`
|
|
1141
|
-
`)}var Wo=["base.json","node.json","next.json"],or="GenerateSaaS ";async function pr(e){if(!e.demo)for(let t of Wo){let n=ar(e.projectDir,"tooling/typescript",t),r;try{r=await sr(n,"utf-8")}catch{continue}let i=JSON.parse(r);typeof i.display!="string"||!i.display.startsWith(or)||(i.display=i.display.slice(or.length),await c(n,JSON.stringify(i,null," ")+`
|
|
1142
|
-
`))}}import{readFile as Xo,rm as Zo}from"fs/promises";import{existsSync as lr}from"fs";import{join as dr}from"path";async function ur(e){if(e.frontend==="nuxt")return;let t=dr(e.projectDir,"packages/i18n/package.json");if(!lr(t))throw new Error(`pruneI18nNuxt: expected ${t} to exist - did the i18n package move?`);let n=JSON.parse(await Xo(t,"utf-8")),r=!!(n.exports?.["./module"]??n.exports?.["./nuxt"]),i=!1;if(n.exports)for(let s of["./module","./nuxt"])s in n.exports&&(delete n.exports[s],i=!0);n.devDependencies&&"@nuxt/kit"in n.devDependencies&&(delete n.devDependencies["@nuxt/kit"],i=!0),i&&await c(t,JSON.stringify(n,null," ")+`
|
|
1143
|
-
`);let o=dr(e.projectDir,"packages/i18n/nuxt");if(r&&!lr(o))throw new Error(`pruneI18nNuxt: packages/i18n declares a Nuxt export surface but ${o} is missing - did the i18n Nuxt module move?`);await Zo(o,{recursive:!0,force:!0})}import{readFile as fr,rm as Qo}from"fs/promises";import{join as _t}from"path";async function gr(e){e.cacheProvider==="upstash"&&await Promise.all([mr(_t(e.projectDir,"packages/runtime/tests/setup.ts")),mr(_t(e.projectDir,"packages/mail/tests/setup.ts")),es(e.projectDir),Qo(_t(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})])}async function mr(e){let t;try{t=await fr(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let n=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
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",
|
|
1144
1016
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1145
|
-
`);
|
|
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",
|
|
1146
1018
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1147
|
-
`),
|
|
1019
|
+
`),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",
|
|
1148
1020
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1149
|
-
`),
|
|
1021
|
+
`),n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`vi.mock("@upstash/redis", () => {
|
|
1150
1022
|
class Redis {
|
|
1151
1023
|
get = vi.fn().mockResolvedValue(null);
|
|
1152
1024
|
set = vi.fn().mockResolvedValue("OK");
|
|
@@ -1163,26 +1035,26 @@ vi.mock("@upstash/lock", () => {
|
|
|
1163
1035
|
return { Lock };
|
|
1164
1036
|
});
|
|
1165
1037
|
|
|
1166
|
-
$1`),r
|
|
1167
|
-
`).find(
|
|
1168
|
-
`,"","configuration.mdx companion config-table row",
|
|
1169
|
-
`),
|
|
1170
|
-
`))}async function
|
|
1171
|
-
`)}async function
|
|
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
|
|
1172
1044
|
|
|
1173
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).
|
|
1174
1046
|
|
|
1175
|
-
`,"","companion index.mdx desktop-setup section",
|
|
1047
|
+
`,"","companion index.mdx desktop-setup section",r),await j(R(t,`docs/${n}/companion/terminal.mdx`),`## In the desktop app
|
|
1176
1048
|
|
|
1177
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).
|
|
1178
1050
|
|
|
1179
|
-
`,"","companion terminal.mdx desktop-panel section",
|
|
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:
|
|
1180
1052
|
workflow_run:
|
|
1181
1053
|
workflows: ["Tag Release"]
|
|
1182
1054
|
branches: [main]
|
|
1183
1055
|
types: [completed]
|
|
1184
|
-
workflow_dispatch:`,
|
|
1185
|
-
workflow_dispatch:`;async function
|
|
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:
|
|
1186
1058
|
postgres:
|
|
1187
1059
|
image: postgres:18-alpine
|
|
1188
1060
|
env:
|
|
@@ -1196,13 +1068,13 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
|
|
|
1196
1068
|
--health-interval 10s
|
|
1197
1069
|
--health-timeout 5s
|
|
1198
1070
|
--health-retries 5
|
|
1199
|
-
`,
|
|
1071
|
+
`,i=t?"postgres://test:test@localhost:5432/saas_test":"postgres://postgres:postgres@localhost:5432/saas",s=r?`
|
|
1200
1072
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1201
1073
|
UPSTASH_REDIS_REST_TOKEN: test-token`:"",a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1202
1074
|
STRIPE_SECRET_KEY: test
|
|
1203
1075
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1204
1076
|
POLAR_ACCESS_TOKEN: test
|
|
1205
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
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.)
|
|
1206
1078
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1207
1079
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1208
1080
|
|
|
@@ -1226,7 +1098,7 @@ jobs:
|
|
|
1226
1098
|
name: Checks
|
|
1227
1099
|
runs-on: ubuntu-latest
|
|
1228
1100
|
timeout-minutes: 20
|
|
1229
|
-
${
|
|
1101
|
+
${o} env:
|
|
1230
1102
|
CONTENT_API_KEY: test-contentapi-key-16chars${s}${a}
|
|
1231
1103
|
STORAGE_REGION: test
|
|
1232
1104
|
STORAGE_ENDPOINT: http://test
|
|
@@ -1240,7 +1112,7 @@ ${i} env:
|
|
|
1240
1112
|
|
|
1241
1113
|
- run: pnpm lint
|
|
1242
1114
|
|
|
1243
|
-
${
|
|
1115
|
+
${n?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
1244
1116
|
# the type graph (Nuxt + Pinia + vue-i18n + content collections)
|
|
1245
1117
|
# crosses a threshold. Bump to 6 GB; ubuntu-latest has ~7 GB RAM.
|
|
1246
1118
|
- run: pnpm check-types
|
|
@@ -1248,53 +1120,156 @@ ${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
|
1248
1120
|
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1249
1121
|
|
|
1250
1122
|
- name: Write root env
|
|
1251
|
-
run: echo "DATABASE_URL=${
|
|
1123
|
+
run: echo "DATABASE_URL=${i}" > .env
|
|
1252
1124
|
|
|
1253
1125
|
- run: pnpm test
|
|
1254
|
-
`}import{readFile as
|
|
1255
|
-
`))}async function
|
|
1256
|
-
`))}async function
|
|
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
|
|
1257
1129
|
// "./polar/index" or "./none/index" (other folders are kept in place).
|
|
1258
|
-
export { ops } from "./${
|
|
1259
|
-
`;await c(
|
|
1260
|
-
`).filter(s=>!
|
|
1261
|
-
`)}import{
|
|
1262
|
-
|
|
1263
|
-
`)
|
|
1264
|
-
|
|
1265
|
-
`),await c(
|
|
1266
|
-
`)}
|
|
1267
|
-
`);
|
|
1268
|
-
|
|
1269
|
-
`),
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
`),await Hr(v,v)}await qr(v),await Gr(U,$),r.stop("Project files generated.")}catch(h){r.stop("Generation failed."),y.cancel(O(h)),process.exit(1)}!await Xr(v)&&U.demo===!0&&(y.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let X=await Zr(v);X&&U.demo!==!0&&e.dbMigration!==!1&&await Qr(v),await ei(v),X&&await ti(v);let fe=Re("docker"),ge=Ft(U).map(h=>h.key).filter(h=>!U.credentials?.[h]);ni(U,{pnpmInstalled:X,dockerAvailable:fe,skippedCredentials:ge}),gn(),y.log.info(na.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as cn}from"fs";import{readFile as mi}from"fs/promises";import{join as ze,resolve as ua}from"path";import*as w from"@clack/prompts";import z from"picocolors";import{mkdtemp as sa,rm as aa}from"fs/promises";import{tmpdir as ca}from"os";import{join as pa}from"path";async function an(e,t,n,r){let i=await sa(pa(ca(),"generatesaas-stage-"));try{await St(e,t,i),await Ct({...n,projectDir:i}),await nn(i,r)}finally{await aa(i,{recursive:!0,force:!0})}}function ut(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var si=[{key:"frontend",label:"Frontend framework",hint:"Nuxt (Vue) or Next.js (React).",category:"Project",kind:"enum",default:"nuxt",choices:ke,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:De,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:te,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:ne,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:re,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:Ce,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:ee,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:Ne,adoptable:!1,impact:"config",shapesTree:!1},{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.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0,requiresLabel:"requires AI features"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>ut(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 la(e,t){return e[t]!==void 0}function ai(e){return si.filter(t=>t.adoptable&&!la(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 ci(e){let t={};for(let n of si)if(typeof n.default=="function"){if(n.requires&&!n.requires(e))continue;t[n.key]=n.default(e)}else t[n.key]=Array.isArray(n.default)?[...n.default]:n.default;return{...t,...e}}function pi(e){return e?"ON":"OFF"}var mt="packages/config/src/index.ts";function li(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",n=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(r=>!(r==="postgres"&&t)&&!(r==="redis"&&n)).sort()}function di(e){return[...Oe({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var da=[{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 ${mt} 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 ${mt} 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 ${mt}. 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===ut(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${pi(e.aiBuiltin)}, but it is now a plain config value generated ${pi(ut(e))} for a project ${ut(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${mt} 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 ${mt} 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=>li(e).join(",")===di(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${li(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 ${di(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===wn.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 (${Ie.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 ui(e){let t=[];for(let n of da){if(n.normalize?.(e),e[n.key]===void 0)continue;(!n.applies||n.applies(e))&&!n.preserved(e)&&t.push({key:n.key,message:n.describe(e),severity:n.severity}),delete e[n.key]}return t}function fi(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,n)=>{let r=t==="auto"?"auto":void 0,i=ua(n.cwd??process.cwd()),o=ze(i,ae),s;try{s=JSON.parse(await mi(o,"utf-8"))}catch{w.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let a;try{a=await Le()}catch(u){w.cancel(O(u)),process.exit(1)}let d=oe(a),l=w.spinner();try{l.start("Verifying access...");let u;try{u=await le(d)}catch(I){throw I instanceof N&&I.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):I}let k=Lt(u,"update");if(!k.ok)throw new Error(k.message);l.stop("Access verified."),Se(a),l.start("Fetching latest skill files...");let A=await xn(d,u.latest);await on(i,A.skillMd,A.scripts);let $=Ie;if(l.stop("Skills updated."),w.log.success(`Skill files installed to ${z.cyan($.length.toString())} locations.`),s.version===u.latest){w.log.info(`Already on the latest version (${s.version}).`);return}let v=JSON.stringify(s);bn(s),await ma(s,Sn(s),r),await ga(ui(s),r);let U=ai(s),me=ci(s),X=JSON.stringify(me)!==v;if(s=me,s.licenseToken)try{let I=await On(d,{currentToken:s.licenseToken,newVersion:u.latest});s.licenseToken=I.token,I.licenseKeyHash&&(s.licenseKeyHash=I.licenseKeyHash),await c(o,JSON.stringify(s,null," ")+`
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1130
|
+
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"]);
|
|
1134
|
+
`,`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=`
|
|
1136
|
+
});
|
|
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
|
|
1143
|
+
* there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
|
|
1144
|
+
*
|
|
1145
|
+
* To change providers, set \`errorTracking\` in \`.generatesaas/manifest.json\` to the one you want and
|
|
1146
|
+
* run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
|
|
1147
|
+
* 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(`
|
|
1151
|
+
}
|
|
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;
|
|
1158
|
+
}
|
|
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;
|
|
1192
|
+
}
|
|
1193
|
+
return sentryDesktopMainOps;`,tc=` if (errorTracking.provider !== "sentry") {
|
|
1194
|
+
announceMissingDesktopSdk(errorTracking.provider);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
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;
|
|
1210
|
+
}
|
|
1211
|
+
return sentryDesktopRendererOps;`,mc=` if (errorTracking.provider !== "sentry") {
|
|
1212
|
+
announceMissingDesktopSdk(errorTracking.provider);
|
|
1213
|
+
return;
|
|
1214
|
+
}
|
|
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(`
|
|
1241
|
+
`)}
|
|
1242
|
+
|
|
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.
|
|
1244
|
+
|
|
1245
|
+
${l.reason}
|
|
1246
|
+
|
|
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}
|
|
1253
|
+
|
|
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}
|
|
1255
|
+
|
|
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}
|
|
1257
|
+
|
|
1258
|
+
${a??"_No changelog available for this release._"}`)}return{text:i.join(`
|
|
1259
|
+
|
|
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";
|
|
1289
1264
|
`,` licenseHeartbeatFunction,
|
|
1290
1265
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1291
1266
|
`,` .route("/license", licenseRoutes)
|
|
1292
|
-
`]}];function $
|
|
1293
|
-
`).filter(
|
|
1294
|
-
`);return r
|
|
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",`
|
|
1295
1270
|
Examples:
|
|
1296
1271
|
$ generatesaas init Interactive setup
|
|
1297
1272
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1298
1273
|
$ generatesaas status Check for updates
|
|
1299
1274
|
$ generatesaas auth Set or update API key
|
|
1300
|
-
`);
|
|
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)});
|