generatesaas 2.3.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js
CHANGED
|
@@ -1,25 +1,30 @@
|
|
|
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
|
-
`)}
|
|
14
|
-
`).find(
|
|
15
|
-
`,""
|
|
16
|
-
`).find(
|
|
17
|
-
`,""
|
|
18
|
-
`,""
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
`)}
|
|
22
|
-
|
|
2
|
+
import{Command as Rl}from"commander";import*as ls from"@clack/prompts";import{existsSync as Lc,readdirSync as jc,rmSync as Mc}from"fs";import{join as Uc,resolve as Vc}from"path";import{Option as ne}from"commander";import*as b from"@clack/prompts";import*as Pt from"@clack/prompts";import tr from"picocolors";function Vr(e){let t=e?` GenerateSaaS v${e} `:" GenerateSaaS ";Pt.intro(tr.bgYellow(tr.black(t)))}function Fr(){Pt.outro(tr.yellow("Happy building!"))}import*as u from"@clack/prompts";import h from"picocolors";var ct={fullstack:{label:"Fullstack",hint:"Frontend hosts the API - works on serverless or long-running"},separate:{label:"Separate",hint:"Standalone Hono backend - long-running runtimes only (Docker, Render, Fly.io, Railway, Coolify, Dokploy)"}},It={stripe:{label:"Stripe"},polar:{label:"Polar"},none:{label:"None",hint:"disable payments"}},Tt={smtp:{label:"SMTP",hint:"Mailpit for local dev"},ses:{label:"Amazon SES"},resend:{label:"Resend"}},_t={sentry:{label:"Sentry",hint:"web, server and desktop - release health, tracing, alerting"},posthog:{label:"PostHog",hint:"web and server, plus LLM analytics - no Electron SDK, so a desktop build reports nothing"}},Br={postgres:{label:"PostgreSQL",hint:"port 5432",port:5432},redis:{label:"Redis",hint:"port 6379",port:6379},inngest:{label:"Inngest",hint:"port 8288",port:8288},mailpit:{label:"Mailpit",hint:"port 1025",port:1025}};var Ie={USD:{symbol:"$",name:"US Dollar",place:"left",space:!1},EUR:{symbol:"\u20AC",name:"Euro",place:"right",space:!1},GBP:{symbol:"\xA3",name:"British Pound",place:"left",space:!1},CAD:{symbol:"CA$",name:"Canadian Dollar",place:"left",space:!1},AUD:{symbol:"A$",name:"Australian Dollar",place:"left",space:!1},BRL:{symbol:"R$",name:"Brazilian Real",place:"left",space:!1},JPY:{symbol:"\xA5",name:"Japanese Yen",place:"left",space:!1}};var G={node:{label:"Node.js / Docker",hint:"long-running runtime - Render, Fly.io, Railway, Coolify, Dokploy, VPS",edgeRuntime:!1},vercel:{label:"Vercel",hint:"serverless functions",edgeRuntime:!0}},Te={postgres:{label:"PostgreSQL (self-hosted)",hint:"local Docker, drizzle-orm/node-postgres",managed:!1,envVars:[{key:"DATABASE_URL",defaultValue:"postgres://postgres:postgres@localhost:5432/saas"}]},neon:{label:"Neon",hint:"serverless Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Neon connection string"}]},supabase:{label:"Supabase",hint:"managed Postgres",managed:!0,envVars:[{key:"DATABASE_URL",comment:"# TODO: Add your Supabase connection string"}]}},_e={redis:{label:"Redis (self-hosted)",hint:"local Docker, ioredis",managed:!1,envVars:[{key:"REDIS_URL",defaultValue:"redis://localhost:6379"}]},upstash:{label:"Upstash",hint:"serverless Redis",managed:!0,envVars:[{key:"UPSTASH_REDIS_REST_URL",comment:"# TODO: Add your Upstash REST URL"},{key:"UPSTASH_REDIS_REST_TOKEN",comment:"# TODO: Add your Upstash REST token"}]}},Ke=[{target:"vercel",provider:"redis",reason:"Vercel serverless cannot maintain persistent Redis connections. Consider Upstash."},{target:"vercel",provider:"postgres",reason:"Vercel serverless cannot pool connections to a self-hosted Postgres. Use Neon or Supabase - both are managed, connection-pooled Postgres."}],Ge=[{architecture:"separate",target:"vercel",reason:"Standalone backends need a long-running runtime. Vercel's per-function TypeScript check conflicts with pnpm's isolated install. Use --architecture fullstack for serverless, or deploy the standalone backend to a long-running runtime (Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS via Docker)."}],ds=[{feature:"runner",target:"vercel",reason:"Serverless (Vercel) cannot hold a connection open, and the runner holds one open per paired device. Deploy to a long-running runtime instead (Node.js / Docker on Render, Fly.io, Railway, Coolify, Dokploy, or your own VPS)."}];function ie(e){return ds.find(t=>e[t.feature]===!0&&e.deploymentTarget===t.target)}var se={serverless:{label:"Serverless",hint:"Vercel + Neon + Upstash",values:{deploymentTarget:"vercel",databaseProvider:"neon",cacheProvider:"upstash"}},selfhost:{label:"Self-host",hint:"Docker or Node + Postgres + Redis",values:{deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis"}}},Oe=Object.keys(se);function rr(e){let t=[];for(let r of Ke)if(e.deploymentTarget===r.target&&(e.databaseProvider===r.provider||e.cacheProvider===r.provider)){let n=e.databaseProvider===r.provider?"databaseProvider":"cacheProvider";t.push(`\`${n}: "${r.provider}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`)}for(let r of Ge)e.deploymentTarget===r.target&&e.architecture===r.architecture&&t.push(`\`architecture: "${r.architecture}"\` with \`deploymentTarget: "${r.target}"\` - ${r.reason}`);return t}var Kr=["Local file storage (sharp, geoip-lite)","SMTP email (use Resend or SES instead)","Content API git integration"];function He(e){let t=[];return e.databaseProvider==="postgres"&&t.push("postgres"),e.cacheProvider==="redis"&&t.push("redis"),e.emailProvider==="smtp"&&t.push("mailpit"),t.push("inngest"),t}var Ye=["fullstack","separate"],We=["stripe","polar","none"],qe=["smtp","ses","resend"];var Gr=["claude-code","cursor","codex","gemini-cli","windsurf"],oe=["USD","EUR","GBP","CAD","AUD","BRL","JPY"],ae=["node","vercel"],ce=["postgres","neon","supabase"],le=["redis","upstash"],B=["sentry","posthog"];function Hr(e,t){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t}function Ot(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function xt(e){return/^[a-z][a-z0-9-]*$/.test(e)}function D(e){return e instanceof Error?e.message:String(e)}var Yr=["runner"];function nr(e){if(!Yr.some(r=>e[r]===!0))return e;if(e.ai===!1)throw new Error("--runner requires AI features; remove --no-ai.");return e.ai===void 0&&(e.ai=!0),e}function lt(e){if(e.webAi!==!1)return e;if(e.ai===!1)throw new Error("--no-web-ai requires --ai (the desktop app is where AI lives when the web surface is off).");if(e.desktop===!1)throw new Error("--no-web-ai requires --desktop - with the web AI surface off, the desktop app is the only place your AI features exist.");if(e.runner===!0)throw new Error("--runner needs the web AI surface; drop --runner or keep web AI.");return e}function Wr(e){return Yr.some(r=>e[r]===!0)&&(e.ai=!0),e}function qr(e){if(e.webAi!==!1)return[];let t=[];return e.desktop!==!0&&t.push("`desktop` is not true, so this project has no desktop app - and with the web AI surface off, that app is the only place its AI features would exist."),e.runner===!0&&t.push("`runner` is true, and the runner's pairing, install and Runners screens are part of the web AI surface."),t}function zr(e){let t=us(e,e.desktopAi);return delete e.desktopAi,t}function us(e,t){return e.desktop!==!0?{kind:"none"}:t===!0&&e.ai!==!0?{kind:"legacy-desktop-ai"}:t===!1&&e.ai===!0?{kind:"desktop-gains-ai"}:{kind:"none"}}function Jr(e){let t={};if(e.name!==void 0){if(!xt(e.name))throw new Error(`Invalid project name "${e.name}". Use lowercase letters, numbers, and hyphens only. Must start with a letter.`);t.projectName=e.name}if(e.appName!==void 0){if(!e.appName.trim())throw new Error("App name cannot be empty.");t.appName=e.appName}if(e.location!==void 0?t.projectDir=e.location==="."?process.cwd():e.location:t.projectName!==void 0&&(t.projectDir=`./${t.projectName}`),e.architecture!==void 0&&(t.architecture=e.architecture),e.payment!==void 0&&(t.paymentProvider=e.payment),e.email!==void 0&&(t.emailProvider=e.email),e.org!==void 0&&(t.multiTenancy=e.org),e.blog!==void 0&&(t.blog=e.blog),e.docs!==void 0&&(t.docs=e.docs),e.desktop!==void 0&&(t.desktop=e.desktop),e.ai!==void 0&&(t.ai=e.ai),e.webAi!==void 0&&(t.webAi=e.webAi),e.runner!==void 0&&(t.runner=e.runner),nr(t),lt(t),e.revenueSharing!==void 0&&(t.revenueSharing=e.revenueSharing),e.credits!==void 0){if(e.credits===!0&&e.payment==="none")throw new Error("--credits requires a payment provider (got --payment none).");t.credits=e.credits}if(e.currency!==void 0){if(!oe.includes(e.currency))throw new Error(`Invalid currency "${e.currency}". Valid values: ${oe.join(", ")}`);t.defaultCurrency=e.currency}if(e.deploy!==void 0){if(!ae.includes(e.deploy))throw new Error(`Invalid deployment target "${e.deploy}". Valid values: ${ae.join(", ")}`);t.deploymentTarget=e.deploy}if(e.database!==void 0){if(!ce.includes(e.database))throw new Error(`Invalid database provider "${e.database}". Valid values: ${ce.join(", ")}`);t.databaseProvider=e.database}if(e.cache!==void 0){if(!le.includes(e.cache))throw new Error(`Invalid cache provider "${e.cache}". Valid values: ${le.join(", ")}`);t.cacheProvider=e.cache}if(e.observability!==void 0){let r=e.observability.split(",").map(i=>i.trim()).filter(Boolean),n=r.filter(i=>!B.includes(i));if(n.length>0)throw new Error(`Invalid observability provider ${JSON.stringify(n.join(", "))}. Valid values: ${B.join(", ")}`);t.observability=r}if(e.preset!==void 0){if(!Oe.includes(e.preset))throw new Error(`Invalid preset "${e.preset}". Valid values: ${Oe.join(", ")}`);let r=se[e.preset].values;t.deploymentTarget??=r.deploymentTarget,t.databaseProvider??=r.databaseProvider,t.cacheProvider??=r.cacheProvider}if(e.demo===!0&&(t.demo=!0),e.baseUrl!==void 0){let r=e.baseUrl.trim();if(r==="")throw new Error("--base-url cannot be empty. Provide an absolute URL like https://example.com.");let n;try{n=new URL(r)}catch{throw new Error(`Invalid --base-url "${e.baseUrl}". Must be an absolute URL like https://example.com.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new Error(`Invalid --base-url "${e.baseUrl}". Must use http or https.`);t.baseUrl=`${n.protocol}//${n.host}`}return t}var ze={projectName:"my-saas",architecture:"fullstack",paymentProvider:"stripe",emailProvider:"smtp",multiTenancy:!1,blog:!0,docs:!1,desktop:!1,ai:!1,webAi:!0,runner:!1,revenueSharing:!1,credits:!0,defaultCurrency:"USD",deploymentTarget:"node",databaseProvider:"postgres",cacheProvider:"redis",observability:[]};function Xr(e){let t=e.projectName??ze.projectName,r=e.projectDir??`./${t}`,n=e.appName??Ot(t),i=e.deploymentTarget??ze.deploymentTarget,o=G[i]?.edgeRuntime??!1,s=e.databaseProvider??(o?"neon":ze.databaseProvider),a=e.cacheProvider??(o?"upstash":ze.cacheProvider),p=e.emailProvider??(o?"resend":ze.emailProvider),m={...ze,...e,projectName:t,appName:n,projectDir:r,deploymentTarget:i,databaseProvider:s,cacheProvider:a,emailProvider:p};m.paymentProvider==="none"&&(m.credits=!1);for(let g of Ke){if(m.deploymentTarget!==g.target)continue;let k=m.databaseProvider===g.provider?"database":"cache";if(m.databaseProvider===g.provider||m.cacheProvider===g.provider)throw new Error(`Incompatible: --deploy ${g.target} + --${k} ${g.provider}. ${g.reason}`)}for(let g of Ge)if(m.architecture===g.architecture&&m.deploymentTarget===g.target)throw new Error(`Incompatible: --architecture ${g.architecture} + --deploy ${g.target}. ${g.reason}`);let w=ie(m);if(w)throw new Error(`Incompatible: --${w.feature} + --deploy ${w.target}. ${w.reason}`);return lt(m),m}function S(e){u.isCancel(e)&&(u.cancel("Setup cancelled."),process.exit(0))}function ir(e){let t=[];return e.databaseProvider==="neon"&&t.push({key:"DATABASE_URL",message:"Neon connection string (optional):",placeholder:"postgres://...",secret:!0}),e.databaseProvider==="supabase"&&t.push({key:"DATABASE_URL",message:"Supabase connection string (optional):",placeholder:"postgres://...",secret:!0}),e.cacheProvider==="upstash"&&(t.push({key:"UPSTASH_REDIS_REST_URL",message:"Upstash REST URL (optional):",placeholder:"https://...",secret:!1}),t.push({key:"UPSTASH_REDIS_REST_TOKEN",message:"Upstash REST token (optional):",secret:!0})),e.paymentProvider==="stripe"&&(t.push({key:"STRIPE_SECRET_KEY",message:"Stripe secret key (optional):",placeholder:"sk_test_...",secret:!0}),t.push({key:"STRIPE_WEBHOOK_SECRET",message:"Stripe webhook secret (optional):",placeholder:"whsec_...",secret:!0})),e.paymentProvider==="polar"&&(t.push({key:"POLAR_ACCESS_TOKEN",message:"Polar access token (optional):",secret:!0}),t.push({key:"POLAR_WEBHOOK_SECRET",message:"Polar webhook secret (optional):",secret:!0})),e.emailProvider==="resend"&&t.push({key:"RESEND_API_KEY",message:"Resend API key (optional):",placeholder:"re_...",secret:!0}),e.emailProvider==="ses"&&(t.push({key:"AMAZON_SES_REGION",message:"Amazon SES region (optional):",placeholder:"us-east-1",secret:!1}),t.push({key:"AMAZON_SES_KEY",message:"Amazon SES access key (optional):",secret:!0}),t.push({key:"AMAZON_SES_SECRET",message:"Amazon SES secret (optional):",secret:!0})),e.demo&&t.push({key:"TURNSTILE_SECRET_KEY",message:"Cloudflare Turnstile secret key (optional):",secret:!0}),t}async function Zr(e,t){let r=!1;e&&nr(e),e&<(e),u.log.info(h.bold("Project"));let n=e?.projectName??await(async()=>{r=!0;let c=await u.text({message:"Project name:",placeholder:"my-saas",validate:d=>{if(!d?.trim())return"Project name is required.";if(!xt(d))return"Use lowercase letters, numbers, and hyphens only. Must start with a letter."}});return S(c),c})(),i=e?.appName??await(async()=>{r=!0;let c=await u.text({message:"App name:",initialValue:Ot(n),validate:d=>{if(!d?.trim())return"App name is required."}});return S(c),c})(),o=e?.projectDir??await(async()=>{r=!0;let c=await u.text({message:"Project location:",initialValue:`./${n}`});return S(c),c==="."?process.cwd():c})();u.log.info(h.bold("Infrastructure"));let s={};if(e?.deploymentTarget===void 0&&e?.databaseProvider===void 0&&e?.cacheProvider===void 0){r=!0;let c=await u.select({message:"Infrastructure:",options:[...Oe.map(d=>({value:d,label:se[d].label,hint:se[d].hint})),{value:"custom",label:"Customize",hint:"choose each piece yourself"}]});if(S(c),c!=="custom"){let d=se[c].values;s.deploymentTarget=d.deploymentTarget,s.databaseProvider=d.databaseProvider,s.cacheProvider=d.cacheProvider,u.log.info(`${se[c].label}: ${se[c].hint}.`)}}let a=e?.deploymentTarget??s.deploymentTarget??"node";if(e?.deploymentTarget===void 0&&s.deploymentTarget===void 0){r=!0;let c=await u.select({message:"Deployment target:",options:ae.map(d=>({value:d,label:G[d].label,hint:G[d].hint}))});S(c),a=c}let p=e?.architecture?Ge.find(c=>c.architecture===e.architecture&&c.target===a):void 0;if(p)throw new Error(`Incompatible: --architecture ${p.architecture} + --deploy ${p.target}. ${p.reason}`);let m=ie({...e,deploymentTarget:a});if(m)throw new Error(`Incompatible: --${m.feature} + --deploy ${m.target}. ${m.reason}`);let w=ie({runner:!0,deploymentTarget:a})!==void 0,g=new Set(Ge.filter(c=>c.target===a).map(c=>c.architecture)),k=Ye.filter(c=>!g.has(c)),A=e?.architecture??await(async()=>{if(k.length===1){let d=k[0];return u.log.info(`Auto-selected ${ct[d].label} architecture (only compatible option for ${G[a].label}).`),d}r=!0;let c=await u.select({message:"Architecture:",options:k.map(d=>({value:d,label:ct[d].label,hint:ct[d].hint}))});return S(c),c})(),f=e?.databaseProvider??s.databaseProvider??await(async()=>{r=!0;let c=ce.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${Te[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Database provider:",options:c.map(T=>({value:T,label:Te[T].label,hint:Te[T].hint}))});return S(d),d})(),$=e?.cacheProvider??s.cacheProvider??await(async()=>{r=!0;let c=le.filter(T=>!Ke.some(ye=>ye.target===a&&ye.provider===T));if(c.length===1){let T=c[0];return u.log.info(`Auto-selected ${_e[T].label} (only compatible option for ${G[a].label}).`),T}let d=await u.select({message:"Cache provider:",options:c.map(T=>({value:T,label:_e[T].label,hint:_e[T].hint}))});return S(d),d})();if(G[a]?.edgeRuntime){let c=Kr.map(d=>` - ${d}`).join(`
|
|
3
|
+
`);u.note(c,"Unavailable on edge runtime")}u.log.info(h.bold("Features"));let J=e?.paymentProvider??await(async()=>{r=!0;let c=await u.select({message:"Payment provider:",options:We.map(d=>({value:d,label:It[d].label,hint:It[d].hint}))});return S(c),c})(),fe=e?.defaultCurrency??await(async()=>{if(J==="none")return"USD";r=!0;let c=await u.select({message:"Default currency:",options:oe.map(d=>({value:d,label:d,hint:Ie[d].name}))});return S(c),c})(),X=e?.emailProvider??await(async()=>{r=!0;let c=await u.select({message:"Email provider:",options:qe.map(d=>({value:d,label:Tt[d].label,hint:Tt[d].hint}))});return S(c),c})(),he=e?.observability??await(async()=>{r=!0;let c=await u.multiselect({message:"Observability (space to select, enter to confirm):",required:!1,initialValues:[],options:B.map(d=>({value:d,label:_t[d].label,hint:_t[d].hint}))});return S(c),c})(),Ee=e?.multiTenancy??await(async()=>{r=!0;let c=await u.confirm({message:"Enable multi-tenancy (organizations)?",initialValue:!1});return S(c),c})(),Se=e?.blog??await(async()=>{r=!0;let c=await u.confirm({message:"Enable blog?",initialValue:!0});return S(c),c})(),Re=e?.docs??await(async()=>{r=!0;let c=await u.confirm({message:"Include docs app? (self-hosted Fumadocs documentation site)",initialValue:!1});return S(c),c})(),v=t?.desktopAllowed!==!1,x=e?.desktop??(v?await(async()=>{r=!0;let c=await u.confirm({message:"Include the desktop app? (apps/electron - cross-platform, built with Electron, device-auth). With AI on, it also runs a local AI stack.",initialValue:!1});return S(c),c})():(u.log.info(h.dim("Desktop app: available on the Pro plan and up - skipped.")),!1)),L=e?.ai??await(async()=>{r=!0;let c=await u.confirm({message:"Add AI features? (chat, models, schedules, integrations - and unlocks the runner)",initialValue:!1});return S(c),c})(),ge=t?.runnerAllowed!==!1,U=e?.webAi===!1,V=!L||w||U?!1:e?.runner??(ge?await(async()=>{r=!0;let c=await u.confirm({message:"Add the runner daemon for your WEB users? A small program they install on their own machine or VPS to run their Claude Code / Codex subscription for this app 24/7 - the AI runs on their hardware, not yours. Off means no install UI and no pairing endpoint on your site; you can adopt it later.",initialValue:!1});return S(c),c})():(u.log.info(h.dim("Runner: available on the Pro plan and up - skipped.")),!1));L&&w?u.log.info(h.dim(`Runner: ${G[a].label} cannot hold a connection open - skipped.`)):L&&U&&u.log.info(h.dim("Runner: its pairing and device screens live in the web AI surface, which is off - skipped."));let F=e?.webAi??(x&&L&&!V?await(async()=>{r=!0;let c=await u.confirm({message:"Show the AI surfaces in the web app? (No: desktop-first - the web keeps account, billing, and licensing only)",initialValue:!0});return S(c),c})():!0);lt({webAi:F,ai:L,desktop:x,runner:V});let Ae=e?.revenueSharing??await(async()=>{r=!0;let c=await u.confirm({message:"Enable revenue sharing? (opt-in MRR leaderboard with dofollow backlinks)",initialValue:!1});return S(c),c})(),Be=J==="none"?!1:e?.credits??await(async()=>{r=!0;let c=await u.confirm({message:"Enable credits? (metered usage on top of subscription plans)",initialValue:!0});return S(c),c})(),R=e?.demo,Pe=ir({databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,demo:R}),at={};if(Pe.length>0&&r){u.log.info(h.bold("Credentials")+h.dim(" all optional - press Enter to skip, fill in .env later"));for(let c of Pe)if(r=!0,c.secret){let d=await u.password({message:c.message,mask:"*"});S(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}else{let d=await u.text({message:c.message,placeholder:c.placeholder});S(d),typeof d=="string"&&d.trim()&&(at[c.key]=d.trim())}}if(r){let c=[` Name: ${h.cyan(n)}`,` App name: ${h.cyan(i)}`,` Location: ${h.cyan(o)}`,` Architecture: ${h.cyan(ct[A].label)}`].join(`
|
|
4
|
+
`),d=[` Deploy target: ${h.cyan(G[a]?.label??"Node.js / Docker")}`,` Database: ${h.cyan(Te[f].label)}`,` Cache: ${h.cyan(_e[$].label)}`].filter(Boolean).join(`
|
|
5
|
+
`),T=[J!=="none"?` Payment: ${h.cyan(It[J].label)} (${fe})`:` Payment: ${h.dim("none")}`,` Credits: ${Be?h.cyan("Yes"):h.dim("No")}`,` AI features: ${L?h.cyan("Yes"):h.dim("No")}`,...L?[` Runner: ${V?h.cyan("Yes"):h.dim("No")}`]:[],...F?[]:[` Web AI: ${h.dim("No")} (desktop-first)`],` Email: ${h.cyan(Tt[X].label)}`,` Observability: ${he.length===0?h.dim("none"):h.cyan(he.map(er=>_t[er].label).join(", "))}`,` Multi-tenancy: ${Ee?h.cyan("Yes"):h.dim("No")}`,` Blog: ${Se?h.cyan("Yes"):h.dim("No")}`,` Docs app: ${Re?h.cyan("Yes"):h.dim("No")}`,` Desktop app: ${x?h.cyan("Yes"):h.dim("No")}`,` Rev. sharing: ${Ae?h.cyan("Yes"):h.dim("No")}`].join(`
|
|
6
|
+
`),ye=[h.bold("Project"),c,"",h.bold("Infrastructure"),d,"",h.bold("Features"),T];if(Pe.length>0){let er=Pe.map(Ur=>{let ps=at[Ur.key]?h.green("provided"):h.dim("skipped");return` ${Ur.key}: ${ps}`}).join(`
|
|
7
|
+
`);ye.push("",h.bold("Credentials"),er)}u.note(ye.join(`
|
|
8
|
+
`),"Summary");let Mr=await u.confirm({message:"Proceed with these settings?"});(u.isCancel(Mr)||!Mr)&&(u.cancel("Setup cancelled."),process.exit(0))}return{projectName:n,appName:i,projectDir:o,architecture:A,deploymentTarget:a,databaseProvider:f,cacheProvider:$,paymentProvider:J,emailProvider:X,observability:he,multiTenancy:Ee,blog:Se,docs:Re,desktop:x,ai:L,webAi:F,runner:V,revenueSharing:Ae,credits:Be,defaultCurrency:fe,...Object.keys(at).length>0?{credentials:at}:{},...e?.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...R!==void 0?{demo:R}:{}}}import{createReadStream as pn,existsSync as Es}from"fs";import{mkdir as Ss}from"fs/promises";import{join as Rs}from"path";import{Readable as As}from"stream";import{pipeline as mr}from"stream/promises";import{extract as Ps}from"tar";import{join as xe}from"path";import{homedir as ms}from"os";var pt=process.env.GENERATESAAS_API_URL??"https://cli.generatesaas.com",H=".generatesaas",ve=xe(H,"manifest.json"),Qr="nextjs",sr="nuxt",or="2.4.1",en=xe(H,"hashes.json"),Dt=xe(H,"template-hashes.json"),Nt=xe(H,"template"),tn=xe(H,"staging"),rn=xe(H,"staging.json"),pe=xe(ms(),".generatesaas");var j=class extends Error{constructor(r,n,i){super(n);this.status=r;this.body=i}status;body;name="ApiError"};function de(e){return{apiKey:e,baseUrl:pt}}async function be(e,t,r){let n=`${e.baseUrl}${t}`,i=await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${e.apiKey}`,"User-Agent":"generatesaas-cli/3.0.1"}});if(!i.ok){let o,s;try{s=await i.json(),o=s.error??`API ${i.status}: ${t}`}catch{o=`API ${i.status}: ${t}`}throw new j(i.status,o,s)}return i}import{existsSync as fs,readFileSync as hs,writeFileSync as gs,mkdirSync as ys}from"fs";import{dirname as vs}from"path";import*as we from"@clack/prompts";function dt(){if(!fs(pe))return null;try{let e=JSON.parse(hs(pe,"utf-8"));return e.apiKey?e.apiKey:(e.token&&!e.apiKey&&we.log.warning(`Found old GitHub token in ${pe}. Run 'generatesaas init' to set up your API key.`),null)}catch{return null}}function De(e){ys(vs(pe),{recursive:!0}),gs(pe,JSON.stringify({apiKey:e},null," ")+`
|
|
9
|
+
`,{mode:384})}async function Je(e){if(e?.apiKey)return e.apiKey;let t=process.env.GENERATESAAS_API_KEY;if(t)return t;let r=dt();if(r)return r;if(!e?.prompt)throw new Error("API key not found. Set GENERATESAAS_API_KEY or run 'generatesaas init' to configure.");return ut()}async function ut(){let e=await we.text({message:"Enter your GenerateSaaS API key:",placeholder:"gs_live_...",validate:t=>{if(!t?.trim())return"API key is required."}});return we.isCancel(e)&&(we.cancel("Setup cancelled."),process.exit(0)),e.trim()}import{readFile as bs}from"fs/promises";async function ke(e){let t=process.env.GENERATESAAS_VERSION_INDEX;return t?JSON.parse(await bs(t,"utf-8")):process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{latest:"0.0.0-ci",versions:[{version:"0.0.0-ci",date:new Date().toISOString(),breaking:!1}],entitlements:null}:await(await be(e,"/versions")).json()}async function nn(e,t){if(process.env.GENERATESAAS_OFFLINE_LICENSE==="1")return null;try{return await(await be(e,`/changelog/${encodeURIComponent(t)}`)).text()}catch(r){if(r instanceof j&&r.status===404)return null;throw r}}async function sn(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{skillMd:`# Offline skill stub
|
|
10
|
+
`,scripts:{}}:await(await be(e,`/skill/${encodeURIComponent(t)}`)).json()}function Ct(e){if(!(e instanceof j)||e.status!==403)return null;let t=e.body;return!t||t.code!=="update_window_expired"?null:{message:e.message,lastAllowedVersion:t.lastAllowedVersion??null}}var ar="nextjs";function on(e){return{frontend:ar,architecture:e.architecture,deployTarget:e.deploymentTarget,database:e.databaseProvider,cache:e.cacheProvider,payment:e.paymentProvider,email:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,currency:e.defaultCurrency}}async function cr(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:"offline-test-token",licenseId:"offline-test-license-id",installId:t.installId}:await(await be(e,"/license/sign",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function an(e,t){return process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?{token:t.currentToken}:await(await be(e,"/license/refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json()}async function lr(e,t){let r=await fetch(`${e}/license/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Verification service returned ${r.status}`);return await r.json()}async function cn(e,t,r){let n=await fetch(`${e}/license/inspect`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(r)});if(!n.ok){let i=await n.json().catch(()=>null);throw new Error(i?.error??`Inspect endpoint returned ${n.status}`)}return await n.json()}var pr=new Set([".git","node_modules",".pnpm-store",".env",".env.test",".turbo",".data","dist",".next",".svelte-kit",".wrangler",".devcontainer","playwright-report","test-results"]),dr=new Set(["pnpm-lock.yaml"]);function Xe(e){if(ur(e))return!0;for(let t of e.split("/"))if(dr.has(t))return!0;return!1}var ws=new Set(["data","mksaas","references","scripts",".cursor",".agents",".codex",".generatesaas",".vscode",".mcp.json","vitest.config.ts","README.md","TODO.md","OVERVIEW.md"]),ln=["scripts/docs-lint.ts"],ks=["docs/superpowers","packages/cli","packages/cli-api","packages/config/tests/runner-brand-lockstep.test.ts","apps/runner","docs/agentrunner","infra/docker-compose.yml",".claude/commands",".claude/skills/web-port",".claude/skills/web-port-workspace",".claude/settings.local.json",".claude/worktrees"];function ur(e){let t=e.split("/");for(let r of t)if(pr.has(r))return!0;if(ln.includes(e)||ln.some(r=>r.startsWith(e+"/")))return!1;if(ws.has(t[0]))return!0;for(let r of ks)if(e===r||e.startsWith(r+"/"))return!0;return!1}async function $t(e,t,r){await Ss(r,{recursive:!0});let n=process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR;if(n){let a=Rs(n,`v${t}.tar.gz`);if(!Es(a))throw new Error(`GENERATESAAS_TEMPLATE_TARBALL_DIR is set but ${a} does not exist.`);await mr(pn(a),fr(r));return}let i=process.env.GENERATESAAS_TEMPLATE_TARBALL;if(i){await mr(pn(i),fr(r));return}let o=await be(e,`/template/${encodeURIComponent(t)}`);if(!o.body)throw new Error("Empty response body");let s=As.fromWeb(o.body);await mr(s,fr(r))}function fr(e){return Ps({cwd:e,strip:1,filter:t=>{let r=t.replace(/^[^/]+\//,"");return r?!ur(r):!0},sync:!1})}import{readdir as fn,readFile as ht,rm as hr,writeFile as gt}from"fs/promises";import{join as Q}from"path";import{readFile as ft,rm as $s}from"fs/promises";import{join as mt}from"path";import{mkdir as Is,readdir as Ts,rm as _s,rmdir as Os,writeFile as xs}from"fs/promises";import{dirname as Lt,join as Ds,relative as Ns,sep as Cs}from"path";function Ne(e){return e.split(Cs).join("/")}async function jt(e){await Is(e,{recursive:!0})}async function l(e,t){await jt(Lt(e)),await xs(e,t,"utf-8")}async function Mt(e,t){await _s(e,{force:!0});let r=Lt(e);for(;r!==t&&r!==Lt(r);){try{await Os(r)}catch{return}r=Lt(r)}}async function ue(e,t,r,n){let i=[],o=await Ts(e,{withFileTypes:!0});for(let s of o){let a=Ds(e,s.name),p=Ne(Ns(t,a));r(p)||(s.isDirectory()?i.push(...await ue(a,t,r,n)):s.isFile()&&(n===void 0||n(p))&&i.push(a))}return i}function Ls(e){return new RegExp(`^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-start(?: \\*\\/\\})?[ \\t]*\\r?\\n[\\s\\S]*?^[ \\t]*(?:\\/\\/|\\{\\/\\*|\\*) gsaas:${e}-end(?: \\*\\/\\})?[ \\t]*\\r?\\n`,"gm")}function Z(e,t,r,n){let i=Ls(r);if(e.match(i)===null)throw new Error(`${n}: expected gsaas ${r} markers in ${t}, but found none (boilerplate drift).`);let o=e.replace(i,"");if(o.includes(`gsaas:${r}-start`)||o.includes(`gsaas:${r}-end`))throw new Error(`${n}: an unbalanced gsaas ${r} marker is left in ${t} (boilerplate drift).`);return o.replace(/\n{3,}/g,`
|
|
11
|
+
|
|
12
|
+
`).replace(/,(\r?\n[ \t]*[\]})])/g,"$1")}async function Y(e,t,r,n,i){let o=await ft(e,"utf-8"),s=o.indexOf(t);if(s===-1)throw new Error(`${i}: expected to find the ${n} seam, but it was missing (boilerplate drift).`);if(o.indexOf(t,s+t.length)!==-1)throw new Error(`${i}: the ${n} seam appears more than once (boilerplate drift).`);await l(e,o.slice(0,s)+r+o.slice(s+t.length))}async function Ze(e,t,r,n){let i=/\n([\t ]+)"/.exec(await ft(e,"utf-8"))?.[1];if(i!==r){let o=s=>s===" "?"tab":`${s.length}-space`;throw new Error(`${n}: expected ${e} to be ${o(r)}-indented, but it is ${i===void 0?"not indented":o(i)}-indented (boilerplate drift). Re-serializing it with the wrong indent would reformat the whole file.`)}await l(e,`${JSON.stringify(t,null,r)}
|
|
13
|
+
`)}async function js(e,t,r){let n=mt(e,"ai.mdx"),o=(await ft(n,"utf-8")).split(`
|
|
14
|
+
`).find(s=>s.includes(`href="${t}"`));if(o===void 0)throw new Error(`${r}: expected the ai.mdx card linking to ${t} (boilerplate drift).`);await Y(n,`${o}
|
|
15
|
+
`,"",`ai.mdx ${t} card`,r)}async function Ms(e,t,r){let n=mt(e,"ai.mdx"),i=`| **${t}** |`,s=(await ft(n,"utf-8")).split(`
|
|
16
|
+
`).find(a=>a.startsWith(i));if(s===void 0)throw new Error(`${r}: expected the ai.mdx "${t}" hub-table row (boilerplate drift).`);await Y(n,`${s}
|
|
17
|
+
`,"",`ai.mdx ${t} hub-table row`,r)}async function dn(e,t,r,n,i){let o=mt(e,"docs");await $s(mt(o,t),{recursive:!0}),await Y(mt(o,"meta.json"),` "${t}",
|
|
18
|
+
`,"",`docs meta.json ${t} nav entry`,n);for(let s of r)await js(o,s,n);i!==void 0&&await Ms(o,i,n)}function Us(e){let t="",r=0;for(;r<e.length;){let n=e[r],i=e[r+1];if(n==="/"&&i==="/"){for(;r<e.length&&e[r]!==`
|
|
19
|
+
`;)r++;continue}if(n==="/"&&i==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)e[r]===`
|
|
20
|
+
`&&(t+=`
|
|
21
|
+
`),r++;r+=2;continue}if(n==='"'||n==="'"||n==="`"){let o=n;for(r++;r<e.length&&e[r]!==o;)e[r]==="\\"?r++:e[r]===`
|
|
22
|
+
`&&(t+=`
|
|
23
|
+
`),r++;r++;continue}t+=n,r++}return t}async function un(e){let t=`import { config } from "@repo/config";
|
|
24
|
+
`,r=await ft(e,"utf-8");if(!r.includes(t))return;let n=r.replace(t,""),i=Us(n);/\bconfig\b/.test(i)||await l(e,n)}var Vs=["apps/web/public/images/blog"];async function hn(e){let t=Q(e,"packages/content"),r=[];try{r=(await fn(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{}await Promise.all([...Vs.map(n=>hr(Q(e,n),{recursive:!0,force:!0})),...r.map(n=>hr(Q(t,n,"blog"),{recursive:!0,force:!0}))])}var Fs=["apps/electron/src/renderer/router.tsx","apps/electron/src/renderer/config/sidebar.ts"];async function gn(e){let t="removeDesktopDemoScreen";await hr(Q(e,"apps/electron/src/renderer/screens/demo"),{recursive:!0});for(let r of Fs){let n=Q(e,r);await gt(n,Z(await ht(n,"utf-8"),r,"demo",t))}}var Bs="packages/config/src/blog.ts";async function yn(e){let t=Q(e,Bs),r=await ht(t,"utf-8"),n=mn(mn(r,"blogCategories",t),"blogAuthors",t);await gt(t,n)}function mn(e,t,r){let n=new RegExp(`(export const ${t}\\b[^=]*=\\s*)\\[[\\s\\S]*?\\];`);if(!n.test(e))throw new Error(`emptyBlogConfig: could not find the \`export const ${t} = [...]\` declaration in ${r}. The boilerplate blog config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);return e.replace(n,"$1[];")}async function vn(e){let t=Q(e,"packages/i18n/translations"),r;try{r=await fn(t)}catch{return}for(let n of r){let i=Q(t,n,"web.json"),o;try{o=await ht(i,"utf-8")}catch{continue}let s=JSON.parse(o);!s.blog||s.blog.categories===void 0||(s.blog.categories={},await gt(i,JSON.stringify(s,null," ")+`
|
|
25
|
+
`))}}var Ks="packages/config/src/ai/tasks.ts",Gs="The array carries a SINGLE INERT DEMO task: the CLI strips it for buyer builds (leaving an empty\n * `aiTasks`, which hides the Tasks tab) and keeps it for `--demo` builds.",Hs="The array starts EMPTY, which hides the Tasks tab until you declare your first task.";async function bn(e){let t=Q(e,Ks),r=await ht(t,"utf-8"),n=r.replace(/\n?[\t ]*\/\/ gsaas:demo-ai-task-start[\s\S]*?\/\/ gsaas:demo-ai-task-end/,"");if(n===r)throw new Error(`removeDemoAiTasks: could not find the \`gsaas:demo-ai-task\` markers in ${t}. The boilerplate AI tasks config may have been renamed or restructured; update the CLI strip in cleanup.ts.`);let i=n.replace(Gs,Hs);if(i===n)throw new Error(`removeDemoAiTasks: the demo-task paragraph in ${t} did not match, so the shipped file would describe a demo task it no longer carries (boilerplate drift).`);await gt(t,i)}async function wn(e){let t=Q(e,".claude","settings.json"),r;try{r=await ht(t,"utf8")}catch{return}let n=JSON.parse(r);delete n.alwaysThinkingEnabled,delete n.enableAllProjectMcpServers,n.env&&(delete n.env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS,Object.keys(n.env).length===0&&delete n.env),n.permissions?.allow&&(n.permissions.allow=n.permissions.allow.filter(Ys)),await gt(t,JSON.stringify(n,null," ")+`
|
|
26
|
+
`)}function Ys(e){return!(e.startsWith("mcp__")||e.includes("nuxt"))}import{join as kn}from"path";var Ws={postgres:"Postgres",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"},qs={resend:"Resend",ses:"Amazon SES",smtp:"SMTP"},zs={redis:"Redis",upstash:"Upstash Redis"},Js={node:"Node.js / Docker",vercel:"Vercel"},Ut="apps/web",En="Next.js 16",Xs="`app/` routes, `components/`, `lib/`",Zs={stripe:"Stripe",polar:"Polar"};function Qs(e){let t=e.architecture==="fullstack",r=t?"(fullstack - Hono API mounted inside the app)":"(separate - standalone Hono backend)",n=t?`Mounted inside \`${Ut}\`. A standalone \`apps/backend\` is also kept (inert) so you can switch to separate later.`:"Runs from `apps/backend`; the frontend reaches it over HTTP.",i=zs[e.cacheProvider],o=Js[e.deploymentTarget],s=e.paymentProvider==="none"?"":`
|
|
27
|
+
- **Payments:** ${Zs[e.paymentProvider]}`,a=e.desktop?", and the desktop app (built with Electron) under `docs/desktop/`":"",p=e.runner?"\n- **Runner daemon** - your users install AgentRunner on a machine they control and pair it with their account. Everything you own lives in this repo: the `/runner/*` routes, the relay, the Runners page, and the capability layer runs get. The daemon itself is published separately and auto-updates - there is nothing to build or release here.":"",m=`\`useTranslations()\` from \`next-intl\` in components; messages are loaded in \`${Ut}/i18n/request.ts\`.`;return`# AGENTS.md
|
|
23
28
|
|
|
24
29
|
Guidelines for AI coding agents (Claude Code, Codex, Cursor, \u2026) in this project.
|
|
25
30
|
Keep this file tight: add a rule only when it prevents a recurring mistake - too
|
|
@@ -31,9 +36,9 @@ This boilerplate already ships ~30 features, every one config-gated and wired en
|
|
|
31
36
|
end. Before writing a new file, route, table, or component, assume it ALREADY EXISTS
|
|
32
37
|
and go find it:
|
|
33
38
|
|
|
34
|
-
1. \`docs
|
|
39
|
+
1. \`docs/index.mdx\` - the catalog of every shipped feature and its config flag.
|
|
35
40
|
2. \`packages/config/src/index.ts\` - the flag that turns the feature on/off (check it before rendering).
|
|
36
|
-
3. Search \`packages/\` and \`${
|
|
41
|
+
3. Search \`packages/\` and \`${Ut}/\` for the name before creating anything.
|
|
37
42
|
|
|
38
43
|
Already built - extend these, never re-implement: auth (email / OAuth / 2FA / passkeys),
|
|
39
44
|
billing & subscriptions, credits, organizations & teams, notifications, email, SMS,
|
|
@@ -45,13 +50,13 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
45
50
|
|
|
46
51
|
## Stack
|
|
47
52
|
|
|
48
|
-
- **Frontend:** ${
|
|
49
|
-
- **API:** Hono, RPC-typed. ${
|
|
50
|
-
- **Database:** Drizzle ORM + ${
|
|
51
|
-
- **Cache + jobs:** ${
|
|
52
|
-
- **Auth:** Better Auth${
|
|
53
|
-
- **Email:** ${
|
|
54
|
-
- **Deploy:** ${
|
|
53
|
+
- **Frontend:** ${En} ${r}
|
|
54
|
+
- **API:** Hono, RPC-typed. ${n}
|
|
55
|
+
- **Database:** Drizzle ORM + ${Ws[e.databaseProvider]}
|
|
56
|
+
- **Cache + jobs:** ${i} + Inngest
|
|
57
|
+
- **Auth:** Better Auth${s}
|
|
58
|
+
- **Email:** ${qs[e.emailProvider]}
|
|
59
|
+
- **Deploy:** ${o}
|
|
55
60
|
|
|
56
61
|
## Where things live (extend these - don't reinvent)
|
|
57
62
|
|
|
@@ -61,8 +66,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
61
66
|
- \`packages/auth/src/config.ts\` - Better Auth config.
|
|
62
67
|
- \`packages/runtime/src/env.ts\` - the validated (Zod) env schema. New env var \u2192 add it here **and** to \`.env.example\` (the committed reference); set the local value in \`.env\`.
|
|
63
68
|
- \`packages/{payments,mail,sms,storage,notifications}\` - config-gated integrations. Every provider's files stay even when its feature is off, so flipping a flag is enough to enable it.
|
|
64
|
-
- \`${
|
|
65
|
-
- \`docs
|
|
69
|
+
- \`${Ut}\` - the ${En} app (${Xs}).${p}
|
|
70
|
+
- \`docs/\` - feature & architecture documentation for this stack (Markdown). Consult it before searching from scratch; it cites real config keys, package names, and file paths you can act on. The GenerateSaaS CLI lives under \`docs/cli/\`${a}.
|
|
66
71
|
|
|
67
72
|
## Code style
|
|
68
73
|
|
|
@@ -79,8 +84,8 @@ flag, route, or translation is the most common and most costly mistake in this r
|
|
|
79
84
|
|
|
80
85
|
- **Hono routes:** keep the method chain (\`.get().post()\`) - RPC type inference depends on it. Validate with \`sValidator\` from \`@hono/standard-validator\`.
|
|
81
86
|
- **Feature flags:** respect \`config.*\` - hide/skip a feature when its flag is off (the files stay so you can flip it later).
|
|
82
|
-
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${
|
|
83
|
-
-
|
|
87
|
+
- **i18n:** strings live in \`packages/i18n/translations/{locale}/{scope}.json\`; edit \`en/\` only, keep keys generic. ${m} A pre-commit hook runs \`pnpm translate\` (needs \`OPENROUTER_API_KEY\`) to sync other locales from \`en\`; without the key it skips.
|
|
88
|
+
- **Navigation:** \`next/link\` for links; \`redirect()\` from \`next/navigation\` for programmatic redirects in Server Components.
|
|
84
89
|
- **Routes:** use \`config.routes.*\`, never hardcoded path strings.
|
|
85
90
|
- **Secrets:** never send them to an external service; generate tokens/QR codes client-side.
|
|
86
91
|
|
|
@@ -91,23 +96,23 @@ In \`@repo/*\` backend packages prefer web-standard APIs: \`crypto.randomUUID()\
|
|
|
91
96
|
## This project
|
|
92
97
|
|
|
93
98
|
Scaffolded from the GenerateSaaS boilerplate. To pull upstream boilerplate updates, ask your agent to **"update my GenerateSaaS project"**. To remove the license heartbeat + manifest: \`pnpm dlx generatesaas eject\`.
|
|
94
|
-
`}async function
|
|
95
|
-
`)}import{join as
|
|
99
|
+
`}async function Sn(e){await l(kn(e.projectDir,"AGENTS.md"),Qs(e)),await l(kn(e.projectDir,"CLAUDE.md"),`@AGENTS.md
|
|
100
|
+
`)}import{join as eo}from"path";var Rn="apps/web",gr="Next.js 16",to={postgres:"Postgres (self-hosted)",neon:"Neon (managed Postgres)",supabase:"Supabase (managed Postgres)"};function ro(e){let t=e.appName.trim()||e.projectName,r=to[e.databaseProvider],n=e.architecture==="fullstack"?`${gr} app at \`${Rn}/\` with the Hono API mounted inside it. A standalone \`apps/backend/\` is also included (inert in this fullstack setup) so you can split the API into a separate service later without re-scaffolding.`:`${gr} app at \`${Rn}/\` and a separate Hono backend at \`apps/backend/\`.`,i=e.architecture==="fullstack"?`- App + API: http://localhost:3000
|
|
96
101
|
- Inngest dev server: http://127.0.0.1:8288`:`- App: http://localhost:3000
|
|
97
102
|
- API: http://localhost:3010
|
|
98
|
-
- Inngest dev server: http://127.0.0.1:8288`,
|
|
99
|
-
`,
|
|
103
|
+
- Inngest dev server: http://127.0.0.1:8288`,o=`pnpm infra # optional: starts local Docker services (Postgres / Redis / Inngest / Mailpit)
|
|
104
|
+
`,s=e.deploymentTarget==="vercel"?"### Deployment\n\nDeploy to Vercel: `vercel deploy` (or connect the repo in the Vercel dashboard). Required environment variables are listed in `.env`.":"### Deployment\n\nThis project ships with Dockerfiles for each app. Build images with `docker build` and deploy to your runtime of choice (Render / Fly.io / Railway / Coolify / Dokploy / your own VPS).\n\nThe `infra/` directory ships a Docker Compose file for the local-only services (Postgres / Redis / Inngest / Mailpit, filtered by your provider choices).";return`# ${t}
|
|
100
105
|
|
|
101
|
-
${
|
|
106
|
+
${n}
|
|
102
107
|
|
|
103
108
|
## Stack
|
|
104
109
|
|
|
105
|
-
- **Frontend:** ${
|
|
110
|
+
- **Frontend:** ${gr}
|
|
106
111
|
- **Backend:** Hono (TypeScript, RPC-typed)
|
|
107
112
|
- **Auth:** Better Auth
|
|
108
|
-
- **ORM / DB:** Drizzle + ${
|
|
113
|
+
- **ORM / DB:** Drizzle + ${r}
|
|
109
114
|
- **Background jobs:** Inngest
|
|
110
|
-
- **i18n:**
|
|
115
|
+
- **i18n:** next-intl
|
|
111
116
|
|
|
112
117
|
## Development
|
|
113
118
|
|
|
@@ -116,11 +121,11 @@ pnpm install
|
|
|
116
121
|
# A ready-to-run \`.env\` was generated for you - open it and fill in the
|
|
117
122
|
# values marked \`# TODO\` (provider API keys). \`.env.example\` is the committed
|
|
118
123
|
# reference. All apps load the single root \`.env\`.
|
|
119
|
-
${
|
|
124
|
+
${o}pnpm db:setup # first run: create the database schema (idempotent)
|
|
120
125
|
pnpm dev
|
|
121
126
|
\`\`\`
|
|
122
127
|
|
|
123
|
-
${
|
|
128
|
+
${i}
|
|
124
129
|
|
|
125
130
|
## Build your SaaS
|
|
126
131
|
|
|
@@ -140,7 +145,7 @@ pnpm -F @repo/database studio # open Drizzle Studio
|
|
|
140
145
|
pnpm auth:generate # regenerate Better Auth schema after config changes
|
|
141
146
|
\`\`\`
|
|
142
147
|
|
|
143
|
-
${
|
|
148
|
+
${s}
|
|
144
149
|
|
|
145
150
|
## Removing the GenerateSaaS license
|
|
146
151
|
|
|
@@ -153,37 +158,55 @@ pnpm dlx generatesaas eject
|
|
|
153
158
|
## Updates
|
|
154
159
|
|
|
155
160
|
To pull the latest boilerplate changes into this project, open it in your AI coding agent and ask: \`update my GenerateSaaS project\`.
|
|
156
|
-
`}async function
|
|
161
|
+
`}async function An(e){await l(eo(e.projectDir,"README.md"),ro(e))}import{access as no}from"fs/promises";import{join as Vt}from"path";var Pn="1x00000000000000000000AA",In="1x0000000000000000000000000000000AA",yt="NEXT_PUBLIC_TURNSTILE_SITE_KEY";async function io(e,t,r){let n=Vt(e,"apps/electron/dev-app-update.yml");try{await no(n)}catch{throw new Error(`Cannot neutralize the desktop dev update feed: ${n} is missing (boilerplate drift).`)}await l(n,`provider: generic
|
|
157
162
|
url: ${t}
|
|
158
|
-
updaterCacheDirName: ${
|
|
159
|
-
`)}function
|
|
160
|
-
`):'{ enabled: false, clientId: "
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
163
|
+
updaterCacheDirName: ${r}
|
|
164
|
+
`)}function so(e){let t=e.split(".");return t.length>=3?t.slice(1).join("."):e}function oo(e,t){let r=Hr(e,"app");return{appId:`${t.split(".").reverse().join(".")}.${r.replace(/-/g,"")}`,productName:e,protocol:r}}var Qe={name:"AgentRunner",binary:"agentrunner",envPrefix:"AGENTRUNNER",repoUrl:"https://github.com/AlexChelan/AgentRunner",installBase:"https://github.com/AlexChelan/AgentRunner/releases/latest/download",image:"ghcr.io/alexchelan/agentrunner"};function ao(e){return e.runner?["{"," enabled: true,",' clientId: "runner",'," daemon: {",` name: ${JSON.stringify(Qe.name)},`,` binary: ${JSON.stringify(Qe.binary)},`,` envPrefix: ${JSON.stringify(Qe.envPrefix)},`,` repoUrl: ${JSON.stringify(Qe.repoUrl)},`,` installBase: ${JSON.stringify(Qe.installBase)},`,` image: ${JSON.stringify(Qe.image)}`," }"," }"].join(`
|
|
165
|
+
`):'{ enabled: false, clientId: "runner" }'}function co(e){let t=[" // PRESENCE IS THE SWITCH: reporting runs as soon as the credential below is non-empty. There"," // is no separate `enabled` flag to remember - pasting the key IS turning it on, and clearing it"," // is turning it off. These are PUBLISHABLE credentials: they only authorize SENDING events,"," // never reading them, which is why they live here rather than in env and why a packaged desktop"," // app can carry them. Server-side, SENTRY_DSN and POSTHOG_API_KEY override them."].join(`
|
|
166
|
+
`),r=[];return e.includes("sentry")&&r.push(' sentry: { dsn: "" }'),e.includes("posthog")&&r.push([" // llmContent sends your users' prompts and completions to PostHog. Every number (tokens,"," // cost, latency, errors) is captured either way - turn it on only if your privacy policy"," // covers sending their message text to a third party.",' posthog: { publicKey: "", host: "https://us.i.posthog.com", llmContent: false }'].join(`
|
|
167
|
+
`)),r.length===0?[" // Error and product reporting is OFF: no provider was selected at init, so neither adapter",' // nor SDK was generated. To turn one on, add `"sentry"`, `"posthog"` or both to the'," // `observability` array in `.generatesaas/manifest.json`, then run `generatesaas update` -"," // which re-shapes the project and installs what it needs. Note that update stages nothing"," // while you are already on the latest version, so take the upgrade first if it reports no"," // changes."," observability: {},"].join(`
|
|
168
|
+
`):`${t}
|
|
169
|
+
observability: {
|
|
170
|
+
${r.join(`,
|
|
171
|
+
`)}
|
|
172
|
+
},`}async function Tn(e){let t=e.appName.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=e.paymentProvider!=="none",n=e.baseUrl??"http://localhost:3000",i=e.baseUrl?new URL(e.baseUrl).hostname:"example.com",o=so(i),s=e.demo?"false":"true",a=e.multiTenancy?`{
|
|
173
|
+
multiTenant: true,
|
|
174
|
+
organizationLimit: 5
|
|
175
|
+
}`:"{ multiTenant: false }",p=co(e.observability),m=e.demo?`{
|
|
176
|
+
enableInDev: true,
|
|
177
|
+
chatwoot: {
|
|
178
|
+
baseUrl: "https://support.alexchelan.com",
|
|
179
|
+
websiteToken: "1uWvJLHkhWLihkK2bxLaj2Fg"
|
|
180
|
+
}
|
|
181
|
+
}`:"{}",w=e.architecture==="fullstack"?"false":"true",g=oo(t,o),k=`https://cdn.${o}/desktop`,A=ao(e),f=`import type { AppConfig } from "@repo/config/types";
|
|
167
182
|
import { desktopConfig } from "./desktop.mjs";
|
|
168
|
-
import {
|
|
169
|
-
import { supportConfig } from "./support.mjs";
|
|
170
|
-
import { tenancyConfig } from "./tenancy-flags.mjs";
|
|
171
|
-
|
|
172
|
-
const trustedOrigins = process.env.TRUSTED_ORIGINS?.split(",").map((s) => s.trim()).filter(Boolean);
|
|
183
|
+
import { supportConfig } from "./support";
|
|
173
184
|
|
|
185
|
+
/**
|
|
186
|
+
* This file is PURE STATIC DATA. No \`process.env\`, no imports that read it.
|
|
187
|
+
*
|
|
188
|
+
* That is load-bearing, not style. A packaged desktop app has no \`.env\` and a sandboxed renderer
|
|
189
|
+
* cannot read one, so a config that touches \`process.env\` either fails or silently resolves to
|
|
190
|
+
* undefined on those surfaces. Keeping it env-free is what lets server, browser, Electron main and
|
|
191
|
+
* Electron renderer all import the SAME module.
|
|
192
|
+
*
|
|
193
|
+
* A value that varies per DEPLOYMENT belongs in \`@repo/runtime\`'s \`env\` instead, which is
|
|
194
|
+
* server-only and validated - \`BASE_URL\` and \`TRUSTED_ORIGINS\` are declared there. What lives here
|
|
195
|
+
* is your project's own identity: edit it directly.
|
|
196
|
+
*/
|
|
174
197
|
export const config: AppConfig = {
|
|
175
198
|
siteName: "${t}",
|
|
176
199
|
fullSiteName: "${t}",
|
|
177
200
|
domain: "${i}",
|
|
178
|
-
baseUrl:
|
|
201
|
+
baseUrl: "${n}",
|
|
179
202
|
indexable: ${s},
|
|
180
203
|
logo: {
|
|
181
204
|
main: "/images/logo.svg",
|
|
182
205
|
square: "/images/logo-square.svg"
|
|
183
206
|
},
|
|
184
|
-
origins:
|
|
207
|
+
origins: ["http://localhost:3000", "http://localhost:5173"],
|
|
185
208
|
waitlist: false,
|
|
186
|
-
tenancy:
|
|
209
|
+
tenancy: ${a},
|
|
187
210
|
theme: {
|
|
188
211
|
default: "system",
|
|
189
212
|
switcher: true,
|
|
@@ -226,7 +249,7 @@ export const config: AppConfig = {
|
|
|
226
249
|
maxFileSizeMB: 5,
|
|
227
250
|
dailyUploadLimit: 20
|
|
228
251
|
},
|
|
229
|
-
payment: ${
|
|
252
|
+
payment: ${r?`{
|
|
230
253
|
enabled: true,
|
|
231
254
|
provider: "${e.paymentProvider}",
|
|
232
255
|
bannedCountries: ["BY", "CU", "IR", "KP", "RU", "SY"]
|
|
@@ -238,8 +261,8 @@ export const config: AppConfig = {
|
|
|
238
261
|
prefix: "key_"
|
|
239
262
|
},
|
|
240
263
|
apiDocs: true,
|
|
241
|
-
performanceMonitor: { enabled: ${
|
|
242
|
-
|
|
264
|
+
performanceMonitor: { enabled: ${w} },
|
|
265
|
+
${p}
|
|
243
266
|
notifications: {
|
|
244
267
|
enabled: true,
|
|
245
268
|
maxPerUser: 100,
|
|
@@ -256,7 +279,11 @@ export const config: AppConfig = {
|
|
|
256
279
|
captcha: ${e.demo?`{
|
|
257
280
|
enabled: true,
|
|
258
281
|
provider: "turnstile",
|
|
259
|
-
|
|
282
|
+
// Cloudflare's always-passes TEST site key. A real one is domain-locked, so it
|
|
283
|
+
// works only for the deployment that owns it - set yours in ${yt}
|
|
284
|
+
// on the deployment, and swap TURNSTILE_SECRET_KEY to its matching secret in the
|
|
285
|
+
// same breath (a test key and a real secret reject each other).
|
|
286
|
+
siteKey: "${Pn}"
|
|
260
287
|
}`:"{ enabled: false }"},
|
|
261
288
|
support: supportConfig,
|
|
262
289
|
currency: ${e.demo?`{
|
|
@@ -278,7 +305,7 @@ export const config: AppConfig = {
|
|
|
278
305
|
}`:`{
|
|
279
306
|
base: "${e.defaultCurrency}",
|
|
280
307
|
list: [
|
|
281
|
-
{ symbol: "${
|
|
308
|
+
{ symbol: "${Ie[e.defaultCurrency].symbol}", name: "${Ie[e.defaultCurrency].name}", code: "${e.defaultCurrency}", place: "${Ie[e.defaultCurrency].place}", space: ${Ie[e.defaultCurrency].space} }
|
|
282
309
|
],
|
|
283
310
|
countryMap: {
|
|
284
311
|
default: "${e.defaultCurrency}"
|
|
@@ -302,10 +329,20 @@ export const config: AppConfig = {
|
|
|
302
329
|
},
|
|
303
330
|
ai: {
|
|
304
331
|
enabled: ${e.ai},
|
|
305
|
-
//
|
|
306
|
-
//
|
|
307
|
-
//
|
|
308
|
-
|
|
332
|
+
// Where the AI features SHOW UP. False is the desktop-first shape: the AI pages and their nav
|
|
333
|
+
// entries stay out of this website, which keeps account, login and billing, while the desktop
|
|
334
|
+
// app is the AI product. It gates the web SURFACE only - \`enabled\` above still runs the
|
|
335
|
+
// service, the /api/ai routes still answer, and the desktop app still talks to them.
|
|
336
|
+
webUi: ${e.webAi},
|
|
337
|
+
// Built-in AI: your app offers models under its OWN name, billed from user CREDITS - so it is
|
|
338
|
+
// generated on exactly when metered credits are on (which in turn need a payment provider to buy).
|
|
339
|
+
// Both halves are required, and gating on the payment provider ALONE was a real break: a project
|
|
340
|
+
// with a provider but no credits shipped built-in AI with nothing to meter it, and every built-in
|
|
341
|
+
// request 500'd on the credit pre-flight (\`costToCredits\` refuses to price against a missing
|
|
342
|
+
// scale rather than silently under-billing). Without credits your users bring their own keys -
|
|
343
|
+
// that is what \`byok\` below is. Powered by OpenRouter - set OPENROUTER_API_KEY in your env, that
|
|
344
|
+
// is the whole setup. Flip this to change it.
|
|
345
|
+
builtin: ${r&&e.credits},
|
|
309
346
|
// Let users connect their own provider API keys; flip to false to disable.
|
|
310
347
|
byok: true,
|
|
311
348
|
// What every user starts on (their own choice, once made, always wins). Plain
|
|
@@ -326,11 +363,18 @@ export const config: AppConfig = {
|
|
|
326
363
|
}
|
|
327
364
|
},
|
|
328
365
|
desktop: desktopConfig,
|
|
329
|
-
//
|
|
330
|
-
|
|
366
|
+
// Runner: the AgentRunner daemon your users install to run their own subscription CLIs for this app. Off by default.
|
|
367
|
+
runner: ${A},
|
|
331
368
|
// Outward MCP server exposing the capability layer to external agents. Its code ships with every
|
|
332
369
|
// project, so \`enabled\` alone controls the /mcp endpoint and the MCP settings tab.
|
|
333
370
|
mcpServer: { enabled: ${e.demo?"true":"false"} },
|
|
371
|
+
// Revenue sharing: your answer at init, and yours to change here at any time. On, the daily
|
|
372
|
+
// license heartbeat self-reports an aggregate revenue estimate (MRR, ARR, total and 30-day
|
|
373
|
+
// revenue, active subscriptions). No customer data, but not anonymous either: the figures travel
|
|
374
|
+
// with your domain and app name on your own license, which is what lists YOU on the
|
|
375
|
+
// generatesaas.com MRR leaderboard. Off, nothing revenue-related is computed or sent, and any
|
|
376
|
+
// figures already reported are cleared on the next heartbeat. It gates nothing else in your app.
|
|
377
|
+
revenueSharing: { enabled: ${e.revenueSharing} },
|
|
334
378
|
seo: {
|
|
335
379
|
description: "Production-ready SaaS application",
|
|
336
380
|
foundingDate: "${new Date().getFullYear()}-01-01"
|
|
@@ -347,7 +391,7 @@ export const config: AppConfig = {
|
|
|
347
391
|
schedules: "/schedules",
|
|
348
392
|
settingsModels: "/settings/models",
|
|
349
393
|
settingsIntegrations: "/settings/integrations",
|
|
350
|
-
|
|
394
|
+
settingsRunners: "/settings/runners",
|
|
351
395
|
settingsMcp: "/settings/mcp",
|
|
352
396
|
notifications: "/notifications",
|
|
353
397
|
admin: "/admin/users"
|
|
@@ -362,7 +406,7 @@ export * from "./billing-fields";
|
|
|
362
406
|
export * from "./social-providers";
|
|
363
407
|
export * from "./blog";
|
|
364
408
|
export * from "./cache";
|
|
365
|
-
export * from "./
|
|
409
|
+
export * from "./runner";
|
|
366
410
|
export * from "./footer";
|
|
367
411
|
export * from "./i18n";
|
|
368
412
|
export * from "./landing";
|
|
@@ -371,7 +415,20 @@ export * from "./pricing";
|
|
|
371
415
|
export * from "./roles";
|
|
372
416
|
export * from "./section-tabs";
|
|
373
417
|
export * from "./tenancy";
|
|
374
|
-
`,$=
|
|
418
|
+
`,$=Vt(e.projectDir,"packages/config/src/index.ts");await l($,f),await l(Vt(e.projectDir,"packages/config/src/support.ts"),`import type { SupportConfig } from "@repo/config/types";
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Live-chat (support widget) configuration, re-exported by the config index as
|
|
422
|
+
* \`config.support\`. Presence is the switch: add a \`crisp\` or \`chatwoot\` sub-key and that
|
|
423
|
+
* provider's widget loads on every surface - web and desktop. Configure ONE; both keys
|
|
424
|
+
* active would load two widgets.
|
|
425
|
+
*
|
|
426
|
+
* It lives outside the index because the desktop app's vite config imports it under raw
|
|
427
|
+
* Node, which cannot resolve the index's extensionless relative imports. Keep any relative
|
|
428
|
+
* import here type-only.
|
|
429
|
+
*/
|
|
430
|
+
export const supportConfig: SupportConfig = ${m};
|
|
431
|
+
`),await l(Vt(e.projectDir,"packages/config/src/desktop.mjs"),`// Plain-JS desktop app identity. NO env reads, so tooling that cannot import the
|
|
375
432
|
// TypeScript config index reads it directly: the Electron main + renderer bundles,
|
|
376
433
|
// the CSP policy builder, and the electron-builder packaging config. Edit these
|
|
377
434
|
// values once to rebrand - they are the same in dev and production, so they live in
|
|
@@ -379,29 +436,35 @@ export * from "./tenancy";
|
|
|
379
436
|
|
|
380
437
|
export const desktopConfig = {
|
|
381
438
|
enabled: ${e.desktop},
|
|
382
|
-
appId: "${
|
|
383
|
-
productName: "${
|
|
384
|
-
protocol: "${
|
|
385
|
-
baseUrl: "${
|
|
386
|
-
// Name of the app's data folder (created under the OS app-data dir). Where the app
|
|
387
|
-
// and its AI agents persist files - logs, gathered data, generated artifacts. Rename
|
|
388
|
-
// it freely; it is a plain folder name, not a path.
|
|
389
|
-
dataFolder: "data",
|
|
439
|
+
appId: "${g.appId}",
|
|
440
|
+
productName: "${g.productName}",
|
|
441
|
+
protocol: "${g.protocol}",
|
|
442
|
+
baseUrl: "${n}",
|
|
390
443
|
// Public base URL the release workflow uploads to; electron-updater polls
|
|
391
444
|
// \`<url>/latest-mac.yml\` (\`latest.yml\` on Windows, \`latest-linux.yml\` on Linux) plus
|
|
392
445
|
// the per-installer blockmaps, and the stable installer download links live under it.
|
|
393
|
-
autoUpdate: { url: "${
|
|
446
|
+
autoUpdate: { url: "${k}" },
|
|
394
447
|
// Whether the support live-chat widget you configured in config.support (Crisp,
|
|
395
448
|
// Chatwoot) also mounts in the DESKTOP app. On by default, so one provider reaches
|
|
396
449
|
// every surface. Set false to keep live chat on your website only - the app then
|
|
397
450
|
// mounts no widget and its CSP never names the provider's origins.
|
|
398
451
|
supportChat: true,
|
|
452
|
+
// Integrations your users connect inside the app by entering their own credentials.
|
|
453
|
+
// Empty by default, which hides the Integrations tab entirely. Everything stays on the
|
|
454
|
+
// user's machine: credentials are encrypted with the OS keychain and never reach your
|
|
455
|
+
// backend.
|
|
456
|
+
// { id, name, description?, kind: "mcp" | "api", credentials: [{ key, label, secret? }], mcp? }
|
|
457
|
+
// An \`mcp\` entry becomes a local MCP server for chats, schedules and terminal sessions
|
|
458
|
+
// once every credential is set; give it \`mcp: { command, args?, env? }\` and reference a
|
|
459
|
+
// credential in an env VALUE as the whole string "{credential:KEY}". An \`api\` entry only
|
|
460
|
+
// stores the credentials - read them from your own main-process code with
|
|
461
|
+
// \`readIntegrationCredentials(id)\`.
|
|
462
|
+
integrations: [],
|
|
399
463
|
agents: {
|
|
400
|
-
// Feature toggles only. Agents run
|
|
401
|
-
// the
|
|
402
|
-
// TypeScript wiring next to the markdown prompt files you tune.
|
|
464
|
+
// Feature toggles only. Agents run on the agent runtime the app forks from its own
|
|
465
|
+
// binary, supervised by the main process and driven through the @repo/agent-core
|
|
466
|
+
// seam - typed TypeScript wiring next to the markdown prompt files you tune.
|
|
403
467
|
enabled: ${e.desktop&&e.ai},
|
|
404
|
-
modelRegistry: { enabled: true },
|
|
405
468
|
// Provider ids that ship in this app (catalog ids like "anthropic", "openai").
|
|
406
469
|
// Omitted here, which ships them ALL; add \`providers: ["anthropic", ...]\` to trim
|
|
407
470
|
// the catalog to just the ids you list.
|
|
@@ -416,11 +479,6 @@ export const desktopConfig = {
|
|
|
416
479
|
// Cap how many chat conversations are kept per agent on the user's machine;
|
|
417
480
|
// creating a new chat past this limit deletes the oldest. Set to 0 for no limit.
|
|
418
481
|
maxChatsPerAgent: 20,
|
|
419
|
-
// Forbid the bundled companion daemon from connecting to your backend (the buyer
|
|
420
|
-
// connection lock). Default false: the app is local-first and connecting is an
|
|
421
|
-
// OPTIONAL, explicit user action. Set true for a structurally private product - the
|
|
422
|
-
// connect surface never renders AND the daemon refuses pairing.
|
|
423
|
-
connectionLock: false,
|
|
424
482
|
// Whether agent work continues after the window closes. OFF by default: the runtime is a
|
|
425
483
|
// child process of the app and is killed at quit. Turn it on if your product's value
|
|
426
484
|
// depends on schedules firing while the app is closed; end users then get a
|
|
@@ -428,41 +486,8 @@ export const desktopConfig = {
|
|
|
428
486
|
background: false
|
|
429
487
|
}
|
|
430
488
|
};
|
|
431
|
-
`),await
|
|
432
|
-
|
|
433
|
-
// desktop.mjs pattern. The config index re-exports this as config.tenancy.
|
|
434
|
-
|
|
435
|
-
export const tenancyConfig = ${e.multiTenancy?`{
|
|
436
|
-
multiTenant: true,
|
|
437
|
-
organizationLimit: 5,
|
|
438
|
-
billingScope: "${e.demo?"organization":"user"}"
|
|
439
|
-
}`:"{ multiTenant: false }"};
|
|
440
|
-
`),await c(Ue(e.projectDir,"packages/config/src/support.mjs"),`// Plain-JS support (live chat) config. NO env reads, so tooling that cannot import
|
|
441
|
-
// the TypeScript config index reads it directly (the Electron main + renderer and
|
|
442
|
-
// the desktop CSP policy builder). Mirrors the desktop.mjs pattern. The config
|
|
443
|
-
// index re-exports this as config.support.
|
|
444
|
-
|
|
445
|
-
export const supportConfig = ${a};
|
|
446
|
-
`),await c(Ue(e.projectDir,"packages/config/src/observability.mjs"),`// Plain-JS observability (error reporting) config. NO env reads, so tooling that
|
|
447
|
-
// cannot import the TypeScript config index reads it directly (the Electron main +
|
|
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";
|
|
489
|
+
`),e.desktop&&await io(e.projectDir,k,`${g.protocol}-updater`)}import{join as lo}from"path";function po(e){return e==="stripe"?' stripePriceId: "",':' polarProductId: "",'}function yr(e){let t=[];return e.withCredits&&(t.push(` credits: ${e.credits},`),t.push(" creditInterval: 30,")),e.maxSchedules!==void 0?(t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} },`),t.push(` maxSchedules: ${e.maxSchedules}`)):t.push(` apiRateLimit: { maxRequests: ${e.rateLimit} }`),t.join(`
|
|
490
|
+
`)}async function _n(e){let t=lo(e.projectDir,"packages/config/src/pricing.ts"),r=e.defaultCurrency;if(e.paymentProvider==="none"){let A=`import type { PricingConfig } from "@repo/config/types";
|
|
466
491
|
|
|
467
492
|
export const pricingConfig: PricingConfig = {
|
|
468
493
|
defaultPlan: "free",
|
|
@@ -482,7 +507,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
482
507
|
prices: [
|
|
483
508
|
{
|
|
484
509
|
interval: "lifetime",
|
|
485
|
-
amounts: { ${
|
|
510
|
+
amounts: { ${r}: 0 }
|
|
486
511
|
}
|
|
487
512
|
],
|
|
488
513
|
apiRateLimit: { maxRequests: 100 }
|
|
@@ -491,21 +516,21 @@ export const pricingConfig: PricingConfig = {
|
|
|
491
516
|
credits: { enabled: false },
|
|
492
517
|
products: { enabled: false, items: [] }
|
|
493
518
|
};
|
|
494
|
-
`;await
|
|
495
|
-
// !! USD), but your plan prices and credit purchases are denominated in ${
|
|
496
|
-
// !! ${
|
|
519
|
+
`;await l(t,A);return}let n=e.paymentProvider,i=po(n),o=e.credits,s=!!e.ai,a=yr({credits:5,rateLimit:100,withCredits:o,...s&&{maxSchedules:3}}),p=yr({credits:10,rateLimit:1e3,withCredits:o,...s&&{maxSchedules:10}}),m=yr({credits:50,rateLimit:5e3,withCredits:o}),w=r==="USD"?"":` // !! ${r} pricing WARNING: creditsPerUsd anchors credit cost to USD (AI providers bill in
|
|
520
|
+
// !! USD), but your plan prices and credit purchases are denominated in ${r}. Verify that the
|
|
521
|
+
// !! ${r} amounts above cover the USD cost per credit (~0.42 USD at creditsPerUsd 2 with the
|
|
497
522
|
// !! 20% markup) - and raise prices or creditsPerUsd if they do not.
|
|
498
|
-
`;o&&
|
|
499
|
-
!! ${
|
|
500
|
-
!! plan prices and credit purchases are denominated in ${
|
|
501
|
-
!! carries ~0.42 USD of AI cost - verify every ${
|
|
523
|
+
`;o&&r!=="USD"&&console.warn(`
|
|
524
|
+
!! ${r} pricing warning: AI credit costs are anchored to USD (providers bill in USD), but your
|
|
525
|
+
!! plan prices and credit purchases are denominated in ${r}. At the shipped economics 1 credit
|
|
526
|
+
!! carries ~0.42 USD of AI cost - verify every ${r} price still covers it (see the comment on the
|
|
502
527
|
!! credits block in packages/config/src/pricing.ts), or raise prices / creditsPerUsd.
|
|
503
|
-
`);let
|
|
528
|
+
`);let g=o?` // creditsPerUsd scales USD cost -> credits (2 = 1 credit carries ~0.42 USD of cost after the
|
|
504
529
|
// 20% markup); markupPercent is the ONE margin knob for everything that debits credits (AI,
|
|
505
530
|
// external APIs, your own features). Sanity-check whenever you change plan credits, prices, or
|
|
506
531
|
// the markup: each plan's credits / creditsPerUsd * (1 + markup) must stay BELOW its price, or
|
|
507
532
|
// full utilization runs you at a loss.
|
|
508
|
-
${
|
|
533
|
+
${w} credits: { enabled: true, creditsPerUsd: 2, markupPercent: 20 }`:" credits: { enabled: false }",k=`import type { PricingConfig } from "@repo/config/types";
|
|
509
534
|
|
|
510
535
|
export const pricingConfig: PricingConfig = {
|
|
511
536
|
defaultPlan: "free",
|
|
@@ -526,7 +551,7 @@ export const pricingConfig: PricingConfig = {
|
|
|
526
551
|
prices: [
|
|
527
552
|
{
|
|
528
553
|
interval: "lifetime",
|
|
529
|
-
amounts: { ${
|
|
554
|
+
amounts: { ${r}: 0 }
|
|
530
555
|
}
|
|
531
556
|
],
|
|
532
557
|
${a}
|
|
@@ -546,16 +571,16 @@ ${a}
|
|
|
546
571
|
{
|
|
547
572
|
${i}
|
|
548
573
|
interval: "month",
|
|
549
|
-
amounts: { ${
|
|
574
|
+
amounts: { ${r}: 9 }
|
|
550
575
|
},
|
|
551
576
|
{
|
|
552
577
|
${i}
|
|
553
578
|
interval: "year",
|
|
554
|
-
amounts: { ${
|
|
555
|
-
anchorAmounts: { ${
|
|
579
|
+
amounts: { ${r}: 90 },
|
|
580
|
+
anchorAmounts: { ${r}: 109 }
|
|
556
581
|
}
|
|
557
582
|
],
|
|
558
|
-
${
|
|
583
|
+
${p}
|
|
559
584
|
},
|
|
560
585
|
{
|
|
561
586
|
id: "pro",
|
|
@@ -575,32 +600,33 @@ ${d}
|
|
|
575
600
|
{
|
|
576
601
|
${i}
|
|
577
602
|
interval: "month",
|
|
578
|
-
amounts: { ${
|
|
579
|
-
anchorAmounts: { ${
|
|
603
|
+
amounts: { ${r}: 29 },
|
|
604
|
+
anchorAmounts: { ${r}: 39 },
|
|
580
605
|
featured: true
|
|
581
606
|
},
|
|
582
607
|
{
|
|
583
608
|
${i}
|
|
584
609
|
interval: "year",
|
|
585
|
-
amounts: { ${
|
|
586
|
-
anchorAmounts: { ${
|
|
610
|
+
amounts: { ${r}: 290 },
|
|
611
|
+
anchorAmounts: { ${r}: 349 }
|
|
587
612
|
}
|
|
588
613
|
],
|
|
589
|
-
${
|
|
614
|
+
${m}
|
|
590
615
|
}
|
|
591
616
|
],
|
|
592
|
-
${
|
|
617
|
+
${g},
|
|
593
618
|
products: {
|
|
594
619
|
enabled: false,
|
|
595
620
|
items: []
|
|
596
621
|
}
|
|
597
622
|
};
|
|
598
|
-
`;await
|
|
599
|
-
`)}function
|
|
600
|
-
`)}async function
|
|
601
|
-
`+
|
|
602
|
-
`+
|
|
623
|
+
`;await l(t,k)}var uo={smtp:[{key:"SMTP_HOST",defaultValue:"localhost"},{key:"SMTP_PORT",defaultValue:"1025"},{key:"SMTP_USER"},{key:"SMTP_PASSWORD"}],ses:[{key:"AMAZON_SES_REGION",comment:"# TODO: Configure Amazon SES credentials (e.g. us-east-1)"},{key:"AMAZON_SES_KEY"},{key:"AMAZON_SES_SECRET"}],resend:[{key:"RESEND_API_KEY",comment:"# TODO: Add your Resend API key"}]},mo={stripe:[{key:"STRIPE_SECRET_KEY",comment:"# TODO: Add your Stripe keys"},{key:"STRIPE_WEBHOOK_SECRET"}],polar:[{key:"POLAR_ACCESS_TOKEN",comment:"# TODO: Add your Polar keys"},{key:"POLAR_WEBHOOK_SECRET"}]};function vt(e,t){return t?e.map(r=>{let n=t[r.key];return n?{...r,defaultValue:n,comment:void 0}:r}):e}function et(e,t){for(let r of e)r.comment&&t.push(r.comment),r.defaultValue!==void 0?t.push(`${r.key}=${r.defaultValue}`):t.push(`#${r.key}=`)}function vr(e){return Array.from(crypto.getRandomValues(new Uint8Array(e))).map(t=>t.toString(16).padStart(2,"0")).join("")}function Dn(e){return e.architecture==="fullstack"?{apiUrl:"http://localhost:3000/api",baseUrl:"http://localhost:3000"}:{apiUrl:"http://localhost:3010",baseUrl:"http://localhost:3000"}}var fo="https://your-app.example.com/api";function Ft(e,t,r,n){e.push(n==="example"?`${t}=`:`${t}=${r}`)}function On(e,t){let r=t==="example"?void 0:e.credentials,{apiUrl:n,baseUrl:i}=Dn(e),o=[];e.architecture==="separate"?o.push("# API Configuration","# Standalone backend's own URL (the frontend reaches it via the public var above).",`API_URL=${n}`,`BASE_URL=${i}`):o.push("# App","# (API_URL is derived from the frontend's *_PUBLIC_API_URL by the runtime env schema.)",`BASE_URL=${i}`),o.push("","# Client IP (production)","# The backend rate-limits by client IP and stamps it on audit entries. YOU ALMOST","# CERTAINLY DO NOT NEED THIS: it detects Vercel, Fly.io, Render, Railway, Netlify and","# Coolify from their own env vars, and treats a private connection peer (Docker, compose,","# Kubernetes, Dokploy, an nginx/Traefik/Caddy on the same host) as proof that something is","# forwarding to it. A forwarded header is trusted only in those cases, never on a server","# exposed directly - there, a caller could have sent it themselves."),e.architecture==="fullstack"?o.push("# This build runs the API in the frontend's route handler, which has no connection","# address, so on a host the backend does not recognise there is nothing to fall back on","# and every caller shares ONE rate-limit bucket: the 10/min sign-in limit applies to","# your whole app rather than per person, and audit entries record no address."):o.push("# This build reads the connection peer, so a server exposed directly identifies its","# callers correctly with nothing set here."),o.push("# SET IT when nothing above can see your topology - the common case is a CDN in front of a","# directly exposed server, where connections arrive from a public CDN address:","# Cloudflare -> TRUSTED_PROXY=cf-connecting-ip","# another proxy in front -> TRUSTED_PROXY=1 (the number of proxies)","# Whatever you set wins over detection; `false` turns detection off and trusts nothing.","# TRUSTED_PROXY=1"),o.push("","# Auth rate limits","# Raises every Better Auth rate limit by a whole number (1-50). Unset = 1 = the","# shipped limits. No value disables them: 0, empty or unparseable fails at boot.","# You almost certainly want the default. The reason to raise it is an automated suite,","# which drives ONE address and so shares one bucket - and the e2e config already sets","# its own value, so it needs nothing here.","# AUTH_RATE_LIMIT_MULTIPLIER=1"),o.push("","# Database"),et(vt(Te[e.databaseProvider].envVars,r),o),o.push("","# Cache"),et(vt(_e[e.cacheProvider].envVars,r),o),o.push("","# Authentication"),t==="example"&&o.push("# Generate a strong secret, e.g. `openssl rand -hex 32`"),Ft(o,"BETTER_AUTH_SECRET",crypto.randomUUID(),t),o.push("","# Content API (random secret; required when contentApi feature is enabled in @repo/config)"),Ft(o,"CONTENT_API_KEY",vr(32),t),o.push("","# Job Queue - Inngest","INNGEST_APP_ID=api"),Ft(o,"INNGEST_EVENT_KEY",vr(32),t),Ft(o,"INNGEST_SIGNING_KEY",vr(32),t),o.push("INNGEST_BASE_URL=http://127.0.0.1:8288"),e.architecture==="separate"&&(o.push("","# API Port (standalone backend)","API_PORT=3010"),o.push("","# CORS + cross-subdomain cookies (production only - leave unset for local dev)","# TRUSTED_ORIGINS=https://your-app.example.com","# AUTH_COOKIE_DOMAIN=.example.com"));let s=uo[e.emailProvider];if(s&&(o.push("","# Email"),et(vt(s,r),o)),e.paymentProvider!=="none"){let p=mo[e.paymentProvider];p&&(o.push("","# Payment"),et(vt(p,r),o))}e.demo&&(o.push("","# Captcha (Cloudflare Turnstile)","# @repo/config ships Cloudflare's always-passes TEST site key, and the matching test","# secret is below - so sign-up and sign-in work with no Cloudflare account.","# THE TWO KEYS MUST MATCH: the test site key only validates against the test secret,","# and a real site key only against its own real secret. A mixed pair rejects every","# solved widget. For production set BOTH - your site key in",`# ${yt} (it overrides the committed config value) and its secret here.`,`#${yt}=`),et(vt([{key:"TURNSTILE_SECRET_KEY",defaultValue:In}],r),o)),o.push("","# Storage - S3 Compatible (required for uploads: avatars, files)","# Works with AWS S3, Cloudflare R2, MinIO, and other S3-compatible services.","# Uploads fail until these are set - storage is enabled in @repo/config by default.","#STORAGE_REGION=us-east-1","#STORAGE_ENDPOINT=https://your-account.r2.cloudflarestorage.com","#STORAGE_ACCESS_KEY_ID=","#STORAGE_SECRET_ACCESS_KEY=","# Two buckets: one publicly readable (avatars, assets), one credentials-only (private","# uploads served through the app). The bucket boundary is the privacy guarantee.","#STORAGE_PUBLIC_BUCKET=","#STORAGE_PRIVATE_BUCKET=",'# Public base URL for the public bucket. Public file URLs are STORAGE_PUBLIC_URL + "/" + key.',"#STORAGE_PUBLIC_URL=https://cdn.example.com","","# Storage - Local Filesystem (optional overrides)","# Defaults work out of the box; override for Docker volume mounts.","#STORAGE_LOCAL_PATH=/data","#STORAGE_LOCAL_PUBLIC_URL=https://cdn.example.com/files"),o.push("","# Admin Notifications (optional)","# Real-time notifications when business events occur (signups, purchases, etc.).","# Each provider is auto-enabled when its env vars are set.","#DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/...","#SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...","#TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz","#TELEGRAM_CHAT_ID=-1001234567890","#TELEGRAM_TOPIC_ID=123"),o.push("","# Social sign-in (optional)","# Enable the matching provider in @repo/config, then set its pair here.","#GOOGLE_CLIENT_ID=","#GOOGLE_CLIENT_SECRET=","#GITHUB_CLIENT_ID=","#GITHUB_CLIENT_SECRET="),o.push("","# SMS - Twilio (optional)","#TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","#TWILIO_AUTH_TOKEN=","#TWILIO_PHONE_NUMBER=+1234567890"),o.push("","# Newsletter (optional)","#RESEND_AUDIENCE_ID=","#LISTMONK_URL=https://listmonk.yourdomain.com","#LISTMONK_API_USER=admin","#LISTMONK_API_TOKEN=","#LISTMONK_LIST_ID=1"),o.push("","# Translations - OpenRouter (optional)","# Set to auto-translate en/* into your other locales with `pnpm translate`.","# The pre-commit hook runs it on commit; without a key it skips and untranslated","# locales fall back to the default locale. Get a key: https://openrouter.ai/keys","#OPENROUTER_API_KEY=");let a=[];return e.observability.includes("sentry")&&a.push({key:"SENTRY_DSN",comment:"# Overrides config.observability.sentry.dsn for the server only."}),e.observability.includes("posthog")&&a.push({key:"POSTHOG_API_KEY",comment:"# Overrides config.observability.posthog.publicKey for the server only (host stays in config)."}),a.length>0&&(o.push("","# Error and product reporting (optional)"),et(a,o)),o.push("","# AI base (optional)","# Enable config.ai in packages/config. Built-in AI resolves through OpenRouter only,","# so OPENROUTER_API_KEY above is the only provider API key the backend reads.","# BYOK is per-user and never an env var: users paste their own key in the app and it","# is stored encrypted in the database."),o.push(""),o.join(`
|
|
624
|
+
`)}var xn="NEXT_PUBLIC_API_URL";function ho(e){let{apiUrl:t}=Dn(e),r=["# API Configuration",`${xn}=${t}`];return e.architecture==="separate"&&r.push("","# Production (uncomment and replace with your deployed hostnames):",`# ${xn}=${fo}`),r.push(""),r.join(`
|
|
625
|
+
`)}async function Nn(e){let t=ho(e);await l(`${e.projectDir}/.env`,t+`
|
|
626
|
+
`+On(e,"env")),await l(`${e.projectDir}/.env.example`,t+`
|
|
627
|
+
`+On(e,"example"))}import{join as go}from"path";async function Cn(e){let t=He(e),r=[],n=[];if(t.includes("postgres")&&(r.push(` postgres:
|
|
603
628
|
image: postgres:18-alpine
|
|
629
|
+
restart: unless-stopped
|
|
604
630
|
ports:
|
|
605
631
|
- "\${POSTGRES_PORT:-5432}:5432"
|
|
606
632
|
environment:
|
|
@@ -614,8 +640,9 @@ ${k},
|
|
|
614
640
|
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
|
615
641
|
interval: 5s
|
|
616
642
|
timeout: 5s
|
|
617
|
-
retries: 5`),
|
|
643
|
+
retries: 5`),n.push(" postgres_data:")),t.includes("redis")&&(r.push(` redis:
|
|
618
644
|
image: redis:8-alpine
|
|
645
|
+
restart: unless-stopped
|
|
619
646
|
ports:
|
|
620
647
|
- "\${REDIS_PORT:-6379}:6379"
|
|
621
648
|
volumes:
|
|
@@ -624,65 +651,51 @@ ${k},
|
|
|
624
651
|
test: ["CMD", "redis-cli", "ping"]
|
|
625
652
|
interval: 5s
|
|
626
653
|
timeout: 5s
|
|
627
|
-
retries: 5`),
|
|
654
|
+
retries: 5`),n.push(" redis_data:")),t.includes("mailpit")&&r.push(` mailpit:
|
|
628
655
|
image: axllent/mailpit
|
|
656
|
+
restart: unless-stopped
|
|
629
657
|
ports:
|
|
630
658
|
- "\${MAILPIT_SMTP_PORT:-1025}:1025"
|
|
631
659
|
- "\${MAILPIT_UI_PORT:-8025}:8025"
|
|
632
660
|
environment:
|
|
633
661
|
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
|
634
|
-
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")
|
|
662
|
+
MP_SMTP_AUTH_ALLOW_INSECURE: 1`),t.includes("inngest")){let s=e.architecture==="separate"?"http://host.docker.internal:3010/inngest":"http://host.docker.internal:3000/api/inngest";r.push(` inngest:
|
|
635
663
|
image: inngest/inngest:v1.17.4
|
|
664
|
+
restart: unless-stopped
|
|
636
665
|
ports:
|
|
637
666
|
- "\${INNGEST_PORT:-8288}:8288"
|
|
638
|
-
|
|
639
|
-
|
|
667
|
+
# \`-u\` is load-bearing, not tuning. Without it \`inngest dev\` AUTO-DISCOVERS, and it scans its own
|
|
668
|
+
# container's localhost - where nothing is listening. It then registers zero apps and silently
|
|
669
|
+
# runs no functions, so on a stock stack NOTHING that goes through Inngest is ever delivered: no
|
|
670
|
+
# verification email, no password reset, no invite, no notification. Signup still returns 200 and
|
|
671
|
+
# the mailbox simply stays empty, which reads as a mail bug rather than a discovery one.
|
|
672
|
+
#
|
|
673
|
+
# \`host.docker.internal\` is how the container reaches the app on the host. It is not built in on
|
|
674
|
+
# Linux, which is what \`extra_hosts\` supplies.
|
|
675
|
+
command: >-
|
|
676
|
+
inngest dev
|
|
677
|
+
-u ${s}
|
|
678
|
+
extra_hosts:
|
|
679
|
+
- "host.docker.internal:host-gateway"`)}let o=`name: ${`${e.projectName}-infra`}
|
|
680
|
+
|
|
681
|
+
services:
|
|
682
|
+
${r.join(`
|
|
640
683
|
|
|
641
684
|
`)}
|
|
642
|
-
`;
|
|
685
|
+
`;n.length>0&&(o+=`
|
|
643
686
|
volumes:
|
|
644
|
-
${
|
|
687
|
+
${n.join(`
|
|
645
688
|
`)}
|
|
646
|
-
`),await
|
|
647
|
-
`)}import{
|
|
648
|
-
import
|
|
649
|
-
import { closeRedis, env, logger } from "@repo/runtime";
|
|
650
|
-
|
|
651
|
-
async function bootstrap() {
|
|
652
|
-
const apiServer = serve({
|
|
653
|
-
fetch: app.fetch,
|
|
654
|
-
port: env.API_PORT,
|
|
655
|
-
});
|
|
656
|
-
logger.info(\`[API] Listening on port \${env.API_PORT}\`);
|
|
657
|
-
|
|
658
|
-
const shutdown = async (signal: string) => {
|
|
659
|
-
logger.info("[Backend] Shutting down", { signal });
|
|
660
|
-
try {
|
|
661
|
-
await closeRedis();
|
|
662
|
-
} catch (err) {
|
|
663
|
-
logger.error("[Backend] Redis close error during shutdown", err);
|
|
664
|
-
}
|
|
665
|
-
apiServer.close(() => {
|
|
666
|
-
process.exit(0);
|
|
667
|
-
});
|
|
668
|
-
};
|
|
669
|
-
|
|
670
|
-
process.on("SIGINT", () => void shutdown("SIGINT"));
|
|
671
|
-
process.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
bootstrap().catch((error) => {
|
|
675
|
-
logger.error("[Backend] Fatal error", error);
|
|
676
|
-
process.exit(1);
|
|
677
|
-
});
|
|
678
|
-
`)}import{readFile as Co}from"fs/promises";import{join as No}from"path";var Xt='import { drizzle } from "drizzle-orm/node-postgres";',Zt=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
679
|
-
export const pool = db.$client;`,$o={postgres:{importLine:Xt,instantiation:Zt},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
|
|
689
|
+
`),await l(go(e.projectDir,"infra/docker-compose.yml"),o)}import{join as yo}from"path";var bt="Next.js";function vo(e){let t=[];if(t.push({type:"node-terminal",request:"launch",name:"Dev",command:"pnpm dev",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.architecture==="separate"&&t.push({type:"node-terminal",request:"launch",name:"Backend",command:"pnpm dev",cwd:"${workspaceFolder}/apps/backend",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:bt,command:"pnpm dev",cwd:"${workspaceFolder}/apps/web",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.docs&&t.push({type:"node-terminal",request:"launch",name:"Docs",command:"pnpm dev",cwd:"${workspaceFolder}/apps/docs",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.desktop){let r=e.architecture==="separate"?"http://localhost:3010":"http://localhost:3000/api";t.push({type:"node-terminal",request:"launch",name:"Desktop",command:"pnpm dev",cwd:"${workspaceFolder}/apps/electron",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development",BASE_URL:"http://localhost:3000",PUBLIC_API_URL:r}})}if(t.push({type:"node-terminal",request:"launch",name:"Inngest",command:"pnpm dev:inngest",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),t.push({type:"node-terminal",request:"launch",name:"Mail",command:"pnpm dev:mail",cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"],env:{NODE_ENV:"development"}}),e.paymentProvider==="stripe"){let r=e.architecture==="separate"?"localhost:3010/auth/stripe/webhook":"localhost:3000/api/auth/stripe/webhook";t.push({type:"node-terminal",request:"launch",name:"Stripe",command:`stripe listen --forward-to ${r}`,cwd:"${workspaceFolder}",skipFiles:["<node_internals>/**"]})}return t}function bo(e){let t=[];return e.architecture==="separate"?t.push({name:`Dev (${bt} + Backend + Inngest)`,configurations:["Backend",bt,"Inngest"]}):t.push({name:`Dev (${bt} + Inngest)`,configurations:[bt,"Inngest"]}),t}async function $n(e){let t={version:"0.2.0",configurations:vo(e),compounds:bo(e)};await l(yo(e.projectDir,".vscode/launch.json"),JSON.stringify(t,null," ")+`
|
|
690
|
+
`)}import{readFile as wo}from"fs/promises";import{join as ko}from"path";var br='import { drizzle } from "drizzle-orm/node-postgres";',wr=`export const db = drizzle(parsed.data.DATABASE_URL, { schema });
|
|
691
|
+
export const pool = db.$client;`,Eo={postgres:{importLine:br,instantiation:wr},neon:{importLine:`import { Pool } from "@neondatabase/serverless";
|
|
680
692
|
import { drizzle } from "drizzle-orm/neon-serverless";`,instantiation:`const pool = new Pool({ connectionString: parsed.data.DATABASE_URL });
|
|
681
693
|
export const db = drizzle(pool, { schema });`},supabase:{importLine:`import { drizzle } from "drizzle-orm/postgres-js";
|
|
682
694
|
import postgres from "postgres";`,instantiation:`const client = postgres(parsed.data.DATABASE_URL);
|
|
683
|
-
export const db = drizzle(client, { schema });`}};async function
|
|
695
|
+
export const db = drizzle(client, { schema });`}};async function Ln(e){let t=ko(e.projectDir,"packages/database/src/index.ts"),r=await wo(t,"utf-8");if(!r.includes(br)||!r.includes(wr))throw new Error("generateDbDriver: boilerplate packages/database/src/index.ts is missing the node-postgres driver anchors (the import line or the `db` instantiation block); the boilerplate drifted.");let n=Eo[e.databaseProvider],i=r.replace(br,n.importLine).replace(wr,n.instantiation);await l(t,i)}import{join as Bt}from"path";async function jn(e){switch(e.cacheProvider){case"redis":await So(e),await Ro(e);break;case"upstash":await Ao(e),await Po(e);break}}async function So(e){await l(Bt(e.projectDir,"packages/runtime/src/redis.ts"),`import type { Store } from "hono-rate-limiter";
|
|
684
696
|
import { Redis } from "ioredis";
|
|
685
|
-
import { RedisStore
|
|
697
|
+
import { RedisStore } from "rate-limit-redis";
|
|
698
|
+
import type { RedisReply } from "rate-limit-redis";
|
|
686
699
|
import { env } from "./env";
|
|
687
700
|
|
|
688
701
|
/** Options for \`redis.cacheSet\`. */
|
|
@@ -707,6 +720,8 @@ export interface BoilerplateRedisHelpers {
|
|
|
707
720
|
cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean>;
|
|
708
721
|
/** GET typed as \`string | null\`. (On Upstash this also disables auto-deserialization for consistent string round-trip.) */
|
|
709
722
|
cacheGet(key: string): Promise<string | null>;
|
|
723
|
+
/** MGET over an array of keys, typed as \`(string | null)[]\` in the order given. The SDKs' native \`mget\` differ in both arity and return typing. */
|
|
724
|
+
cacheMGet(keys: string[]): Promise<(string | null)[]>;
|
|
710
725
|
/** Iterate keys matching a glob pattern via SCAN. Yields each key as it's discovered. */
|
|
711
726
|
cacheScan(opts: { match: string; count?: number }): AsyncIterable<string>;
|
|
712
727
|
/** Run a Lua script via EVAL with explicit key and argument lists (the SDKs' native \`eval\` signatures differ). Returns the script's raw reply. */
|
|
@@ -755,6 +770,10 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(ioredis, {
|
|
|
755
770
|
async cacheGet(key: string): Promise<string | null> {
|
|
756
771
|
return ioredis.get(key);
|
|
757
772
|
},
|
|
773
|
+
async cacheMGet(keys: string[]): Promise<(string | null)[]> {
|
|
774
|
+
if (keys.length === 0) return [];
|
|
775
|
+
return ioredis.mget(...keys);
|
|
776
|
+
},
|
|
758
777
|
async *cacheScan(opts: { match: string; count?: number }): AsyncIterable<string> {
|
|
759
778
|
let cursor = "0";
|
|
760
779
|
do {
|
|
@@ -776,10 +795,23 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(ioredis, {
|
|
|
776
795
|
* Wraps RedisStore in an adapter exposing only the methods the middleware uses
|
|
777
796
|
* so we don't need an unsafe cross-package type cast.
|
|
778
797
|
*/
|
|
779
|
-
function createLimiterStore(): Store {
|
|
798
|
+
export function createLimiterStore(): Store {
|
|
780
799
|
const inner = new RedisStore({
|
|
781
|
-
sendCommand: (command: string, ...args: string[]) =>
|
|
782
|
-
ioredis.call(command, ...args) as Promise<RedisReply
|
|
800
|
+
sendCommand: (command: string, ...args: string[]) => {
|
|
801
|
+
const pending = ioredis.call(command, ...args) as Promise<RedisReply>;
|
|
802
|
+
// Mark it handled WITHOUT consuming it. A limiter command outlives the request that
|
|
803
|
+
// issued it: the request fail-opens and returns, and nobody is awaiting this promise any
|
|
804
|
+
// more when the cache blips and ioredis rejects the queued command with "Connection is
|
|
805
|
+
// closed". Node treats an unhandled rejection as fatal, so a cache hiccup could take the
|
|
806
|
+
// process down - and during a Docker build or prerender, where Redis is not reachable
|
|
807
|
+
// yet, the fire-and-forget SCRIPT LOAD aborts the build outright.
|
|
808
|
+
//
|
|
809
|
+
// Attaching a catch marks THIS promise handled; returning the same promise leaves the
|
|
810
|
+
// store free to await it and see the error, so nothing is swallowed from a caller that
|
|
811
|
+
// cares.
|
|
812
|
+
pending.catch(() => undefined);
|
|
813
|
+
return pending;
|
|
814
|
+
}
|
|
783
815
|
});
|
|
784
816
|
return {
|
|
785
817
|
init(options) {
|
|
@@ -793,8 +825,6 @@ function createLimiterStore(): Store {
|
|
|
793
825
|
};
|
|
794
826
|
}
|
|
795
827
|
|
|
796
|
-
export const limiterStore: Store = createLimiterStore();
|
|
797
|
-
|
|
798
828
|
let closed = false;
|
|
799
829
|
|
|
800
830
|
/** Gracefully close the Redis connection; idempotent. Falls back to disconnect() on error. */
|
|
@@ -809,7 +839,7 @@ export async function closeRedis() {
|
|
|
809
839
|
closed = true;
|
|
810
840
|
}
|
|
811
841
|
}
|
|
812
|
-
`)}async function
|
|
842
|
+
`)}async function Ro(e){await l(Bt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Mutex } from "redis-semaphore";
|
|
813
843
|
import { redis } from "./redis";
|
|
814
844
|
|
|
815
845
|
export class MutexTimeoutError extends Error {
|
|
@@ -819,20 +849,39 @@ export class MutexTimeoutError extends Error {
|
|
|
819
849
|
}
|
|
820
850
|
}
|
|
821
851
|
|
|
852
|
+
/** Delay between acquisition attempts. */
|
|
853
|
+
const RETRY_INTERVAL_MS = 500;
|
|
854
|
+
|
|
822
855
|
/**
|
|
823
856
|
* Execute \`fn\` while holding a distributed mutex on \`key\`. Backed by
|
|
824
857
|
* \`redis-semaphore\`, which uses Lua scripts for atomic compare-and-delete
|
|
825
|
-
* on release and
|
|
858
|
+
* on release and refreshes the lock while \`fn\` runs.
|
|
859
|
+
*
|
|
860
|
+
* \`acquireTimeout\` is honoured; the attempt budget is derived from it so the two cannot disagree.
|
|
861
|
+
*
|
|
862
|
+
* \`onLockLost\` is supplied because the library's default is \`throw err\`, and it fires from the
|
|
863
|
+
* REFRESH TIMER rather than this call stack - so one failed refresh became an unhandled rejection
|
|
864
|
+
* and, by Node's default, killed the process in the middle of whatever the lock was guarding. The
|
|
865
|
+
* handler logs and lets the work finish: crashing is the defect, and failing a completed operation
|
|
866
|
+
* invites a retry of work that already happened.
|
|
826
867
|
*/
|
|
827
868
|
export async function withMutex<T>(
|
|
828
869
|
key: string,
|
|
829
870
|
fn: () => Promise<T>,
|
|
830
871
|
options?: { lockTimeout?: number; acquireTimeout?: number }
|
|
831
872
|
): Promise<T> {
|
|
873
|
+
const acquireTimeout = options?.acquireTimeout ?? 5_000;
|
|
832
874
|
const mutex = new Mutex(redis, key, {
|
|
833
875
|
lockTimeout: options?.lockTimeout ?? 10_000,
|
|
834
|
-
|
|
835
|
-
|
|
876
|
+
acquireTimeout,
|
|
877
|
+
acquireAttemptsLimit: Math.max(1, Math.ceil(acquireTimeout / RETRY_INTERVAL_MS)),
|
|
878
|
+
retryInterval: RETRY_INTERVAL_MS,
|
|
879
|
+
onLockLost: (error) => {
|
|
880
|
+
console.error(
|
|
881
|
+
\`[Mutex] Lock lost while the critical section was still running - mutual exclusion has lapsed (key: \${key})\`,
|
|
882
|
+
error
|
|
883
|
+
);
|
|
884
|
+
}
|
|
836
885
|
});
|
|
837
886
|
|
|
838
887
|
const acquired = await mutex.tryAcquire();
|
|
@@ -843,10 +892,14 @@ export async function withMutex<T>(
|
|
|
843
892
|
try {
|
|
844
893
|
return await fn();
|
|
845
894
|
} finally {
|
|
846
|
-
|
|
895
|
+
// Releasing a lock that was already lost rejects. Letting that escape from \`finally\` would
|
|
896
|
+
// REPLACE whatever the critical section returned or threw.
|
|
897
|
+
await mutex.release().catch((error: unknown) => {
|
|
898
|
+
console.error(\`[Mutex] Failed to release lock (its TTL will expire it) (key: \${key})\`, error);
|
|
899
|
+
});
|
|
847
900
|
}
|
|
848
901
|
}
|
|
849
|
-
`)}async function
|
|
902
|
+
`)}async function Ao(e){await l(Bt(e.projectDir,"packages/runtime/src/redis.ts"),`import { Redis } from "@upstash/redis";
|
|
850
903
|
import type { Store } from "hono-rate-limiter";
|
|
851
904
|
import { env } from "./env";
|
|
852
905
|
|
|
@@ -872,6 +925,8 @@ export interface BoilerplateRedisHelpers {
|
|
|
872
925
|
cacheSet(key: string, value: string, opts?: CacheSetOptions): Promise<boolean>;
|
|
873
926
|
/** GET typed as \`string | null\`. Pairs with \`automaticDeserialization: false\` for consistent string round-trip. */
|
|
874
927
|
cacheGet(key: string): Promise<string | null>;
|
|
928
|
+
/** MGET over an array of keys, typed as \`(string | null)[]\` in the order given. The SDKs' native \`mget\` differ in both arity and return typing. */
|
|
929
|
+
cacheMGet(keys: string[]): Promise<(string | null)[]>;
|
|
875
930
|
/** Iterate keys matching a glob pattern via SCAN. Yields each key as it's discovered. */
|
|
876
931
|
cacheScan(opts: { match: string; count?: number }): AsyncIterable<string>;
|
|
877
932
|
/** Run a Lua script via EVAL with explicit key and argument lists (the SDKs' native \`eval\` signatures differ). Returns the script's raw reply. */
|
|
@@ -916,6 +971,10 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(upstash, {
|
|
|
916
971
|
async cacheGet(key: string): Promise<string | null> {
|
|
917
972
|
return upstash.get<string>(key);
|
|
918
973
|
},
|
|
974
|
+
async cacheMGet(keys: string[]): Promise<(string | null)[]> {
|
|
975
|
+
if (keys.length === 0) return [];
|
|
976
|
+
return upstash.mget<(string | null)[]>(...keys);
|
|
977
|
+
},
|
|
919
978
|
async *cacheScan(opts: { match: string; count?: number }): AsyncIterable<string> {
|
|
920
979
|
let cursor = "0";
|
|
921
980
|
do {
|
|
@@ -929,23 +988,48 @@ export const redis: Redis & BoilerplateRedisHelpers = Object.assign(upstash, {
|
|
|
929
988
|
}
|
|
930
989
|
});
|
|
931
990
|
|
|
991
|
+
/**
|
|
992
|
+
* Counter increment, window expiry and TTL read in ONE round trip.
|
|
993
|
+
*
|
|
994
|
+
* Split across separate INCR / PEXPIRE / PTTL calls this is not safe: with the expiry behind an
|
|
995
|
+
* \`if (totalHits === 1)\` guard, a crash or a failed REST call between the INCR and the PEXPIRE
|
|
996
|
+
* leaves the key at 1 with NO expiry. Every later request then increments a counter that never
|
|
997
|
+
* resets and never re-enters the guard, so that client is rate-limited out of the entire API
|
|
998
|
+
* permanently - and PTTL returning -1 reports \`resetTime\` as now, telling them to retry
|
|
999
|
+
* immediately, so they loop on 429s with no diagnostic. \`rate-limit-redis\` runs the equivalent as
|
|
1000
|
+
* one Lua script on the ioredis build; this keeps both cache backends behaving the same.
|
|
1001
|
+
*
|
|
1002
|
+
* The \`ttl < 0\` branch is a self-heal, not belt-and-braces: it re-arms the window for any key that
|
|
1003
|
+
* has already lost its expiry, so a counter stranded by an earlier failure recovers on its next hit
|
|
1004
|
+
* instead of blocking that client forever.
|
|
1005
|
+
*/
|
|
1006
|
+
const INCREMENT_SCRIPT = \`
|
|
1007
|
+
local hits = redis.call('INCR', KEYS[1])
|
|
1008
|
+
local ttl = redis.call('PTTL', KEYS[1])
|
|
1009
|
+
if ttl < 0 then
|
|
1010
|
+
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
|
1011
|
+
ttl = tonumber(ARGV[1])
|
|
1012
|
+
end
|
|
1013
|
+
return {hits, ttl}
|
|
1014
|
+
\`;
|
|
1015
|
+
|
|
932
1016
|
/**
|
|
933
1017
|
* Rate-limit store compatible with \`hono-rate-limiter\`, backed by Upstash Redis.
|
|
934
1018
|
* Uses atomic INCR + PEXPIRE for a simple sliding-window counter. Returned as
|
|
935
1019
|
* a plain object matching \`Store\` so no unsafe type cast is needed.
|
|
936
1020
|
*/
|
|
937
|
-
function createLimiterStore(): Store {
|
|
1021
|
+
export function createLimiterStore(): Store {
|
|
938
1022
|
let windowMs = 60_000;
|
|
939
1023
|
return {
|
|
940
1024
|
init(options: { windowMs: number }): void {
|
|
941
1025
|
windowMs = options.windowMs;
|
|
942
1026
|
},
|
|
943
1027
|
async increment(key: string): Promise<{ totalHits: number; resetTime: Date }> {
|
|
944
|
-
const totalHits = await upstash.
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
1028
|
+
const [totalHits, ttl] = await upstash.eval<[number], [number, number]>(
|
|
1029
|
+
INCREMENT_SCRIPT,
|
|
1030
|
+
[key],
|
|
1031
|
+
[windowMs]
|
|
1032
|
+
);
|
|
949
1033
|
return {
|
|
950
1034
|
totalHits,
|
|
951
1035
|
resetTime: new Date(Date.now() + Math.max(0, ttl))
|
|
@@ -960,11 +1044,9 @@ function createLimiterStore(): Store {
|
|
|
960
1044
|
};
|
|
961
1045
|
}
|
|
962
1046
|
|
|
963
|
-
export const limiterStore: Store = createLimiterStore();
|
|
964
|
-
|
|
965
1047
|
/** No persistent connection to close with Upstash REST. */
|
|
966
1048
|
export async function closeRedis(): Promise<void> {}
|
|
967
|
-
`)}async function
|
|
1049
|
+
`)}async function Po(e){await l(Bt(e.projectDir,"packages/runtime/src/mutex.ts"),`import { Lock } from "@upstash/lock";
|
|
968
1050
|
import { redis } from "./redis";
|
|
969
1051
|
|
|
970
1052
|
export class MutexTimeoutError extends Error {
|
|
@@ -974,12 +1056,23 @@ export class MutexTimeoutError extends Error {
|
|
|
974
1056
|
}
|
|
975
1057
|
}
|
|
976
1058
|
|
|
1059
|
+
/** Fraction of the lease after which the lock is renewed, matching redis-semaphore's default. */
|
|
1060
|
+
const REFRESH_INTERVAL_COEF = 0.8;
|
|
1061
|
+
|
|
977
1062
|
/**
|
|
978
1063
|
* Execute \`fn\` while holding a distributed mutex on \`key\`. Backed by
|
|
979
1064
|
* \`@upstash/lock\`, Upstash's official distributed-lock library - uses
|
|
980
|
-
* Lua EVAL for atomic compare-and-delete on release (no TOCTOU race)
|
|
981
|
-
*
|
|
982
|
-
*
|
|
1065
|
+
* Lua EVAL for atomic compare-and-delete on release (no TOCTOU race).
|
|
1066
|
+
*
|
|
1067
|
+
* THE LEASE IS RENEWED WHILE \`fn\` RUNS. Without that the lock simply expires after
|
|
1068
|
+
* \`lockTimeout\` and a second caller acquires it while the first is still inside its critical
|
|
1069
|
+
* section - so the mutex guarding every credit and plan mutation stops guarding anything, silently,
|
|
1070
|
+
* on exactly the long operations that need it most. The ioredis backend gets this for free from
|
|
1071
|
+
* redis-semaphore; wiring it here keeps both cache backends behaving the same, which matters because
|
|
1072
|
+
* a buyer picks one and never sees the other.
|
|
1073
|
+
*
|
|
1074
|
+
* A failed renewal is LOGGED, not thrown: the timer has no caller to reject to, and turning a
|
|
1075
|
+
* completed operation into a failure invites a retry of work that already happened.
|
|
983
1076
|
*/
|
|
984
1077
|
export async function withMutex<T>(
|
|
985
1078
|
key: string,
|
|
@@ -1003,154 +1096,177 @@ export async function withMutex<T>(
|
|
|
1003
1096
|
throw new MutexTimeoutError(key);
|
|
1004
1097
|
}
|
|
1005
1098
|
|
|
1099
|
+
const refresh = setInterval(() => {
|
|
1100
|
+
void lock
|
|
1101
|
+
.extend(lockTimeout)
|
|
1102
|
+
.then((extended) => {
|
|
1103
|
+
if (!extended) {
|
|
1104
|
+
console.error(
|
|
1105
|
+
\`[Mutex] Lock lost while the critical section was still running - mutual exclusion has lapsed (key: \${key})\`
|
|
1106
|
+
);
|
|
1107
|
+
}
|
|
1108
|
+
})
|
|
1109
|
+
.catch((error: unknown) => {
|
|
1110
|
+
console.error(\`[Mutex] Failed to renew lock (key: \${key})\`, error);
|
|
1111
|
+
});
|
|
1112
|
+
}, Math.max(1, Math.round(lockTimeout * REFRESH_INTERVAL_COEF)));
|
|
1113
|
+
// Never let the renewal timer hold the process open on its own.
|
|
1114
|
+
refresh.unref?.();
|
|
1115
|
+
|
|
1006
1116
|
try {
|
|
1007
1117
|
return await fn();
|
|
1008
1118
|
} finally {
|
|
1009
|
-
|
|
1119
|
+
clearInterval(refresh);
|
|
1120
|
+
// Releasing a lock that already expired rejects. Letting that escape from \`finally\` would
|
|
1121
|
+
// REPLACE whatever the critical section returned or threw.
|
|
1122
|
+
await lock.release().catch((error: unknown) => {
|
|
1123
|
+
console.error(\`[Mutex] Failed to release lock (its lease will expire it) (key: \${key})\`, error);
|
|
1124
|
+
});
|
|
1010
1125
|
}
|
|
1011
1126
|
}
|
|
1012
|
-
`)}
|
|
1127
|
+
`)}import{readFile as Io}from"fs/promises";import{join as To}from"path";var Mn=" REDIS_URL: z.string(),",_o=` UPSTASH_REDIS_REST_URL: z.string(),
|
|
1128
|
+
UPSTASH_REDIS_REST_TOKEN: z.string(),`;async function Un(e){let t=To(e.projectDir,"packages/runtime/src/env.ts"),r=await Io(t,"utf-8");if(!r.includes(Mn))throw new Error("generateEnvSchema: boilerplate packages/runtime/src/env.ts is missing the REDIS_URL cache binding anchor; the boilerplate drifted.");let n=e.cacheProvider==="upstash"?r.replace(Mn,_o):r;await l(t,n)}import{readFile as Vn}from"fs/promises";import{join as ee}from"path";var Kt={"@upstash/redis":"^1.37.0","@upstash/lock":"^0.2.1","@neondatabase/serverless":"^1.0.1",postgres:"^3.4.7"};async function tt(e){let t=await Vn(e,"utf-8");return JSON.parse(t)}async function rt(e,t){let r=/\n([\t ]+)"/.exec(await Vn(e,"utf-8"))?.[1]??" ";await l(e,JSON.stringify(t,null,r)+`
|
|
1129
|
+
`)}function Ce(e,t){for(let r of t)delete e.dependencies?.[r],delete e.devDependencies?.[r]}function wt(e,t,r,n=!1){let i=n?"devDependencies":"dependencies";e[i]||(e[i]={}),e[i][t]=r}async function Fn(e){await Oo(e),await xo(e),await Do(e),await $o(e),await Lo(e),await Vo(e)}async function Oo(e){let t=ee(e.projectDir,"packages/api/package.json"),r=await tt(t);Ce(r,["sharp","@types/sharp"]),e.cacheProvider==="upstash"&&Ce(r,["ioredis"]),await rt(t,r)}async function xo(e){let t=ee(e.projectDir,"apps/web/package.json"),r=await tt(t);Ce(r,["@upstash/ratelimit","@upstash/redis"]),await rt(t,r)}async function Do(e){let t=ee(e.projectDir,"packages/runtime/package.json"),r=await tt(t);e.cacheProvider==="upstash"&&(Ce(r,["ioredis","rate-limit-redis","redis-semaphore"]),wt(r,"@upstash/redis",Kt["@upstash/redis"]),wt(r,"@upstash/lock",Kt["@upstash/lock"])),await rt(t,r)}var kr={sentry:["@sentry/node","@sentry/browser","@sentry/electron"],posthog:["posthog-node","posthog-js"]},No=["@sentry/electron"],Co=[...kr.sentry,...kr.posthog];async function $o(e){let t=ee(e.projectDir,"packages/observability/package.json"),r=await tt(t),n=new Set(e.observability.flatMap(i=>kr[i]));if(!e.desktop)for(let i of No)n.delete(i);Ce(r,Co.filter(i=>!n.has(i))),await rt(t,r)}async function Lo(e){let t=ee(e.projectDir,"packages/database/package.json"),r=await tt(t);e.databaseProvider==="neon"?(Ce(r,["pg","@types/pg"]),wt(r,"@neondatabase/serverless",Kt["@neondatabase/serverless"])):e.databaseProvider==="supabase"&&(Ce(r,["pg","@types/pg"]),wt(r,"postgres",Kt.postgres)),await rt(t,r)}var jo=["app/.well-known/oauth-authorization-server/[[...path]]/route.ts","app/.well-known/oauth-protected-resource/[[...path]]/route.ts"];async function Mo(e){let t=await tt(e),r=t.dependencies?.["@repo/api"];r&&(delete t.dependencies?.["@repo/api"],wt(t,"@repo/api",r,!0),await rt(e,t))}var Uo=["instrumentation.ts","tests/instrumentation.test.ts"];async function Vo(e){if(e.architecture!=="separate")return;let t=ee(e.projectDir,"apps/web");await Mt(ee(t,"app/api/[[...rest]]/route.ts"),t);for(let r of jo)await Mt(ee(t,r),t);for(let r of Uo)await Mt(ee(t,r),t);await Mo(ee(t,"package.json"))}import{readFile as Fo}from"fs/promises";import{join as Bo}from"path";var Ko=["base.json","node.json","next.json"],Bn="GenerateSaaS ";async function Kn(e){if(!e.demo)for(let t of Ko){let r=Bo(e.projectDir,"tooling/typescript",t),n;try{n=await Fo(r,"utf-8")}catch{continue}let i=JSON.parse(n);typeof i.display!="string"||!i.display.startsWith(Bn)||(i.display=i.display.slice(Bn.length),await l(r,JSON.stringify(i,null," ")+`
|
|
1130
|
+
`))}}import{readFile as Hn,rm as Go}from"fs/promises";import{join as kt}from"path";async function Yn(e){e.cacheProvider==="upstash"&&(await Promise.all([Gn(kt(e.projectDir,"packages/runtime/tests/setup.ts")),Gn(kt(e.projectDir,"packages/mail/tests/setup.ts")),Yo(e.projectDir),Go(kt(e.projectDir,"packages/runtime/tests/redis.test.ts"),{force:!0})]),await Ho(e.projectDir))}async function Ho(e){await l(kt(e,"packages/runtime/tests/redis.test.ts"),`import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
1013
1131
|
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
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(),
|
|
1132
|
+
/**
|
|
1133
|
+
* Regression guards for the Upstash-backed cache layer in src/redis.ts.
|
|
1134
|
+
*
|
|
1135
|
+
* EVERYTHING cache-backend-specific belongs in THIS file, so the rest of the suite never has to
|
|
1136
|
+
* know which client is underneath. \`@upstash/redis\` is mocked at the module boundary by an
|
|
1137
|
+
* in-memory fake, so the suite needs no network and no Upstash account.
|
|
1138
|
+
*
|
|
1139
|
+
* The contract pinned here - TTL units, the NX guard, verbatim string round-trip, multi-key reads
|
|
1140
|
+
* and full SCAN pagination - is what every credit and plan mutation depends on through the mutex
|
|
1141
|
+
* and the rate limiter.
|
|
1142
|
+
*/
|
|
1043
1143
|
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1144
|
+
interface FakeEntry {
|
|
1145
|
+
value: string;
|
|
1146
|
+
/** Absolute expiry (ms epoch), or null when the key has no TTL. */
|
|
1147
|
+
expiresAt: number | null;
|
|
1148
|
+
}
|
|
1047
1149
|
|
|
1048
|
-
|
|
1049
|
-
AMAZON_SES_KEY: z.string().optional(),
|
|
1050
|
-
AMAZON_SES_SECRET: z.string().optional(),
|
|
1150
|
+
const store = new Map<string, FakeEntry>();
|
|
1051
1151
|
|
|
1052
|
-
|
|
1053
|
-
|
|
1152
|
+
/** Read a key, honouring TTL expiry. */
|
|
1153
|
+
function live(key: string): FakeEntry | null {
|
|
1154
|
+
const entry = store.get(key);
|
|
1155
|
+
if (!entry) return null;
|
|
1156
|
+
if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
|
|
1157
|
+
store.delete(key);
|
|
1158
|
+
return null;
|
|
1159
|
+
}
|
|
1160
|
+
return entry;
|
|
1161
|
+
}
|
|
1054
1162
|
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1163
|
+
vi.mock("@upstash/redis", () => {
|
|
1164
|
+
class Redis {
|
|
1165
|
+
async get(key: string): Promise<string | null> {
|
|
1166
|
+
return live(key)?.value ?? null;
|
|
1167
|
+
}
|
|
1168
|
+
async mget(...keys: string[]): Promise<(string | null)[]> {
|
|
1169
|
+
return keys.map((key) => live(key)?.value ?? null);
|
|
1170
|
+
}
|
|
1171
|
+
async set(key: string, value: string, opts?: Record<string, unknown>): Promise<"OK" | null> {
|
|
1172
|
+
if (opts?.nx === true && live(key)) return null;
|
|
1173
|
+
const ttlMs =
|
|
1174
|
+
typeof opts?.px === "number" ? opts.px : typeof opts?.ex === "number" ? opts.ex * 1000 : null;
|
|
1175
|
+
store.set(key, { value, expiresAt: ttlMs === null ? null : Date.now() + ttlMs });
|
|
1176
|
+
return "OK";
|
|
1177
|
+
}
|
|
1178
|
+
async scan(cursor: string, opts: { match: string }): Promise<[string, string[]]> {
|
|
1179
|
+
const pattern = new RegExp(\`^\${opts.match.split("*").join(".*")}$\`);
|
|
1180
|
+
const keys = [...store.keys()].filter((key) => live(key) && pattern.test(key));
|
|
1181
|
+
// One key per page, so a consumer that stops at the first page fails here.
|
|
1182
|
+
const index = Number(cursor);
|
|
1183
|
+
const next = index + 1 >= keys.length ? "0" : String(index + 1);
|
|
1184
|
+
return [next, keys.slice(index, index + 1)];
|
|
1185
|
+
}
|
|
1186
|
+
async eval(): Promise<unknown> {
|
|
1187
|
+
return null;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
return { Redis };
|
|
1191
|
+
});
|
|
1059
1192
|
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
SMTP_PASSWORD: z.string().optional(),
|
|
1193
|
+
// No env mock: \`tests/setup.ts\` already supplies UPSTASH_REDIS_REST_URL / _TOKEN as process-env
|
|
1194
|
+
// defaults, which is what src/env.ts validates at module load.
|
|
1195
|
+
const { redis } = await import("../src/redis");
|
|
1064
1196
|
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1197
|
+
beforeEach(() => {
|
|
1198
|
+
store.clear();
|
|
1199
|
+
});
|
|
1068
1200
|
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1201
|
+
describe("cacheSet / cacheGet", () => {
|
|
1202
|
+
it("round-trips a value verbatim", async () => {
|
|
1203
|
+
await redis.cacheSet("k", "raw-string");
|
|
1204
|
+
await expect(redis.cacheGet("k")).resolves.toBe("raw-string");
|
|
1205
|
+
});
|
|
1074
1206
|
|
|
1075
|
-
|
|
1076
|
-
|
|
1207
|
+
it("reports a miss as null rather than undefined", async () => {
|
|
1208
|
+
await expect(redis.cacheGet("absent")).resolves.toBeNull();
|
|
1209
|
+
});
|
|
1077
1210
|
|
|
1078
|
-
|
|
1079
|
-
|
|
1211
|
+
it("treats ttlSeconds as SECONDS and ttlMilliseconds as MILLISECONDS", async () => {
|
|
1212
|
+
await redis.cacheSet("s", "v", { ttlSeconds: 60 });
|
|
1213
|
+
await redis.cacheSet("m", "v", { ttlMilliseconds: 60 });
|
|
1080
1214
|
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
STORAGE_PRIVATE_BUCKET: z.string().optional(),
|
|
1087
|
-
STORAGE_PUBLIC_URL: z.string().optional(),
|
|
1215
|
+
const seconds = store.get("s")?.expiresAt ?? 0;
|
|
1216
|
+
const millis = store.get("m")?.expiresAt ?? 0;
|
|
1217
|
+
// A unit mix-up here expires a lock 1000x early or holds it 1000x too long.
|
|
1218
|
+
expect(seconds - millis).toBeGreaterThan(50_000);
|
|
1219
|
+
});
|
|
1088
1220
|
|
|
1089
|
-
|
|
1090
|
-
|
|
1221
|
+
it("honours ifNotExists, so two holders can never both win", async () => {
|
|
1222
|
+
await expect(redis.cacheSet("lock", "first", { ifNotExists: true })).resolves.toBe(true);
|
|
1223
|
+
await expect(redis.cacheSet("lock", "second", { ifNotExists: true })).resolves.toBe(false);
|
|
1224
|
+
await expect(redis.cacheGet("lock")).resolves.toBe("first");
|
|
1225
|
+
});
|
|
1226
|
+
});
|
|
1091
1227
|
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
.
|
|
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(),
|
|
1228
|
+
describe("cacheMGet", () => {
|
|
1229
|
+
it("returns one entry per key, in the order given, with null for misses", async () => {
|
|
1230
|
+
await redis.cacheSet("a", "A");
|
|
1231
|
+
await redis.cacheSet("c", "C");
|
|
1100
1232
|
|
|
1101
|
-
|
|
1233
|
+
await expect(redis.cacheMGet(["a", "missing", "c"])).resolves.toEqual(["A", null, "C"]);
|
|
1234
|
+
});
|
|
1102
1235
|
|
|
1103
|
-
|
|
1236
|
+
it("round-trips an empty key list without touching Redis", async () => {
|
|
1237
|
+
await expect(redis.cacheMGet([])).resolves.toEqual([]);
|
|
1238
|
+
});
|
|
1239
|
+
});
|
|
1104
1240
|
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1241
|
+
describe("cacheScan", () => {
|
|
1242
|
+
it("walks EVERY page, not just the first", async () => {
|
|
1243
|
+
for (const key of ["scan:1", "scan:2", "scan:3"]) await redis.cacheSet(key, "v");
|
|
1108
1244
|
|
|
1109
|
-
|
|
1245
|
+
const seen: string[] = [];
|
|
1246
|
+
for await (const key of redis.cacheScan({ match: "scan:*" })) seen.push(key);
|
|
1110
1247
|
|
|
1111
|
-
|
|
1112
|
-
|
|
1248
|
+
// The fake pages one key at a time, so stopping at the first cursor loses two keys.
|
|
1249
|
+
expect(seen.sort()).toEqual(["scan:1", "scan:2", "scan:3"]);
|
|
1250
|
+
});
|
|
1113
1251
|
});
|
|
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",
|
|
1252
|
+
`)}async function Gn(e){let t;try{t=await Hn(e,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${e} for the Upstash cache swap (boilerplate drift).`)}let r=t.replace(/\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1144
1253
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1145
|
-
`);
|
|
1254
|
+
`);if(r===t){if(t.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: found no REDIS_URL default to swap in ${e} (boilerplate drift).`)}await l(e,r)}async function Yo(e){let t=kt(e,"packages/api/tests/setup.ts"),r;try{r=await Hn(t,"utf-8")}catch{throw new Error(`pruneCacheTests: expected ${t} for the Upstash cache swap (boilerplate drift).`)}let n=r;if(n=n.replace(/\tREDIS_URL:\s*"[^"]*",?\n/g,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1146
1255
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1147
|
-
`),
|
|
1256
|
+
`),n=n.replace(/vi\.mock\("ioredis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/vi\.mock\("rate-limit-redis"[\s\S]*?\n\}\);\n\n?/,""),n=n.replace(/\t\t\tREDIS_URL:\s*"[^"]*",?\n/,` UPSTASH_REDIS_REST_URL: "https://test.upstash.io",
|
|
1148
1257
|
UPSTASH_REDIS_REST_TOKEN: "test-token",
|
|
1149
|
-
`),
|
|
1258
|
+
`),n=n.replace(/(^vi\.mock\("@repo\/runtime")/m,`vi.mock("@upstash/redis", () => {
|
|
1150
1259
|
class Redis {
|
|
1151
1260
|
get = vi.fn().mockResolvedValue(null);
|
|
1261
|
+
mget = vi.fn().mockResolvedValue([]);
|
|
1152
1262
|
set = vi.fn().mockResolvedValue("OK");
|
|
1153
1263
|
del = vi.fn().mockResolvedValue(0);
|
|
1264
|
+
incr = vi.fn().mockResolvedValue(1);
|
|
1265
|
+
decr = vi.fn().mockResolvedValue(0);
|
|
1266
|
+
expire = vi.fn().mockResolvedValue(1);
|
|
1267
|
+
pexpire = vi.fn().mockResolvedValue(1);
|
|
1268
|
+
pttl = vi.fn().mockResolvedValue(-1);
|
|
1269
|
+
scan = vi.fn().mockResolvedValue(["0", []]);
|
|
1154
1270
|
eval = vi.fn().mockResolvedValue(null);
|
|
1155
1271
|
}
|
|
1156
1272
|
return { Redis };
|
|
@@ -1158,31 +1274,25 @@ export const apiOrigin = parsedApiUrl.origin;
|
|
|
1158
1274
|
vi.mock("@upstash/lock", () => {
|
|
1159
1275
|
class Lock {
|
|
1160
1276
|
acquire = vi.fn().mockResolvedValue(true);
|
|
1161
|
-
|
|
1277
|
+
extend = vi.fn().mockResolvedValue(true);
|
|
1278
|
+
release = vi.fn().mockResolvedValue(true);
|
|
1162
1279
|
}
|
|
1163
1280
|
return { Lock };
|
|
1164
1281
|
});
|
|
1165
1282
|
|
|
1166
|
-
$1`),r
|
|
1167
|
-
`).find(
|
|
1168
|
-
`,"","configuration.mdx
|
|
1169
|
-
`)
|
|
1170
|
-
`))}async function
|
|
1171
|
-
`)}async function
|
|
1172
|
-
|
|
1173
|
-
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
|
-
|
|
1175
|
-
`,"","companion index.mdx desktop-setup section",n),await L(E(t,`docs/${r}/companion/terminal.mdx`),`## In the desktop app
|
|
1176
|
-
|
|
1177
|
-
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
|
-
|
|
1179
|
-
`,"","companion terminal.mdx desktop-panel section",n))}async function Pr(e){if(e.desktop)return;await M(E(e.projectDir,"apps/electron"),{recursive:!0});let t=E(e.projectDir,"packages/i18n/translations");for(let i of await wr(t,{withFileTypes:!0}))i.isDirectory()&&await M(E(t,i.name,"desktop.json"),{force:!0});await M(E(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of ns[e.frontend])await M(E(e.projectDir,i),{recursive:!0});await M(E(e.projectDir,"packages/utils/src/desktop-download.ts")),await M(E(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let n=E(e.projectDir,"packages/utils/package.json"),r=JSON.parse(await Ot(n,"utf-8"));if(!r.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete r.exports["./desktop-download"],await It(n,r," ","stripDesktopApp")}function ss(e){return e.desktop}async function Rr(e){ss(e)||await M(E(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as as}from"fs/promises";import{join as cs}from"path";var Tr=`on:
|
|
1283
|
+
$1`),n===r){if(r.includes("UPSTASH_REDIS_REST_URL"))return;throw new Error(`pruneCacheTests: nothing to rewrite in ${t} for the Upstash swap (boilerplate drift).`)}for(let o of['vi.mock("ioredis"','vi.mock("rate-limit-redis"',"REDIS_URL:"])if(n.includes(o))throw new Error(`pruneCacheTests: ${t} still contains ${o} after the Upstash swap (boilerplate drift).`);await l(t,n)}import{readFile as Wo}from"fs/promises";var qo=/^[ \t]*(?:\/\/|\{\/\*|\*) gsaas:[a-z0-9-]+-(?:start|end)(?: \*\/\})?[ \t]*\r?\n/gm,zo=new Set([".ts",".tsx",".vue",".mjs",".js",".jsx"]),Wn=32;function Jo(e){let t=e.lastIndexOf(".");return t>=0&&zo.has(e.slice(t))}async function Xo(e){let t=await Wo(e,"utf-8");if(!t.includes("gsaas:"))return;let r=t.replace(qo,"");r!==t&&await l(e,r)}async function qn(e){let t=await ue(e.projectDir,e.projectDir,r=>r==="node_modules"||r.startsWith("node_modules/")||r===".git"||r.startsWith(".git/"),Jo);for(let r=0;r<t.length;r+=Wn)await Promise.all(t.slice(r,r+Wn).map(Xo))}import{readdir as Xn,readFile as nt,rm as te}from"fs/promises";import{join as I}from"path";import{readFile as Jn,rm as P}from"fs/promises";import{join as E}from"path";import{readFile as Et}from"fs/promises";import{join as St}from"path";async function zn(e,t){let r=St(e,"packages/api/src/routes/internal/index.ts");await l(r,Z(await Et(r,"utf-8"),"internal router","runner",t)),await un(r);let n=St(e,"packages/api/src/ai/schedule-runner.ts");await l(n,Z(await Et(n,"utf-8"),"schedule-runner.ts","runner",t));for(let s of["packages/api/src/index.ts","packages/api/src/routes/internal/ai/chat-router.ts","packages/api/src/routes/internal/ai/schedules-router.ts","packages/api/src/ai/byok.ts","packages/api/tests/ai/schedules.test.ts","packages/api/tests/ai/schedules-runs-route.test.ts","packages/api/tests/routes/ai.test.ts"]){let a=St(e,s);await l(a,Z(await Et(a,"utf-8"),s,"runner",t))}let i=St(e,"packages/api/src/ai/settings-store.ts");await l(i,Z(await Et(i,"utf-8"),"settings-store.ts","runner",t));let o=St(e,"packages/api/tests/ai/settings-store.test.ts");await l(o,Z(await Et(o,"utf-8"),"settings-store.test.ts","runner",t))}async function Er(e){if(e.runner)return;let t=e.projectDir,r="stripRunner";await P(E(t,"packages/api/src/relay"),{recursive:!0}),await P(E(t,"packages/api/src/runner"),{recursive:!0}),await P(E(t,"packages/api/src/ai/runner-model.ts")),await P(E(t,"packages/api/src/ai/runner-routing.ts")),await P(E(t,"packages/api/tests/relay"),{recursive:!0}),await P(E(t,"packages/api/tests/runner"),{recursive:!0}),await P(E(t,"packages/api/src/routes/internal/runner.ts")),await P(E(t,"packages/api/src/routes/internal/runner-transport.ts")),await P(E(t,"packages/api/src/routes/internal/runner-limits.ts")),await P(E(t,"packages/api/tests/routes/runner.test.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-harness.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-connect.test.ts")),await P(E(t,"packages/api/tests/routes/runner-transport-events.test.ts")),await P(E(t,"packages/api/tests/ai/schedule-coalesce.test.ts")),await P(E(t,"packages/api/tests/ai/schedules-lazy-expiry.test.ts")),await P(E(t,"packages/api/tests/ai/runner-model.test.ts")),await P(E(t,"packages/api/tests/unit/runner-offline-routing.test.ts")),await P(E(t,"packages/api/tests/unit/runner-offline-interactive.test.ts")),await P(E(t,"packages/api/tests/ai/runner-chat.test.ts")),await P(E(t,"packages/api/tests/ai/web-tool-manifest.test.ts")),await P(E(t,"packages/api/tests/helpers/redis-mock.ts"));let n=E(t,"packages/api/package.json"),i=JSON.parse(await Jn(n,"utf-8"));if(!i.exports?.["./runner"])throw new Error(`${r}: expected packages/api/package.json to carry the ./runner export`);delete i.exports["./runner"],await Ze(n,i," ",r),await zn(t,r),await dn(t,"runner",["/runner"],r,"Runners"),await Y(E(t,"docs/ai.mdx"),"Runs on a paired [runner](/runner) CLI are never metered either - the user's own subscription executes them. ","","ai.mdx runner metering sentence",r),await Y(E(t,"docs/caching.mdx")," - see [per-runner request budgets](/runner/install#per-runner-request-budgets)","","caching.mdx runner budgets link",r);let o=E(t,"docs/configuration.mdx"),s="| `runner.enabled` |",a=(await Jn(o,"utf-8")).split(`
|
|
1284
|
+
`).find(p=>p.startsWith(s));if(a===void 0)throw new Error(`${r}: expected the configuration.mdx \`runner.enabled\` row (boilerplate drift).`);await Y(o,`${a}
|
|
1285
|
+
`,"","configuration.mdx runner config-table row",r)}var Zo=new Set(["ci.yml","desktop-release.yml"]),Qo=["apps/web/app/[locale]/(marketing)/download","apps/web/tests/routes/download-page.test.tsx"],ea=["cli","cli:clean","demo:bench","playground:regen","playground:test","playground:test:repo","playground:test:audit","playground:test:units","playground:test:e2e","playground:test:build","check-types:scripts","ai:parity","runner:export","runner:verify","runner:publish"];async function Zn(e){let t=I(e.projectDir,".github/workflows"),r=await Xn(t).catch(()=>[]);for(let n of r)Zo.has(n)||await te(I(t,n),{recursive:!0,force:!0})}async function ta(e,t){let r=I(e,"package.json"),n=JSON.parse(await nt(r,"utf-8"));if(!n.scripts)return;let i=!1;for(let s of t)s in n.scripts&&(delete n.scripts[s],i=!0);if(!i)return;let o=/\n([\t ]+)"/.exec(await nt(r,"utf-8"))?.[1]??" ";await l(r,JSON.stringify(n,null,o)+`
|
|
1286
|
+
`)}async function Qn(e){await ta(e.projectDir,[...ea])}async function ei(e){let t=I(e.projectDir,"package.json"),r=await nt(t,"utf-8"),n=JSON.parse(r);!n.scripts||!("dev"in n.scripts)||(n.scripts.dev=e.architecture==="separate"?"turbo run dev --continue":"turbo run dev --continue --filter=!backend",await l(t,JSON.stringify(n,null," ")+`
|
|
1287
|
+
`))}async function ti(e){let t=I(e.projectDir,"package.json"),r=JSON.parse(await nt(t,"utf-8")),n=r.scripts?.test;if(n!=="turbo run test && vitest run")throw new Error(`rewriteRootTestScript: expected the root test script to be "turbo run test && vitest run", got ${JSON.stringify(n)} (boilerplate drift).`);r.scripts.test="turbo run test",await l(t,JSON.stringify(r,null," ")+`
|
|
1288
|
+
`)}async function ri(e){e.docs||await te(I(e.projectDir,"apps/docs"),{recursive:!0})}async function ni(e){e.desktop||await te(I(e.projectDir,"docs/desktop"),{recursive:!0,force:!0}),await ra(e)}async function Gt(e,t,r,n){await l(e,Z(await nt(e,"utf-8"),t,r,n))}async function ra(e){let t=e.projectDir,r="stripUnusedDocsSilo",n=I(t,"docs/configuration.mdx"),i=e.desktop,o=e.desktop&&e.ai;e.desktop||(await Y(n,"| Desktop app + device sign-in - see [desktop app](/desktop) |","| Desktop app + device sign-in |","configuration.mdx desktop config-table link",r),await Gt(n,"configuration.mdx desktop TRUSTED_ORIGINS callout","desktop-origins-docs",r),await Y(I(t,"docs/cli/init.mdx"),"the [desktop app](/desktop), AI features","the desktop app, AI features","cli init.mdx desktop app link",r),await Y(I(t,"docs/index.mdx"),` <Card href="/desktop" title="Desktop app" description="Cross-platform desktop app with device sign-in and AI agents." />
|
|
1289
|
+
`,"","index.mdx desktop app card",r)),i||await Gt(n,"configuration.mdx desktop-AI paragraph","desktop-ai-docs",r),!o&&e.runner&&(await Gt(I(t,"docs/runner/index.mdx"),"runner index.mdx desktop-setup section","desktop-setup-docs",r),await Gt(I(t,"docs/runner/terminal.mdx"),"runner terminal.mdx desktop-panel section","desktop-terminal-docs",r))}async function ii(e){if(e.desktop)return;await te(I(e.projectDir,"apps/electron"),{recursive:!0});let t=I(e.projectDir,"packages/i18n/translations");for(let i of await Xn(t,{withFileTypes:!0}))i.isDirectory()&&await te(I(t,i.name,"desktop.json"),{force:!0});await te(I(e.projectDir,".github/workflows/desktop-release.yml"));for(let i of Qo)await te(I(e.projectDir,i),{recursive:!0});await te(I(e.projectDir,"packages/utils/src/desktop-download.ts")),await te(I(e.projectDir,"packages/utils/tests/desktop-download.test.ts"));let r=I(e.projectDir,"packages/utils/package.json"),n=JSON.parse(await nt(r,"utf-8"));if(!n.exports?.["./desktop-download"])throw new Error("stripDesktopApp: expected packages/utils/package.json to carry the ./desktop-download export");delete n.exports["./desktop-download"],await Ze(r,n," ","stripDesktopApp")}function na(e){return e.desktop}async function si(e){na(e)||await te(I(e.projectDir,"packages/agent-core"),{recursive:!0})}import{readFile as ia}from"fs/promises";import{join as sa}from"path";var oi=`on:
|
|
1180
1290
|
workflow_run:
|
|
1181
1291
|
workflows: ["Tag Release"]
|
|
1182
1292
|
branches: [main]
|
|
1183
1293
|
types: [completed]
|
|
1184
|
-
workflow_dispatch:`,
|
|
1185
|
-
workflow_dispatch:`;async function
|
|
1294
|
+
workflow_dispatch:`,oa=`on:
|
|
1295
|
+
workflow_dispatch:`;async function ai(e){if(!e.desktop)return;let t=sa(e.projectDir,".github/workflows/desktop-release.yml"),r=await ia(t,"utf8");if(!r.includes(oi))throw new Error(`Cannot configure the desktop release trigger: the expected workflow_run block was not found in ${t}. The boilerplate workflow may have drifted.`);await l(t,r.replace(oi,oa))}import{join as aa}from"path";async function ci(e){let t=ca(e);await l(aa(e.projectDir,".github/workflows/ci.yml"),t)}function ca(e){let t=e.cacheProvider==="upstash",i=` services:
|
|
1186
1296
|
postgres:
|
|
1187
1297
|
image: postgres:18-alpine
|
|
1188
1298
|
env:
|
|
@@ -1196,13 +1306,23 @@ If your product ships the [desktop app](/desktop), its **Terminal** side-panel t
|
|
|
1196
1306
|
--health-interval 10s
|
|
1197
1307
|
--health-timeout 5s
|
|
1198
1308
|
--health-retries 5
|
|
1199
|
-
|
|
1309
|
+
${t?"":` redis:
|
|
1310
|
+
image: redis:8-alpine
|
|
1311
|
+
ports:
|
|
1312
|
+
- 6379:6379
|
|
1313
|
+
options: >-
|
|
1314
|
+
--health-cmd "redis-cli ping"
|
|
1315
|
+
--health-interval 10s
|
|
1316
|
+
--health-timeout 5s
|
|
1317
|
+
--health-retries 5
|
|
1318
|
+
`}`,o="postgres://postgres:postgres@localhost:5432/saas",s=t?`
|
|
1200
1319
|
UPSTASH_REDIS_REST_URL: https://test.upstash.io
|
|
1201
|
-
UPSTASH_REDIS_REST_TOKEN: test-token
|
|
1320
|
+
UPSTASH_REDIS_REST_TOKEN: test-token`:`
|
|
1321
|
+
REDIS_URL: redis://localhost:6379`,a=(()=>{switch(e.paymentProvider){case"stripe":return`
|
|
1202
1322
|
STRIPE_SECRET_KEY: test
|
|
1203
1323
|
STRIPE_WEBHOOK_SECRET: test`;case"polar":return`
|
|
1204
1324
|
POLAR_ACCESS_TOKEN: test
|
|
1205
|
-
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let
|
|
1325
|
+
POLAR_WEBHOOK_SECRET: test`;case"none":return"";default:{let m=e.paymentProvider;throw new Error(`buildCiYaml: unhandled payment provider "${String(m)}"`)}}})();return`# Deployment is handled by the hosting platform (Vercel, Coolify, etc.)
|
|
1206
1326
|
# which auto-deploys on push. CI runs in parallel as a quality gate.
|
|
1207
1327
|
# For PR-based workflows, enable GitHub branch protection to require CI before merging.
|
|
1208
1328
|
|
|
@@ -1240,61 +1360,151 @@ ${i} env:
|
|
|
1240
1360
|
|
|
1241
1361
|
- run: pnpm lint
|
|
1242
1362
|
|
|
1243
|
-
${r?` # vue-tsc on web-nuxt OOMs on the GitHub runner's default heap once
|
|
1244
|
-
# the type graph (Nuxt + Pinia + vue-i18n + content collections)
|
|
1245
|
-
# crosses a threshold. Bump to 6 GB; ubuntu-latest has ~7 GB RAM.
|
|
1246
1363
|
- run: pnpm check-types
|
|
1247
|
-
env:
|
|
1248
|
-
NODE_OPTIONS: --max-old-space-size=6144`:" - run: pnpm check-types"}
|
|
1249
1364
|
|
|
1250
1365
|
- name: Write root env
|
|
1251
1366
|
run: echo "DATABASE_URL=${o}" > .env
|
|
1252
1367
|
|
|
1253
1368
|
- run: pnpm test
|
|
1254
|
-
`}import{readFile as
|
|
1255
|
-
`))}async function
|
|
1256
|
-
`))}async function
|
|
1257
|
-
// "
|
|
1258
|
-
export { ops } from "./${
|
|
1259
|
-
`;await
|
|
1369
|
+
`}import{readFile as li}from"fs/promises";import{existsSync as la}from"fs";import{join as Sr}from"path";var pi="@repo/database";function pa(e){return e?"pnpm -F @repo/database reset && pnpm -F @repo/database run deploy -- --push":"pnpm -F @repo/database run deploy"}function da(e){switch(e){case"fullstack":return"web";case"separate":return"backend";default:{let t=e;throw new Error(`schemaOwnerApp: unhandled architecture "${String(t)}"`)}}}async function ua(e,t,r){let n=await li(e,"utf-8"),i=JSON.parse(n),o=i.scripts?.[t];if(!o)throw new Error(`Cannot prepend to missing script "${t}" in ${e}`);o.includes(pi)||(i.scripts={...i.scripts,[t]:`${r} && ${o}`},await l(e,JSON.stringify(i,null," ")+`
|
|
1370
|
+
`))}async function ma(e,t){let r=la(e)?JSON.parse(await li(e,"utf-8")):{$schema:"https://openapi.vercel.sh/vercel.json"},n=r.buildCommand?.trim()||"pnpm build";n.includes(pi)||(r.buildCommand=`${t} && ${n}`,await l(e,JSON.stringify(r,null," ")+`
|
|
1371
|
+
`))}async function di(e){let t=pa(e.demo===!0),r=da(e.architecture),n=Sr(e.projectDir,"apps",r);switch(e.deploymentTarget){case"node":await ua(Sr(n,"package.json"),"start",t);return;case"vercel":await ma(Sr(n,"vercel.json"),t);return;default:{let i=e.deploymentTarget;throw new Error(`generateDeployScripts: unhandled deployment target "${String(i)}"`)}}}import{readFile as fa}from"fs/promises";import{existsSync as ha}from"fs";import{join as Ht}from"path";var ui=["stripe","polar"],ga=[...ui,"none"];async function mi(e){let t=Ht(e.projectDir,"packages/payments/src"),r=e.paymentProvider,i=`// Active payment provider. To switch, change the path below to
|
|
1372
|
+
// ${ga.filter(o=>o!==r).map(o=>`"./${o}/index"`).join(" or ")} (other folders are kept in place).
|
|
1373
|
+
export { ops } from "./${r}/index";
|
|
1374
|
+
`;await l(Ht(t,"providers/index.ts"),i),await l(Ht(t,"index.ts"),await ya(t,r))}async function ya(e,t){let r=Ht(e,"index.ts");if(!ha(r))throw new Error(`generatePaymentBarrel: expected ${r} to exist - did packages/payments move?`);let n=await fa(r,"utf-8"),i=ui.filter(s=>s!==t);return n.split(`
|
|
1260
1375
|
`).filter(s=>!i.some(a=>s.includes(`./providers/${a}/`))).join(`
|
|
1261
|
-
`)}import{
|
|
1262
|
-
|
|
1263
|
-
`)
|
|
1264
|
-
|
|
1265
|
-
`),await
|
|
1266
|
-
`)
|
|
1267
|
-
`);o(new Error(
|
|
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
|
-
|
|
1376
|
+
`)}import{access as va,readFile as qt,rm as Yt}from"fs/promises";import{join as W}from"path";var vi=["sentry","posthog"],Rr={sentry:"src/providers/sentry",posthog:"src/providers/posthog"},Wt={sentry:["tests/sentry-load-guard.test.ts"],posthog:["tests/posthog-load-guard.test.ts","tests/llm-analytics.test.ts"]},ba=["tests/resolution.test.ts","tests/export-isolation.test.ts"],wa=["src/providers/sentry/desktop-main.ts","src/providers/sentry/desktop-renderer.ts","src/resolve-desktop-main.ts","src/resolve-desktop-renderer.ts"],ka=["./desktop-main","./desktop-renderer"],Ea=[`vi.mock("@sentry/electron/main", sdk.factories["@sentry/electron/main"]);
|
|
1377
|
+
`,`vi.mock("@sentry/electron/renderer", sdk.factories["@sentry/electron/renderer"]);
|
|
1378
|
+
`],Sa=[' describeGate("desktop main", "electronMain", async () => {',' describeGate("desktop renderer", "electronRenderer", async () => {',' describe("the desktop main init options", () => {',' describe("the desktop renderer init", () => {'],fi=`
|
|
1379
|
+
});
|
|
1380
|
+
`,Ra=" ";async function bi(e){let t=W(e.projectDir,"packages/observability");await hi(t,"packages/observability");let r=e.observability,n=r.filter(s=>!B.includes(s));if(n.length>0)throw new Error(`observability names ${JSON.stringify(n)}, which is not a reporting provider. Every entry must be one of: ${B.join(", ")}. Shaping stops here so the project is not left half-stripped.`);for(let s of r)await hi(W(t,Rr[s]),`packages/observability/${Rr[s]}`);let i=e.desktop?[...yi,...cc]:yi,o=new Map;for(let s of i)o.set(s.file,await qt(W(t,s.file),"utf-8"));for(let s of Ca(r,e.desktop))await $a(t,s);for(let s of vi)if(!r.includes(s)){await Yt(W(t,Rr[s]),{recursive:!0,force:!0});for(let a of Wt[s])await Yt(W(t,a),{force:!0})}for(let s of ba)await Yt(W(t,s),{force:!0});e.desktop||await Aa(t,r);for(let s of i){let a=o.get(s.file);a!==void 0&&await l(W(t,s.file),Ta(a,s,r))}}async function hi(e,t){try{await va(e)}catch{throw new Error(`generateObservabilityProvider: expected ${t} to exist - did the observability package move?`)}}async function Aa(e,t){for(let i of wa)await Yt(W(e,i),{force:!0});t.includes("sentry")&&await Pa(e);let r=W(e,"package.json"),n=JSON.parse(await qt(r,"utf-8"));for(let i of ka){if(!n.exports?.[i])throw new Error(`generateObservabilityProvider: expected packages/observability/package.json to carry the ${i} export`);delete n.exports[i]}await Ze(r,n," ","generateObservabilityProvider")}async function Pa(e){let t=W(e,Wt.sentry[0]),r=await qt(t,"utf-8");r=Ar(r,Ea.map(n=>({find:n,replace:""})),Wt.sentry[0]);for(let n of Sa)r=Ia(r,n,Wt.sentry[0]);await l(t,r)}function Ia(e,t,r){let n=e.indexOf(t),i=n===-1?-1:e.indexOf(fi,n);if(n===-1||i===-1)throw new Error(`generateObservabilityProvider: ${r} no longer contains the block this strip removes - re-point the anchor. Missing: ${t.trim()}`);if(e.indexOf(t,n+t.length)!==-1)throw new Error(`generateObservabilityProvider: ${r} now opens more than one block with the same line, so this strip cannot tell which one to remove - re-point the anchor. Block: ${t.trim()}`);let o=e.slice(n+t.length,i).split(`
|
|
1381
|
+
`).find(a=>a.trim().length>0&&!a.startsWith(`${Ra} `));if(o!==void 0)throw new Error(`generateObservabilityProvider: ${r} no longer closes the block this strip removes at its own indent - re-point the anchor. Block: ${t.trim()}; first line inside it that is not part of its body: ${o.trim()}`);let s=i+fi.length;return e[s]===`
|
|
1382
|
+
`&&(s+=1),e.slice(0,n)+e.slice(s)}function Ta(e,t,r){let n=vi.filter(s=>!r.includes(s)),i=e,o=[];for(let s of n){let a=_a(i,s);i=a.source,o.push(...a.bindings)}t.dualMode!==!1&&(i=Ar(i,[{find:xa,replace:Da(r)}],t.file)),i=Ar(i,t.edits(r),t.file);for(let s of n)if(i.includes(`./providers/${s}`))throw new Error(`generateObservabilityProvider: ${t.file} still reaches providers/${s} after the strip - the boilerplate grew an import shape the drop does not know.`);for(let s of o)if(new RegExp(String.raw`\b${s}\b`).test(i))throw new Error(`generateObservabilityProvider: ${t.file} still names ${s}, whose import the strip removed - the boilerplate grew a use the pinned rewrites do not cover.`);return i}function Ar(e,t,r){let n=e;for(let i of t){if(!n.includes(i.find))throw new Error(`generateObservabilityProvider: ${r} no longer contains the text this strip rewrites - re-point the anchor. Missing: ${i.find.split(`
|
|
1383
|
+
`)[0]}`);n=n.replace(i.find,i.replace)}return n}function _a(e,t){let r=new RegExp(String.raw`^import[^;]*?from "\./providers/${t}/[^"]*";\n`,"gm"),n=[];return{source:e.replace(r,o=>(n.push(...Oa(o)),"")),bindings:n}}function Oa(e){let t=/^import\s+(?:type\s+)?([\s\S]*?)\s+from\s/.exec(e)?.[1]??"",r=[],n=/\{([\s\S]*?)\}/.exec(t);n?.[1]&&r.push(...n[1].split(",").map(s=>s.trim().replace(/^type\s+/,"")).map(s=>s.split(/\s+as\s+/).at(-1)??"").filter(s=>s.length>0));let i=t.replace(/\{[\s\S]*?\}/,"").replace(/,/g," ").trim(),o=/^\*\s+as\s+([A-Za-z_$][\w$]*)$/.exec(i);return o?.[1]?r.push(o[1]):/^[A-Za-z_$][\w$]*$/.test(i)&&r.push(i),r}var xa=" * DUAL-MODE, exactly as `packages/payments/src/providers/index.ts` does it. This repo resolves the\n * provider at RUNTIME so dev and the test suite exercise every one of them. A generated project has\n * exactly one provider, so the CLI overwrites this file with a direct re-export of it and the rest\n * become unreachable and are pruned; the generator is the observability twin of\n * `packages/cli/src/generators/payment-barrel.ts` and lands with the manifest option.";function Da(e){let t=e.map(n=>n==="sentry"?"Sentry":"PostHog").join(" and ");return`${e.length===0?` * Your project was generated with observability OFF, so no provider adapter and no reporting
|
|
1384
|
+
* SDK were shipped: this file is the whole layer, and every call is a no-op that loads nothing.`:` * Your project reports to ${t}. No other provider's adapter or SDK was generated, so
|
|
1385
|
+
* there is nothing here for a bundler to fold away and nothing for pnpm to install.`}
|
|
1386
|
+
*
|
|
1387
|
+
* To change providers, edit \`observability\` in .generatesaas/manifest.json and
|
|
1388
|
+
* run \`generatesaas update\`: re-shaping brings that provider's adapter and its dependency back. The
|
|
1389
|
+
* update stages nothing while you are already on the latest version, so the switch lands with the
|
|
1390
|
+
* next release. Pasting the other provider's credential into \`config.observability\` on its own
|
|
1391
|
+
* cannot: the adapter it would need is not here.`}var gi={source:"src/providers/sentry/browser.ts",name:"SentryBrowserInitOptions",fields:["environment: string;"]},Na={source:"src/providers/sentry/desktop-main.ts",name:"SentryDesktopMainInitOptions",fields:["environment: string;","appIsReady: boolean;"]};function Ca(e,t){return e.includes("sentry")?[]:t?[gi,Na]:[gi]}async function $a(e,t){let r=await qt(W(e,t.source),"utf-8"),n=`export interface ${t.name} {
|
|
1392
|
+
`,i=r.indexOf(n),o=r.indexOf(`
|
|
1393
|
+
}
|
|
1394
|
+
`,i);if(i===-1||o===-1)throw new Error(`generateObservabilityProvider: ${t.source} no longer exports ${t.name} - the stand-in this strip emits for a project without Sentry has nothing left to track.`);let s=r.slice(i+n.length,o).split(`
|
|
1395
|
+
`).map(a=>a.trim()).filter(a=>/^[A-Za-z_$][\w$]*\??: .+;$/.test(a));if(s.join(" ")!==t.fields.join(" "))throw new Error(`generateObservabilityProvider: ${t.name} now declares [${s.join(" ")}] but the stand-in emitted for a project without Sentry declares [${t.fields.join(" ")}] - update the stand-in so switching providers on an update cannot break a buyer's call site.`)}var La=" into every browser bundle. `tests/export-isolation.test.ts` walks the real module graph to keep\n * that from ever landing quietly.",ja=` if (resolveSentryDsn(observability, process.env.SENTRY_DSN)) ops.push(sentryServerOps);
|
|
1396
|
+
`,Ma=` if (resolvePosthogCredentials(observability, process.env.POSTHOG_API_KEY)) {
|
|
1397
|
+
ops.push(posthogServerOps);
|
|
1398
|
+
}
|
|
1399
|
+
`,Ua=` if (resolveSentryDsn(config.observability, process.env.SENTRY_DSN)) {
|
|
1400
|
+
await initSentryServer();
|
|
1401
|
+
}
|
|
1402
|
+
`,Va=` if (observability?.sentry?.dsn) ops.push(sentryBrowserOps);
|
|
1403
|
+
`,Fa=` if (observability?.posthog?.publicKey) ops.push(posthogBrowserOps);
|
|
1404
|
+
`,Ba=` if (config.observability?.sentry?.dsn) await initSentryBrowser(options);
|
|
1405
|
+
`,wi=` if (observability?.posthog?.publicKey && !observability?.sentry?.dsn) {
|
|
1406
|
+
announceMissingDesktopSdk("posthog");
|
|
1407
|
+
}
|
|
1408
|
+
`,Ka="export type BrowserReportingOptions = SentryBrowserInitOptions;",Ga=`export interface BrowserReportingOptions {
|
|
1409
|
+
/** The deployment environment reports are tagged with. */
|
|
1410
|
+
environment: string;
|
|
1411
|
+
}`,Ha=` return observability?.sentry?.dsn ? [sentryDesktopMainOps] : [];
|
|
1412
|
+
`,Ya=` if (observability?.sentry?.dsn) await initSentryDesktopMain(options);
|
|
1413
|
+
`,Wa="export type DesktopMainReportingOptions = SentryDesktopMainInitOptions;",qa=`export interface DesktopMainReportingOptions {
|
|
1414
|
+
/** The deployment environment reports are tagged with. */
|
|
1415
|
+
environment: string;
|
|
1416
|
+
/** Whether Electron's \`app\` has emitted \`ready\` yet. */
|
|
1417
|
+
appIsReady: boolean;
|
|
1418
|
+
}`,za=` return observability?.sentry?.dsn ? [sentryDesktopRendererOps] : [];
|
|
1419
|
+
`,Ja=` if (observability?.sentry?.dsn) await initSentryDesktopRenderer();
|
|
1420
|
+
`;function ki(e,t){let r=[];return e.includes("sentry")||r.push({find:t.sentry,replace:""}),e.includes("posthog")||r.push({find:t.posthog,replace:""}),r}function Xa(e){let t=[{find:La,replace:" into every browser bundle."},...ki(e,{sentry:ja,posthog:Ma})];return e.includes("sentry")||t.push({find:Ua,replace:""}),t}function Za(e){let t=[...ki(e,{sentry:Va,posthog:Fa})];return e.includes("sentry")||t.push({find:Ba,replace:""},Qa),t}var Qa={find:Ka,replace:Ga};function ec(e){let t=[];return e.includes("posthog")||t.push({find:wi,replace:""}),e.includes("sentry")||t.push({find:Ha,replace:` return [];
|
|
1421
|
+
`},{find:Ya,replace:""},{find:Wa,replace:qa}),t}function tc(e){let t=[];return e.includes("posthog")||t.push({find:wi,replace:""}),e.includes("sentry")||t.push({find:za,replace:` return [];
|
|
1422
|
+
`},{find:Ja,replace:""}),t}var rc=` if (!posthogConfigured()) return;
|
|
1423
|
+
try {
|
|
1424
|
+
const { captureAiGeneration: capture } = await import("./providers/posthog/llm");
|
|
1425
|
+
await capture(event);
|
|
1426
|
+
} catch (reportingError) {
|
|
1427
|
+
logReportingFailure("[observability] failed to report an AI generation", reportingError);
|
|
1428
|
+
}
|
|
1429
|
+
`,nc=` // No PostHog adapter was generated for this project, so there is nothing to report to.
|
|
1430
|
+
`,ic=` // No PostHog adapter was generated for this project, so there is nothing queued to drain.
|
|
1431
|
+
`,sc=`/** Whether PostHog is configured on this server, without touching the PostHog folder. */
|
|
1432
|
+
function posthogConfigured(): boolean {
|
|
1433
|
+
return Boolean(process.env.POSTHOG_API_KEY || config.observability?.posthog?.publicKey);
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
`,oc=` if (!posthogConfigured()) return;
|
|
1437
|
+
try {
|
|
1438
|
+
const { flushAiGenerations: flush } = await import("./providers/posthog/llm");
|
|
1439
|
+
await flush();
|
|
1440
|
+
} catch (reportingError) {
|
|
1441
|
+
logReportingFailure("[observability] failed to flush queued AI generations", reportingError);
|
|
1442
|
+
}
|
|
1443
|
+
`;function ac(e){return e.includes("posthog")?[]:[{find:rc,replace:nc},{find:oc,replace:ic},{find:sc,replace:""},{find:`import { logReportingFailure } from "./logger";
|
|
1444
|
+
`,replace:""},{find:`import { config } from "@repo/config";
|
|
1445
|
+
`,replace:""},{find:"export async function captureAiGeneration(event: AiGenerationEvent): Promise<void> {",replace:"export async function captureAiGeneration(_event: AiGenerationEvent): Promise<void> {"},{find:" * @param event - The call to record.",replace:" * @param _event - Ignored: no PostHog adapter was generated for this project."}]}var yi=[{file:"src/resolve-server.ts",edits:Xa},{file:"src/resolve-browser.ts",edits:Za},{file:"src/llm-analytics.ts",edits:ac,dualMode:!1}],cc=[{file:"src/resolve-desktop-main.ts",edits:ec},{file:"src/resolve-desktop-renderer.ts",edits:tc}];import{readdir as lc,readFile as pc}from"fs/promises";import{join as Ei}from"path";async function Si(e){if(e.demo)return;let t=e.appName.trim()||e.projectName,r=JSON.stringify(t).slice(1,-1),n=Ei(e.projectDir,"packages/i18n/translations"),i;try{i=await lc(n)}catch{return}for(let o of i){let s=Ei(n,o,"web.json"),a;try{a=await pc(s,"utf-8")}catch{continue}let p=a.replaceAll("GenerateSaaS",()=>r);p!==a&&await l(s,p)}}async function zt(e){let t=e.projectDir;e.demo||(await hn(t),await yn(t),await vn(t),await bn(t),e.desktop&&await gn(t)),await wn(t),await Sn(e),await An(e),await Tn(e),e.demo||await _n(e),await Nn(e),await Cn(e),await $n(e),await Ln(e),await jn(e),await Un(e),await Fn(e),await Kn(e),await Yn(e),await Zn(e),await ci(e),await Qn(e),await ei(e),await ti(e),await ri(e),await ni(e),await ii(e),await si(e),await ai(e),await Er(e),await di(e),await mi(e),await bi(e),await Si(e),await qn(e)}import{basename as Ai,join as Pi,relative as uc}from"path";import{createHash as Ri}from"crypto";import{readFile as dc}from"fs/promises";async function Jt(e){let t=await dc(e);return Ri("sha256").update(t).digest("hex")}function Pr(e){return Ri("sha256").update(e).digest("hex")}var mc=new Set(["data",H]);function fc(e){let t=e.split("/");for(let r of t)if(pr.has(r)||dr.has(r)||mc.has(r)||r.startsWith(".env")&&!r.includes("example"))return!0;return!1}function Ii(e,t){return{projectName:e.projectName??Ai(t),appName:e.appName??e.projectName??Ai(t),projectDir:t,architecture:e.architecture??"fullstack",paymentProvider:e.paymentProvider??"none",emailProvider:e.emailProvider??"smtp",multiTenancy:e.multiTenancy??!1,blog:e.blog??!1,docs:e.docs??!1,desktop:e.desktop??!1,ai:e.ai??!1,webAi:e.webAi??!0,runner:e.runner??!1,revenueSharing:e.revenueSharing??!1,credits:e.credits??!1,defaultCurrency:e.defaultCurrency??"USD",deploymentTarget:e.deploymentTarget??"node",databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",observability:e.observability??[],version:e.version,baseUrl:e.baseUrl,credentials:{},demo:!1}}function hc(e,t){return{version:e.version,initialVersion:e.version,appName:e.appName,projectName:e.projectName,frontend:Qr,architecture:e.architecture,paymentProvider:e.paymentProvider,emailProvider:e.emailProvider,multiTenancy:e.multiTenancy,blog:e.blog,docs:e.docs,desktop:e.desktop,ai:e.ai,webAi:e.webAi,runner:e.runner,credits:e.credits,revenueSharing:e.revenueSharing,defaultCurrency:e.defaultCurrency,deploymentTarget:e.deploymentTarget,databaseProvider:e.databaseProvider,cacheProvider:e.cacheProvider,observability:e.observability,...e.baseUrl?{baseUrl:e.baseUrl}:{},...t&&{licenseToken:t.token,licenseKeyHash:t.keyHash,installId:t.installId}}}async function Ti(e,t){let n=(await ue(e.projectDir,e.projectDir,fc)).sort(),i=await Promise.all(n.map(async a=>[Ne(uc(e.projectDir,a)),await Jt(a)])),o=Object.fromEntries(i),s=hc(e,t);await l(Pi(e.projectDir,ve),JSON.stringify(s,null," ")+`
|
|
1446
|
+
`),await l(Pi(e.projectDir,en),JSON.stringify(o,null," ")+`
|
|
1447
|
+
`)}import{relative as gc}from"path";async function it(e){let r=(await ue(e,e,Xe)).sort(),n=await Promise.all(r.map(async i=>[Ne(gc(e,i)),await Jt(i)]));return Object.fromEntries(n)}import{copyFile as yc,mkdir as vc,rm as bc}from"fs/promises";import{dirname as wc,join as _i,relative as kc}from"path";import{existsSync as Ec}from"fs";async function Ir(e,t){Ec(t)&&await bc(t,{recursive:!0,force:!0});let n=(await ue(e,e,Xe)).map(i=>({file:i,dest:_i(t,Ne(kc(e,i)))}));await Promise.all([...new Set(n.map(({dest:i})=>wc(i)))].map(i=>vc(i,{recursive:!0}))),await Promise.all(n.map(({file:i,dest:o})=>yc(i,o)))}async function Oi(e,t){await Ir(e,_i(t,Nt))}import{existsSync as Sc}from"fs";import{readFile as xi,readdir as Rc}from"fs/promises";import{join as re,dirname as Ac,resolve as Pc,sep as Ic}from"path";import{fileURLToPath as Tc}from"url";var _c={"claude-code":".claude/skills",cursor:".cursor/skills",codex:".agents/skills","gemini-cli":".gemini/skills",windsurf:".windsurf/skills"},$e=Object.values(_c),Tr="generatesaas-update",Di=Ac(Tc(import.meta.url));function Oc(){let e=re(Di,"skill","content");return Sc(e)?e:re(Di,"content")}async function _r(e,t,r){for(let n of $e){let i=re(e,n,Tr),o=re(i,"scripts"),s=re(i,"references");await jt(o),await jt(s),await l(re(i,"SKILL.md"),t.replaceAll("__SKILL_ROOT__",n)),await l(re(s,".gitkeep"),"");for(let[a,p]of Object.entries(r)){let m=Pc(o,a);m.startsWith(o+Ic)&&await l(m,p)}}}async function Ni(e){let t=Oc(),r=await xi(re(t,"SKILL.md"),"utf-8"),n=re(t,"scripts"),i=await Rc(n),o={};for(let s of i)s!==".gitkeep"&&(o[s]=await xi(re(n,s),"utf-8"));await _r(e,r,o)}import{execFile as xc,execFileSync as Dc}from"child_process";import{access as Ci,readFile as Nc}from"fs/promises";import{join as Or}from"path";import*as N from"@clack/prompts";function je(e){try{let t=process.platform==="win32"?"where":"which";return Dc(t,[e],{stdio:"ignore"}),!0}catch{return!1}}function Le(e,t,r,n=3e5){return new Promise((i,o)=>{xc(e,t,{cwd:r,timeout:n,maxBuffer:50*1024*1024},(s,a,p)=>{if(s){let m=String(a||"").trim(),g=[String(p||"").trim(),m].filter(Boolean).join(`
|
|
1448
|
+
`);o(new Error(g?`${s.message}
|
|
1449
|
+
${g}`:s.message))}else i()})})}async function $i(e){if(!je("pnpm"))return N.log.warn("pnpm not found. Skipping lockfile regeneration."),!1;try{return await Le("pnpm",["install","--lockfile-only","--no-frozen-lockfile","--config.minimumReleaseAge=0"],e),!0}catch(t){let r=t instanceof Error?t.message:String(t);return N.log.warn(`Lockfile regeneration failed: ${r}`),N.log.warn("Deploys using --frozen-lockfile may fail."),!1}}async function Li(e){if(!je("pnpm"))return N.log.warn("pnpm not found. Skipping dependency installation."),N.log.info("Install pnpm: https://pnpm.io/installation"),!1;let t=N.spinner();t.start("Installing dependencies (this may take a minute)...");try{return await Le("pnpm",["install","--config.minimumReleaseAge=0"],e),t.stop("Dependencies installed."),!0}catch(r){t.stop("Dependency installation failed.");let n=r instanceof Error?r.message:String(r);return N.log.warn(`pnpm install failed: ${n}`),N.log.warn("You can run it manually later."),!1}}async function ji(e){if(!je("pnpm"))return!1;let t=N.spinner();t.start("Generating baseline database migration...");try{return await Le("pnpm",["-F","@repo/database","generate"],e),t.stop("Baseline migration generated."),!0}catch(r){t.stop("Baseline migration generation failed.");let n=r instanceof Error?r.message:String(r);return N.log.warn(`Could not generate baseline migration: ${n}`),N.log.warn("Run 'pnpm -F @repo/database generate' before your first deploy."),!1}}async function Mi(e){try{return await Ci(Or(e,".git")),N.log.info("Git repository already exists, skipping init."),!0}catch{}if(!je("git"))return N.log.warn("git not found. Skipping repository initialization."),!1;let t=N.spinner();t.start("Initializing git repository...");try{return await Le("git",["init"],e),await Le("git",["add","-A"],e),await Le("git",["commit","--no-verify","-m","Initial commit from GenerateSaaS"],e),t.stop("Git repository initialized."),!0}catch{return t.stop("Git initialization failed."),N.log.warn("You can run git init manually later."),!1}}async function Ui(e){if(!je("pnpm"))return!1;try{await Ci(Or(e,".git"))}catch{return!1}try{let t=JSON.parse(await Nc(Or(e,"package.json"),"utf-8")),r=!!t.devDependencies?.["simple-git-hooks"],n=!!t["simple-git-hooks"];if(!r||!n)return!1}catch{return!1}try{return await Le("pnpm",["exec","simple-git-hooks"],e),!0}catch{return N.log.warn("Could not install git hooks. Run 'pnpm exec simple-git-hooks' manually."),!1}}import*as Me from"@clack/prompts";import q from"picocolors";function Vi(e,t){let r=He(e);t.dockerAvailable||Me.log.warn("Docker not found. Install Docker to run local services: https://docs.docker.com/get-docker/"),t.baselineMigrationMissing&&Me.log.warn("No database migration was generated (the install did not complete). Run `pnpm install` then `pnpm --filter @repo/database generate` and commit the result BEFORE deploying - deploying without it crash-loops the container.");let n=[];n.push(`cd ${e.projectDir}`),t.pnpmInstalled||n.push("pnpm install"),n.push(`pnpm infra ${q.dim(`# ${r.map(a=>Br[a].label).join(", ")}`)}`),n.push(`pnpm dev ${q.dim("# http://localhost:3000")}`),t.skippedCredentials.length>0&&(n.push(""),n.push(q.dim("Fill in remaining TODO values in .env"))),Me.note(n.join(`
|
|
1450
|
+
`),q.yellow("Start Development"));let i=[];i.push(`App ${q.cyan("http://localhost:3000")}`),e.architecture==="separate"&&i.push(`API ${q.cyan("http://localhost:3010")}`),r.includes("mailpit")&&i.push(`Mailpit ${q.cyan("http://localhost:8025")}`),r.includes("inngest")&&i.push(`Inngest ${q.cyan("http://localhost:8288")}`),Me.note(i.join(`
|
|
1451
|
+
`),q.yellow("Dev Tools"));let o=[],s=Cc(e);s.length>0&&o.push(`Set in production: ${q.dim(s.join(", "))}`),o.push("pnpm db:setup # Apply the database schema"),o.push($c(e)),Me.note(o.join(`
|
|
1452
|
+
`),q.yellow("Deployment"))}function Cc(e){let t=["DATABASE_URL","BETTER_AUTH_SECRET","INNGEST_APP_ID","INNGEST_EVENT_KEY","INNGEST_BASE_URL"];return e.cacheProvider==="upstash"?t.push("UPSTASH_REDIS_REST_URL","UPSTASH_REDIS_REST_TOKEN"):t.push("REDIS_URL"),e.paymentProvider==="stripe"?t.push("STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"):e.paymentProvider==="polar"&&t.push("POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"),e.emailProvider==="ses"?t.push("AMAZON_SES_REGION","AMAZON_SES_KEY","AMAZON_SES_SECRET"):e.emailProvider==="resend"?t.push("RESEND_API_KEY"):t.push("SMTP_HOST","SMTP_PORT"),t}function $c(e){switch(e.deploymentTarget){case"node":return"Deploy with Docker or your preferred Node.js host";case"vercel":return"vercel deploy # Deploy to Vercel"}}function st(e){let r=(e.startsWith("v")?e.slice(1):e).match(/^(\d+)\.(\d+)\.(\d+)$/);return r?[Number(r[1]),Number(r[2]),Number(r[3])]:null}function Ue(e,t){let r=st(e),n=st(t);if(!r||!n)return 0;for(let i=0;i<3;i++)if(r[i]!==n[i])return r[i]-n[i];return 0}function Xt(e,t){return e.versions.find(r=>r.version===t)?.cli}function Fi(e){return process.env.GENERATESAAS_TEMPLATE_TARBALL||process.env.GENERATESAAS_TEMPLATE_TARBALL_DIR||process.env.GENERATESAAS_OFFLINE_LICENSE==="1"?!0:st(e)===null}function Zt(e,t,r="3.0.1"){if(Fi(r))return{ok:!0};let n=Xt(e,e.latest);return!n||st(n)===null?{ok:!0}:Ue(r,n)>=0?{ok:!0}:{ok:!1,message:`Your installed generatesaas CLI (v${r}) is too old for template v${e.latest}, which needs CLI v${n} or newer. Run npx generatesaas@latest ${t} so npm fetches the current CLI. If the release happened minutes ago, npm may still be propagating it - retry shortly.`}}function Bi(e,t,r="3.0.1"){if(Fi(r))return{ok:!0};let n=Xt(e,t);return!n||st(n)===null?{ok:!0}:Ue(r,n)===0?{ok:!0}:{ok:!1,message:`Template v${t} must be scaffolded by CLI v${n} exactly (the CLI whose generators produced that release). Run npx generatesaas@${n} init.`}}import Fc from"picocolors";var Bc="a10a6fb9d7cadde32e37dad52059d17b5d2b916b08c76d8fbcc99982e9a3d87f";async function Kc(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`generatesaas-demo:${e}`)),r=[...new Uint8Array(t).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function Ki(e){e.command("init").description("Scaffold a new GenerateSaaS project").argument("[apiKey]","license key (same as --api-key)").option("-n, --name <name>","project name (lowercase, hyphens, starts with letter)").option("--app-name <name>","display name for the app").option("-l, --location <path>","project directory (default: ./{name})").addOption(new ne("--architecture <type>","fullstack or separate").choices([...Ye])).addOption(new ne("--payment <provider>","payment provider").choices([...We])).addOption(new ne("--email <provider>","email provider").choices([...qe])).option("--org","enable multi-tenancy (organizations)").option("--no-org","disable multi-tenancy").option("--blog","enable blog").option("--no-blog","disable blog").option("--docs","include the docs app (apps/docs, Fumadocs)").option("--no-docs","exclude the docs app").option("--desktop","include the desktop app (apps/electron, built with Electron)").option("--no-desktop","exclude the desktop app").option("--ai","include the AI features (chat, models, schedules, integrations); unlocks the runner").option("--no-ai","exclude the AI features").option("--web-ai","show the AI features in the web app (the default)").option("--no-web-ai","desktop-first: keep the AI features out of the web app, which is reduced to account, login and billing - the desktop app is the AI product. Requires --desktop and --ai, and cannot be combined with --runner").option("--runner","include the runner feature - your web users connect a machine that runs their own AI subscriptions for this app").option("--no-runner","exclude the backend runner feature").option("--revenue-sharing","enable revenue sharing").option("--no-revenue-sharing","disable revenue sharing").option("--credits","enable credits system").option("--no-credits","disable credits system (subscription-only)").addOption(new ne("--currency <code>","default currency for billing").choices([...oe])).addOption(new ne("--preset <preset>","infrastructure preset: serverless (Vercel + Neon + Upstash) or selfhost (Docker or Node + Postgres + Redis); --deploy/--database/--cache override it piecewise").choices([...Oe])).addOption(new ne("--deploy <target>","deployment target").choices([...ae])).addOption(new ne("--database <provider>","database provider").choices([...ce])).addOption(new ne("--cache <provider>","cache provider").choices([...le])).option("--observability <providers>",`comma-separated observability providers (${B.join(", ")}); anything unselected ships no SDK`).option("--api-key <key>","API key (skips interactive prompt)").option("--base-url <url>","public base URL (e.g. https://example.com) - bakes into canonical/og/sitemap").option("-y, --yes","accept defaults for unspecified options (non-interactive)").addOption(new ne("--demo","first-party demo build: keep sample content, mark site non-indexable - requires CI API key").hideHelp()).addOption(new ne("--no-db-migration","skip generating the baseline DB migration (internal: demos/CI/playground)").hideHelp()).action(async(t,r)=>{await Gc(t?{...r,apiKey:t}:r)})}async function Gc(e){let t=performance.now();Vr("3.0.1");let r;try{r=Jr(e)}catch(v){b.cancel(D(v)),process.exit(1)}let n=b.spinner(),i;try{i=await Je({apiKey:e.apiKey,prompt:!e.yes})}catch(v){b.cancel(D(v)),process.exit(1)}e.demo&&Pr(i)!==Bc&&(b.cancel("--demo is restricted to first-party demo deployments."),process.exit(1));let o=de(i),s,a=async()=>{s=await ke(o);let v=Zt(s,"init");if(!v.ok)throw new Error(v.message);return{latestVersion:s.latest,selectedVersion:s.latest,desktopAllowed:s.entitlements?.desktopAllowed??!0,runnerAllowed:s.entitlements?.runnerAllowed??!0}};n.start("Verifying access...");let p,m,w=!0,g=!0;try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(v){if(n.stop("Access verification failed."),v instanceof j&&v.status===401){e.yes&&(b.cancel("Invalid API key. Cannot prompt in non-interactive mode."),process.exit(1)),b.log.warning("Invalid API key."),i=await ut(),o=de(i),n.start("Verifying access...");try{({latestVersion:p,selectedVersion:m,desktopAllowed:w,runnerAllowed:g}=await a()),n.stop("Access verified."),De(i)}catch(x){n.stop("Access verification failed."),b.cancel(x instanceof j&&x.status===401?"Invalid API key.":D(x)),process.exit(1)}}else b.cancel(D(v)),process.exit(1)}b.log.success(`Latest version: ${p}`),r.desktop===!0&&!w&&(b.cancel("The desktop app is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1)),r.runner===!0&&!g&&(b.cancel("The runner is available on the Pro plan and up. Upgrade your plan at generatesaas.com."),process.exit(1));let k;e.yes?k=Xr({...r,...w?{}:{desktop:!1},...g?{}:{runner:!1}}):k=await Zr(r,{desktopAllowed:w,runnerAllowed:g});let A;n.start("Activating license...");try{let v=e.demo&&k.baseUrl?await Kc(k.baseUrl):crypto.randomUUID(),x=()=>({frontend:ar,version:m,installId:v,projectName:k.projectName,options:on(k)}),L;try{L=await cr(o,x())}catch(ge){let U=Ct(ge);if(!U?.lastAllowedVersion||!s)throw ge;n.stop("License activation failed.");let V=Bi(s,U.lastAllowedVersion);if(V.ok||(b.cancel(`${U.message} ${V.message}`),process.exit(1)),e.yes){let Ae=Xt(s,U.lastAllowedVersion);b.cancel(`${U.message} Re-run ${Ae?`npx generatesaas@${Ae} init`:"init"} without --yes to continue with v${U.lastAllowedVersion} (the last version your license covers).`),process.exit(1)}let F=await b.confirm({message:`Your update window has ended. Continue with v${U.lastAllowedVersion} (the last version your license covers)?`});(b.isCancel(F)||!F)&&(b.cancel("Setup cancelled."),process.exit(0)),m=U.lastAllowedVersion,n.start(`Activating license for v${m}...`),L=await cr(o,x())}A={token:L.token,keyHash:Pr(i),installId:L.installId??v},n.stop("License activated.")}catch(v){n.stop("License activation failed."),b.cancel(D(v)),process.exit(1)}let f=Vc(k.projectDir);if(Lc(f)&&jc(f).length>0)if(e.yes)b.log.info(`Directory ${f} is not empty. Merging (keeping existing files, overwriting conflicts).`);else{let x=await b.select({message:`Directory ${f} is not empty.`,options:[{value:"merge",label:"Merge",hint:"keep existing files, overwrite conflicts"},{value:"overwrite",label:"Overwrite",hint:"delete everything and start fresh"},{value:"cancel",label:"Cancel"}]});(b.isCancel(x)||x==="cancel")&&(b.cancel("Setup cancelled."),process.exit(0)),x==="overwrite"&&Mc(f,{recursive:!0,force:!0})}let $={...k,projectDir:f,version:m,...e.demo?{docs:!1}:{}};n.start("Downloading template...");try{await $t(o,m,f),n.stop("Template downloaded.")}catch(v){n.stop("Download failed."),b.cancel(D(v)),process.exit(1)}n.start("Generating project files...");try{if(await zt($),!e.demo){let v=await it(f);await l(Uc(f,Dt),JSON.stringify(v,null," ")+`
|
|
1453
|
+
`),await Oi(f,f)}await Ni(f),await Ti($,A),n.stop("Project files generated.")}catch(v){n.stop("Generation failed."),b.cancel(D(v)),process.exit(1)}!await $i(f)&&$.demo===!0&&(b.cancel("Lockfile regeneration failed on a demo build - refusing to ship a stale lockfile."),process.exit(1));let fe=await Li(f),X=$.demo!==!0&&e.dbMigration!==!1,he=!1;X&&fe&&(await ji(f),he=!0),await Mi(f),fe&&await Ui(f);let Ee=je("docker"),Re=ir($).map(v=>v.key).filter(v=>!$.credentials?.[v]);Vi($,{pnpmInstalled:fe,dockerAvailable:Ee,skippedCredentials:Re,baselineMigrationMissing:X&&!he}),Fr(),b.log.info(Fc.dim(`Done in ${((performance.now()-t)/1e3).toFixed(1)}s`))}import{existsSync as Cr}from"fs";import{readFile as Zi}from"fs/promises";import{join as ot,resolve as Zc}from"path";import*as y from"@clack/prompts";import C from"picocolors";import{mkdtemp as Hc,rm as Yc}from"fs/promises";import{tmpdir as Wc}from"os";import{join as qc}from"path";async function xr(e,t,r,n){let i=await Hc(qc(Wc(),"generatesaas-stage-"));try{await $t(e,t,i),await zt({...r,projectDir:i}),await Ir(i,n)}finally{await Yc(i,{recursive:!0,force:!0})}}function Rt(e){return e.paymentProvider!==void 0&&e.paymentProvider!=="none"}var Dr=[{key:"architecture",label:"Architecture",hint:"Fullstack (frontend hosts the API) or a standalone Hono backend.",category:"Infrastructure",kind:"enum",default:"fullstack",choices:Ye,adoptable:!1,impact:"structural",shapesTree:!0},{key:"deploymentTarget",label:"Deployment target",hint:"Node.js / Docker or Vercel serverless.",category:"Infrastructure",kind:"enum",default:"node",choices:ae,adoptable:!1,impact:"config",shapesTree:!0},{key:"databaseProvider",label:"Database provider",hint:"Self-hosted PostgreSQL, Neon, or Supabase.",category:"Infrastructure",kind:"enum",default:"postgres",choices:ce,adoptable:!1,impact:"config",shapesTree:!0},{key:"cacheProvider",label:"Cache provider",hint:"Self-hosted Redis or Upstash.",category:"Infrastructure",kind:"enum",default:"redis",choices:le,adoptable:!1,impact:"config",shapesTree:!0},{key:"paymentProvider",label:"Payment provider",hint:"Stripe, Polar, or none.",category:"Features",kind:"enum",default:"none",choices:We,adoptable:!1,impact:"structural",shapesTree:!0},{key:"defaultCurrency",label:"Default currency",hint:"Billing and pricing currency.",category:"Features",kind:"enum",default:"USD",choices:oe,adoptable:!1,impact:"config",shapesTree:!1},{key:"emailProvider",label:"Email provider",hint:"SMTP, Amazon SES, or Resend.",category:"Features",kind:"enum",default:"smtp",choices:qe,adoptable:!1,impact:"config",shapesTree:!1},{key:"observability",label:"Observability",hint:"Which services receive your app's errors, and on PostHog its LLM analytics. Pick any combination - anything you do not pick costs nothing, since its SDK and its adapter are never generated.",category:"Features",kind:"multiselect",default:[],choices:B,adoptable:!0,impact:"config",shapesTree:!0},{key:"multiTenancy",label:"Multi-tenancy (organizations)",hint:"Adds organizations - teams, members, and shared resources.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"blog",label:"Blog",hint:"Adds the marketing blog (content collection, list and post pages).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!1},{key:"docs",label:"Docs app",hint:"Adds the self-hosted Fumadocs documentation site (apps/docs).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"desktop",label:"Desktop app",hint:"Adds the cross-platform desktop app (apps/electron, built with Electron).",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"ai",label:"AI features",hint:"Adds the AI surface (chat, models, schedules, integrations) and unlocks the runner option. A desktop project ALWAYS ships the app's local AI stack: this option sets config.desktop.agents.enabled (the runtime gate on those screens). Off keeps config.ai.enabled false so the AI nav stays hidden - the AI packages still ship, because packages/translate depends on @repo/ai for the i18n pipeline every project uses.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0},{key:"webAi",label:"AI in the web app",hint:"Whether the WEB app shows the AI surfaces - chat, schedules, model and integration settings, and their nav entries. Off is the desktop-first shape: the desktop app is where your AI product lives and the website keeps account, billing and licensing only. The AI SERVICE is untouched either way (config.ai.enabled, the /api/ai routes and the desktop agents all stay exactly as your AI option set them), so the desktop app keeps talking to the same backend. Only meaningful with both AI features and the desktop app, and never with the runner - its pairing and device screens are part of the web AI surface.",category:"Features",kind:"boolean",default:!0,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>e.ai===!0&&e.desktop===!0&&e.runner!==!0,requiresLabel:"requires AI features and the desktop app, and is unavailable with the runner (its pairing and device screens live in the web AI surface)"},{key:"runner",label:"Runner daemon",hint:"Lets your users connect a machine that runs their own AI subscriptions (and any device-side work you add) on their hardware. They install AgentRunner, the daemon we publish and keep updated - your project ships the pairing, dispatch and Runners surface, never the daemon. Needs an always-on backend: the transport holds one connection open per paired device, which serverless (Vercel) cannot do.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"structural",shapesTree:!0,requires:e=>e.ai===!0&&e.webAi!==!1&&ie({...e,runner:!0})===void 0,requiresLabel:"requires AI features, the web AI surface, and an always-on deployment target (not Vercel)"},{key:"credits",label:"Metered credits",hint:"Adds metered usage credits on top of subscription plans.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1,requires:e=>Rt(e),requiresLabel:"requires a payment provider"},{key:"revenueSharing",label:"Revenue sharing",hint:"Opt-in MRR leaderboard with dofollow backlinks.",category:"Features",kind:"boolean",default:!1,adoptable:!0,impact:"config",shapesTree:!1}];function zc(e,t){return e[t]!==void 0}function Gi(e){return Dr.filter(t=>t.adoptable&&!zc(e,t.key)&&(t.requires?t.requires(e):!0)).map(t=>({key:t.key,label:t.label,hint:t.hint,kind:t.kind,default:typeof t.default=="function"?t.default(e):t.default,...t.choices?{choices:t.choices}:{},impact:t.impact,...t.requiresLabel?{requiresLabel:t.requiresLabel}:{}}))}function Jc(e,t){switch(e.kind){case"boolean":return typeof t=="boolean";case"enum":return typeof t=="string"&&(e.choices??[]).includes(t);case"multiselect":return Array.isArray(t)&&t.every(r=>typeof r=="string"&&(e.choices??[]).includes(r))}}function Xc(e){let t=(e.choices??[]).map(r=>JSON.stringify(r)).join(", ");switch(e.kind){case"boolean":return"true or false";case"enum":return`one of ${t}`;case"multiselect":return`an array of ${t}`}}function Hi(e){let t=[];for(let r of Dr){let n=e[r.key];n!==void 0&&(Jc(r,n)||t.push(`\`${r.key}\` is ${JSON.stringify(n)}, but it must be ${Xc(r)}.`))}return t}function Yi(e){let t={};for(let r of Dr)if(typeof r.default=="function"){if(r.requires&&!r.requires(e))continue;t[r.key]=r.default(e)}else t[r.key]=Array.isArray(r.default)?[...r.default]:r.default;return{...t,...e}}function Wi(e){return e?"ON":"OFF"}var At="packages/config/src/index.ts";function qi(e){let t=e.databaseProvider!==void 0&&e.databaseProvider!=="postgres",r=e.cacheProvider!==void 0&&e.cacheProvider!=="redis";return[...e.dockerServices??[]].filter(n=>!(n==="postgres"&&t)&&!(n==="redis"&&r)).sort()}function zi(e){return[...He({databaseProvider:e.databaseProvider??"postgres",cacheProvider:e.cacheProvider??"redis",emailProvider:e.emailProvider??"smtp"})].sort()}var Nr=[{key:"errorTracking",severity:"warn",normalize:e=>{e.errorTracking===void 0||e.observability!==void 0||(e.observability=e.errorTracking==="none"?[]:[e.errorTracking])},preserved:()=>!0,describe:()=>"Retired option `errorTracking`: it is now `observability`, an array, because a project may run more than one provider at once. Your recorded choice was migrated across automatically."},{key:"companion",severity:"warn",normalize:e=>{e.companion===void 0||e.runner!==void 0||(e.runner=e.companion)},preserved:()=>!0,describe:()=>"Retired option `companion`: it is now `runner`, because the daemon it names is AgentRunner. Your recorded choice was migrated across automatically - the feature itself is unchanged."},{key:"companionSource",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionSource\`: your project recorded a \`${String(e.companionSource)}\` daemon source. There is now one runner daemon - AgentRunner - which we publish and your users install from its own releases. Your project keeps the runner feature and its own pairing, dispatch and Runners page; it no longer holds or brands a daemon.`},{key:"companionName",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionName\`: your project recorded a branded daemon called ${e.companionName}. Buyers no longer brand or publish a daemon - your users install AgentRunner, which we maintain. Their existing install of your old daemon keeps running until they switch.`},{key:"companionRepoUrl",severity:"warn",preserved:()=>!1,describe:e=>`Retired option \`companionRepoUrl\`: your project pointed its install flow at ${e.companionRepoUrl}. It now points at AgentRunner, the one daemon we publish.`},{key:"companionLocalPath",severity:"warn",preserved:e=>(e.companionLocalPath??"").trim()==="",describe:e=>`Retired option \`companionLocalPath\`: your project recorded a local daemon checkout at ${e.companionLocalPath}. The option is gone, and so is the choice behind it - there is one runner daemon (AgentRunner) and we publish it, so nothing in your project is built from a local checkout any more.`},{key:"desktopAutoRelease",severity:"warn",applies:e=>e.desktop===!0,preserved:e=>e.desktopAutoRelease!==!0,describe:()=>"Retired option `desktopAutoRelease`: your project recorded automatic desktop releases, but the release trigger is no longer an option - cutting a release publishes signed installers from your repository and spends your Actions minutes, so it is always deliberate now. The staged `.github/workflows/desktop-release.yml` runs on `workflow_dispatch` only (the Actions tab). Add a `workflow_run` block to it if you want the CI-chained trigger back."},{key:"billingScope",severity:"ask",applies:e=>e.multiTenancy===!0,preserved:e=>e.billingScope!=="organization",describe:()=>"Retired option `billingScope`: your project recorded organization-scoped billing, and organization billing is GONE - not moved to config, removed. Money now lives only on a USER: an organization has no balance, no plan and no payment-provider customer of its own, and a workspace is funded by that organization's OWNER, whose personal balance every credit spent in it is drawn from. Payments already in flight are safe - a webhook arriving with old organization metadata is credited to that organization's owner rather than dropped - but a STORED balance is not: the `credits` and `plan` columns an organization holds them in are going away, and this update does NOT migrate them for you. MOVE every paying organization's credits and plan onto its owner BEFORE you take new checkouts, or that balance goes with the columns. How should this update proceed?"},{key:"socialProviders",severity:"warn",preserved:e=>(e.socialProviders??[]).length===0,describe:e=>`Retired option \`socialProviders\`: your project recorded ${(e.socialProviders??[]).join(", ")}, but it is now a plain config value that starts empty. Add those IDs back to \`config.auth.socialProviders\` in ${At} or their sign-in buttons stop rendering.`},{key:"mcpServer",severity:"warn",preserved:e=>e.mcpServer!==!0,describe:()=>`Retired option \`mcpServer\`: your project recorded the outward MCP server ON, but its code now ships to every project behind a config gate generated OFF. Set \`config.mcpServer.enabled\` to \`true\` in ${At} to keep your /mcp endpoint and its settings tab.`},{key:"emailTracking",severity:"ask",preserved:e=>e.emailTracking!==!1,describe:()=>`Retired option \`emailTracking\`: your project recorded email open/click tracking OFF, but it is now a plain config value generated ON. Applying this update as-is starts tracking opens and clicks for every user you mail. Put it back by setting \`config.email.tracking.enabled\` to \`false\` in ${At}. How should this update proceed?`},{key:"aiBuiltin",severity:"warn",normalize:e=>{e.aiBuiltin===void 0&&e.aiByok!==void 0&&(e.aiBuiltin=e.aiByok===!1)},applies:e=>e.ai===!0,preserved:e=>e.aiBuiltin===Rt(e),describe:e=>`Retired option \`aiBuiltin\`: your project recorded built-in AI models ${Wi(e.aiBuiltin)}, but it is now a plain config value generated ${Wi(Rt(e))} for a project ${Rt(e)?"with":"without"} a payment provider. Set \`config.ai.builtin\` to \`${String(e.aiBuiltin===!0)}\` in ${At} to keep your choice.`},{key:"aiByok",severity:"warn",applies:e=>e.ai===!0,preserved:e=>e.aiByok!==!1,describe:()=>`Retired option \`aiByok\`: your project recorded bring-your-own-key AI OFF, but it is now a plain config value generated ON. Set \`config.ai.byok\` to \`false\` in ${At} to keep it off.`},{key:"dockerServices",severity:"warn",preserved:e=>qi(e).join(",")===zi(e).join(","),describe:e=>`Retired option \`dockerServices\`: your project recorded ${qi(e).join(", ")||"no services"}, but the local Docker services are now DERIVED from your stack - postgres when you self-host Postgres, redis when you self-host Redis, mailpit on SMTP, inngest always - so an inconsistent selection is no longer possible. Your regenerated \`infra/docker-compose.yml\` will contain ${zi(e).join(", ")}. Add any extra service back by hand; the file is yours to edit.`},{key:"aiTools",severity:"warn",preserved:e=>(e.aiTools??[]).length===Gr.length,describe:e=>`Retired option \`aiTools\`: your project recorded ${(e.aiTools??[]).join(", ")||"no AI tools"}, but the \`generatesaas-update\` skill bundle now ships to every AI-tool root (${$e.join(", ")}) so it is there whichever assistant you switch to. Delete the roots you do not use - they are plain text files with no runtime path.`}],df=Nr.map(e=>e.key);function Ji(e){for(let t of Nr)t.normalize?.(e)}function Xi(e){let t=[];for(let r of Nr){if(r.normalize?.(e),e[r.key]===void 0)continue;(!r.applies||r.applies(e))&&!r.preserved(e)&&t.push({key:r.key,message:r.describe(e),severity:r.severity}),delete e[r.key]}return t}function Qi(e){e.command("update").description("Update AI skill files and stage template updates").argument("[mode]","pass 'auto' to mark the staged update for unattended apply by your AI assistant").option("--cwd <path>","project directory (default: current directory)").action(async(t,r)=>{let n=t==="auto"?"auto":void 0,i=Zc(r.cwd??process.cwd()),o=ot(i,ve),s;try{s=JSON.parse(await Zi(o,"utf-8"))}catch{y.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}s.frontend===sr&&(y.cancel(`This project was generated on the Nuxt frontend (\`.generatesaas/manifest.json\` records \`frontend: "${sr}"\`).
|
|
1454
|
+
|
|
1455
|
+
v${or} is the last release that ships a Nuxt frontend, and this CLI cannot update or migrate a Nuxt project to Next.js.
|
|
1456
|
+
|
|
1457
|
+
Your project keeps working exactly as it is - stay on v${or}, or start a fresh project on Next.js with ${C.cyan("generatesaas init")} when you are ready to move.`),process.exit(1));let a=Hi(s);a.length>0&&(y.cancel(`.generatesaas/manifest.json carries a value this CLI cannot shape a project from:
|
|
1458
|
+
|
|
1459
|
+
${a.map(f=>` - ${f}`).join(`
|
|
1460
|
+
`)}
|
|
1461
|
+
|
|
1462
|
+
Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1)),Ji(s);let p=ie(s);p&&(y.cancel(`.generatesaas/manifest.json turns \`${p.feature}\` on with \`deploymentTarget: "${p.target}"\`, which cannot run it.
|
|
1463
|
+
|
|
1464
|
+
${p.reason}
|
|
1465
|
+
|
|
1466
|
+
Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let m=rr(s);m.length>0&&(y.cancel(`.generatesaas/manifest.json records a combination this project cannot run:
|
|
1467
|
+
|
|
1468
|
+
${m.map(f=>` - ${f}`).join(`
|
|
1469
|
+
`)}
|
|
1470
|
+
|
|
1471
|
+
Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let w=qr(s);w.length>0&&(y.cancel(`.generatesaas/manifest.json turns the web AI surface off (\`webAi: false\`) in a project that cannot run without it:
|
|
1472
|
+
|
|
1473
|
+
${w.map(f=>` - ${f}`).join(`
|
|
1474
|
+
`)}
|
|
1475
|
+
|
|
1476
|
+
Correct it there, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let g;try{g=await Je()}catch(f){y.cancel(D(f)),process.exit(1)}let k=de(g),A=y.spinner();try{A.start("Verifying access...");let f;try{f=await ke(k)}catch(R){throw R instanceof j&&R.status===401?new Error("Your saved API key was rejected. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):R}let $=Zt(f,"update");if(!$.ok)throw new Error($.message);A.stop("Access verified."),De(g),A.start("Fetching latest skill files...");let J=await sn(k,f.latest);await _r(i,J.skillMd,J.scripts);let fe=$e;if(A.stop("Skills updated."),y.log.success(`Skill files installed to ${C.cyan(fe.length.toString())} locations.`),s.version===f.latest){y.log.info(`Already on the latest version (${s.version}).`);return}let X=f.entitlements;X&&(s.desktop&&!X.desktopAllowed&&(y.cancel("This project includes the desktop app, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)),s.runner&&!X.runnerAllowed&&(y.cancel("This project includes the runner, which is available on the Pro plan and up. Upgrade your plan at generatesaas.com to keep updating it."),process.exit(1)));let he=JSON.stringify(s);Wr(s),await Qc(s,zr(s),n),await tl(Xi(s),n);let Ee=Gi(s),Se=Yi(s),Re=rr(Se);Re.length>0&&(y.cancel(`.generatesaas/manifest.json is missing a provider key, and its default would create a combination this project cannot run:
|
|
1477
|
+
|
|
1478
|
+
${Re.map(R=>` - ${R}`).join(`
|
|
1479
|
+
`)}
|
|
1480
|
+
|
|
1481
|
+
Add the key to .generatesaas/manifest.json with a value your deployment target supports, then run ${C.cyan("generatesaas update")} again.`),process.exit(1));let v=JSON.stringify(Se)!==he;if(s=Se,s.licenseToken)try{let R=await an(k,{currentToken:s.licenseToken,newVersion:f.latest});s.licenseToken=R.token,R.licenseKeyHash&&(s.licenseKeyHash=R.licenseKeyHash),await l(o,JSON.stringify(s,null," ")+`
|
|
1482
|
+
`),v=!1,y.log.success("License refreshed.")}catch(R){let Pe=Ct(R);Pe&&(y.cancel(Pe.message),process.exit(1)),y.log.warn("License refresh skipped.")}v&&await l(o,JSON.stringify(s,null," ")+`
|
|
1483
|
+
`);let x=Ii(s,i),L=ot(i,tn);A.start(`Staging v${f.latest} (shaped for your config)...`),await xr(k,f.latest,x,L),A.stop("Template staged.");let{text:ge,title:U}=await il(k,f,s.version);ge&&y.note(ge,U);let V=ot(i,Dt),F=ot(i,Nt),Ae=!Cr(F),Be=!Cr(V);if(Ae){if(A.start("Building baseline template (one-time migration)..."),await xr(k,s.version,x,F),Be){let R=await it(F);await l(V,JSON.stringify(R,null," ")+`
|
|
1484
|
+
`)}if(A.stop("Baseline template stored."),!Be){let R=await sl(V,F);R>0&&y.log.warn(`Rebuilt baseline differs from the original for ${R} file(s) (the CLI's shaping evolved since this project was scaffolded). Classification still follows the committed template-hashes.json; upstream diffs for those files may include unrelated noise.`)}}else if(Be){A.start("Computing baseline template hashes...");let R=await it(F);await l(V,JSON.stringify(R,null," ")+`
|
|
1485
|
+
`),A.stop("Baseline hashes computed.")}await l(ot(i,rn),JSON.stringify({currentVersion:s.version,targetVersion:f.latest,changelog:ge,stagedAt:new Date().toISOString(),...Ee.length>0?{newOptions:Ee}:{},...n?{mode:n}:{}},null," ")+`
|
|
1486
|
+
`),y.log.info(`Update staged: ${C.cyan(s.version)} \u2192 ${C.cyan(f.latest)}`),y.log.info(`Ask your AI coding assistant to ${C.cyan("'update my GenerateSaaS project'")}.`),s.desktop===!0&&Cr(ot(i,"apps/tauri"))&&y.log.warn(`Desktop: the app moved to an Electron shell (${C.cyan("apps/electron")}). Your project still has the old Tauri shell (${C.cyan("apps/tauri")}) - remove it after verifying the Electron app builds and runs. See ${C.cyan("/desktop/updates")}.`)}catch(f){A.stop("Failed."),y.cancel(`Update failed: ${D(f)}`),process.exit(1)}})}async function Qc(e,t,r){if(t.kind==="none")return;let n=nl[t.kind];r==="auto"&&(y.cancel(`${n.message}
|
|
1487
|
+
|
|
1488
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let i=await y.select({message:n.message,options:n.options});y.isCancel(i)&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1)),i.apply(e)}var el={billingScope:[{value:"stage",label:"Stage it - I will move each organization's balance to its owner myself",hint:"move every paying organization's credits and plan onto its owner before you take new checkouts - the columns holding them are going away, and a stored balance is not migrated for you"},{value:"stop",label:"Stop, and stage nothing",hint:"migrate those balances in your database first, then re-run update - this is buyer DATA, not a config line, so nothing the update stages can put it back"}],emailTracking:[{value:"stage",label:"Stage it - I will turn tracking back off myself",hint:"set `config.email.tracking.enabled` to false in packages/config/src/index.ts before your next send"},{value:"stop",label:"Stop, and stage nothing",hint:"edit packages/config/src/index.ts first, then re-run update - a file you have edited is walked as a 3-way merge instead of being replaced"}]};async function tl(e,t){let r=[];for(let n of e){let i=n.severity==="ask"?el[n.key]:void 0;if(!i){y.log.warn(n.message);continue}r.push({notice:n,answers:i})}for(let{notice:n,answers:i}of r){t==="auto"&&(y.cancel(`${n.message}
|
|
1489
|
+
|
|
1490
|
+
This is a decision only you can make, so an unattended update will not guess it. Run ${C.cyan("generatesaas update")} without ${C.cyan("auto")} and answer it.`),process.exit(1));let o=await y.select({message:n.message,options:i});(y.isCancel(o)||o==="stop")&&(y.cancel("Update cancelled. Nothing was changed or staged."),process.exit(1))}}function rl(e){e.desktop=!1}var nl={"legacy-desktop-ai":{message:"Your desktop app runs the local AI stack through the retired desktop-AI option. Desktop AI now follows the AI option. Keep it?",options:[{value:{apply:e=>{e.ai=!0}},label:"Turn AI on, keep the desktop AI stack",hint:"also makes your website's AI surface available - keep it hidden with config.ai.enabled: false"},{value:{apply:e=>{e.ai=!1}},label:"Turn desktop AI off",hint:"your desktop app becomes a client shell: no AI, no Terminal"}]},"desktop-gains-ai":{message:"Your desktop app has no AI today, but your project has the AI option on. With the desktop-AI option retired, AI on a desktop project now ships the app's local AI stack. Keep it?",options:[{value:{apply:()=>{}},label:"Keep AI - the desktop app gains the AI stack",hint:"adds the local AI stack and the Terminal to your desktop app"},{value:{apply:e=>{e.ai=!1,e.runner=!1}},label:"Drop AI",hint:"your website's AI surface hides, and this also drops the web runner - it requires AI"},{value:{apply:rl},label:"Drop the desktop app",hint:"your website keeps its AI surface exactly as it is today"}]}};async function il(e,t,r){let n=t.latest,i=t.versions.filter(p=>Ue(p.version,r)>0&&Ue(p.version,n)<=0).sort((p,m)=>Ue(p.version,m.version)),o=async p=>{try{return await nn(e,p)}catch{return null}};if(i.length<=1)return{text:await o(n),title:`Changelog v${n}`};let s=await Promise.all(i.map(p=>o(p.version)));return{text:i.map((p,m)=>{let w=p.date?` (${p.date.slice(0,10)})`:"",g=p.breaking?" [BREAKING]":"",k=s[m]??"_No changelog available for this release._";return`# v${p.version}${w}${g}
|
|
1491
|
+
|
|
1492
|
+
${k}`}).join(`
|
|
1493
|
+
|
|
1494
|
+
`),title:`Changelog v${r} \u2192 v${n}`}}async function sl(e,t){let r=JSON.parse(await Zi(e,"utf-8")),n=await it(t),i=0;for(let[o,s]of Object.entries(r))Xe(o)||n[o]!==s&&i++;for(let o of Object.keys(n))o in r||i++;return i}import*as K from"@clack/prompts";import me from"picocolors";import{readFile as ol}from"fs/promises";import{join as al,resolve as cl}from"path";function es(e){e.command("status").description("Show project status and check for updates").option("--cwd <path>","project directory (default: current directory)").action(async t=>{let r=cl(t.cwd??process.cwd()),n=al(r,ve),i;try{i=JSON.parse(await ol(n,"utf-8"))}catch{K.cancel(".generatesaas/manifest.json not found. Run this from a GenerateSaaS project."),process.exit(1)}let o=[`Version: ${me.cyan(i.version)}`,i.deploymentTarget?`Deploy target: ${me.cyan(i.deploymentTarget)}`:null,i.databaseProvider?`Database: ${me.cyan(i.databaseProvider)}`:null,i.cacheProvider?`Cache: ${me.cyan(i.cacheProvider)}`:null].filter(Boolean).join(`
|
|
1495
|
+
`);K.note(o,me.bold("Project Status"));let s=K.spinner();s.start("Checking for updates...");try{let a=await Je(),p=de(a),w=(await ke(p)).latest;i.version===w?(s.stop("Up to date."),K.log.success(`Already on the latest version (${me.green(w)})`)):(s.stop("Update available."),K.log.warning(`Update available: ${me.yellow(i.version)} \u2192 ${me.green(w)}`),K.log.info(`Open this project in your AI coding agent and ask it to ${me.cyan("update my GenerateSaaS project")} - it fetches and applies the update for you.`))}catch(a){s.stop("Check failed."),a instanceof j&&a.status===401?K.log.warning("Invalid API key. Run `generatesaas auth` to update it, or set GENERATESAAS_API_KEY."):K.log.warning(`Could not check for updates: ${D(a)}`)}})}import{readFile as ll}from"fs/promises";import*as O from"@clack/prompts";import _ from"picocolors";function pl(){return process.env.GENERATESAAS_API_KEY??dt()}function dl(e){return{verdict:e.verdict,plan:e.license?.plan??e.domainInstalls.find(t=>t.ownerPlan)?.ownerPlan??null,mismatchDomain:e.install?.domain??null,ejectedAt:e.install?.ejectedAt??e.domainInstalls.find(t=>t.ejectedAt)?.ejectedAt??null}}function ul(e){return{verdict:e.verdict??"unknown",ejectedAt:e.ejectedAt??null}}function ml(e){switch(e.verdict){case"licensed":return O.log.success(`${_.green("LICENSED")} - resolves to an account with an active${e.plan?` ${e.plan}`:""} license.`),!0;case"ejected":return O.log.success(`${_.green("EJECTED")} - a licensed buyer opted this install out of telemetry${e.ejectedAt?` on ${e.ejectedAt.slice(0,10)}`:""}. The site is legitimate.`),!0;case"revoked":return O.log.error(`${_.red("REVOKED")} - the owning account no longer holds a plan (refund or chargeback). This deployment is no longer licensed.`),!1;case"token_domain_mismatch":return O.log.error(`${_.red("LEAKED TOKEN")} - this license belongs to a different deployment${e.mismatchDomain?` (${_.cyan(e.mismatchDomain)})`:""}, not this site. The token was copied from a licensed project.`),!1;case"no_license_history":return O.log.error(`${_.red("NO LICENSE HISTORY")} - no license has ever been associated with this site. If it runs GenerateSaaS, treat it as unlicensed.`),!1;default:return O.log.warn(`${_.yellow("UNKNOWN")} - could not cross-reference the records right now. Try again shortly.`),!1}}async function ts(e,t){let r=process.env.GENERATESAAS_API_URL??pt,n=pl();e.start("Cross-referencing license records...");try{let i=n?dl(await cn(r,n,{lkh:t.lkh,nid:t.nid,domain:t.domain})):ul(await lr(r,{token:t.token,domain:t.domain}));return e.stop(`${_.green("Checked")} - records cross-referenced`),ml(i)}catch(i){return e.stop(`${_.yellow("Skipped")} - ${D(i)}`),null}}function fl(e){let t=e.split(".");if(t.length!==3||!t[1])throw new Error("Invalid JWT format");let r=Buffer.from(t[1],"base64url").toString("utf-8");return JSON.parse(r)}function $r(e){return typeof e!="number"?"unknown":new Date(e*1e3).toISOString().split("T")[0]}function rs(e){O.note([`License ID: ${_.cyan(String(e.lid??"unknown"))}`,`Version: ${_.cyan(String(e.ver??"unknown"))}`,`Init version: ${String(e.iver??"unknown")}`,`Frontend: ${String(e.fe??"unknown")}`,`Created: ${$r(e.pat)}`,`Last updated: ${$r(e.uat)}`,`Expires: ${$r(e.exp)}`,`Install ID: ${String(e.nid??"unknown")}`].join(`
|
|
1496
|
+
`),_.yellow("License Details"))}function hl(e){let r=(/^https?:\/\//i.test(e)?e:`https://${e}`).replace(/\/+$/,"");if(r.endsWith("/api"))return[`${r}/license`];try{if(new URL(r).pathname!=="/")return[`${r}/license`]}catch{return[`${r}/license`]}return[`${r}/api/license`,`${r}/license`]}async function ns(e){let t=O.spinner(),r=null,n="no candidates";for(let s of hl(e)){t.start(`Checking ${s}...`);try{let a=await fetch(s);if(!a.ok){n=`${s} returned ${a.status}`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}let p=(await a.text()).trim();if(!p||p.split(".").length!==3){n=`${s} did not return a JWT`,t.stop(`${_.yellow("Not here")} - ${n}`);continue}r=p,t.stop(`${_.green("Found")} - license endpoint responded`);break}catch(a){n=`${s}: ${D(a)}`,t.stop(`${_.yellow("Unreachable")} - ${n}`)}}if(r===null){O.log.warn(`No license endpoint found (last: ${n}). The site may be ejected, not a GenerateSaaS app, or serving its API elsewhere.`);let s=is(e);return s?await ts(t,{domain:s})??!1:!1}let i;try{i=fl(r)}catch{return O.log.error("Could not decode JWT payload."),!1}t.start("Verifying signature...");try{let s=process.env.GENERATESAAS_API_URL??pt,a=await lr(s,{token:r});if(a.valid)t.stop(`${_.green("Valid")} - signature verified`);else return t.stop(`${_.red("Invalid")} - ${a.reason}`),!1}catch{return t.stop(`${_.yellow("Skipped")} - could not reach verification service`),O.log.warn("Signature not verified. Displaying unverified claims:"),rs(i),!1}return rs(i),await ts(t,{token:r,lkh:typeof i.lkh=="string"?i.lkh:void 0,nid:typeof i.nid=="string"?i.nid:void 0,domain:is(e)})??!0}function is(e){try{return new URL(/^https?:\/\//i.test(e)?e:`https://${e}`).hostname}catch{return}}function ss(e){e.command("verify").description("Verify a GenerateSaaS license on a deployed site").argument("[url]","URL of the site to verify (e.g. https://example.com or https://example.com/api)").option("--file <path>","file with URLs to check, one per line").action(async(t,r)=>{if(!t&&!r.file&&(O.cancel("Provide a URL or --file <path>."),process.exit(1)),r.file){let i=(await ll(r.file,"utf-8")).split(`
|
|
1497
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#"));i.length===0&&(O.cancel("No URLs found in file."),process.exit(1));let o=0;for(let s of i)await ns(s)&&o++,O.log.info("");O.log.success(`${o}/${i.length} sites verified.`)}else await ns(t)||process.exit(1)})}import{existsSync as gl,rmSync as yl}from"fs";import*as z from"@clack/prompts";function os(e){e.command("auth").description("Set or update your GenerateSaaS API key").option("--clear","remove saved API key").action(async t=>{if(t.clear){gl(pe)?(yl(pe),z.log.success("API key removed.")):z.log.info("No API key configured.");return}let r=dt();r?z.log.info(`Current API key: ****${r.slice(-4)}`):z.log.info("No API key configured.");let n=await ut(),i=de(n),o=z.spinner();o.start("Verifying API key...");try{await ke(i),o.stop("API key verified."),De(n),z.log.success("API key saved.")}catch(s){o.stop("Verification failed."),s instanceof j&&s.status===401?z.cancel("Invalid API key."):z.cancel(D(s)),process.exit(1)}})}import{existsSync as Qt,rmSync as vl,readFileSync as jr,writeFileSync as as}from"fs";import{join as Ve}from"path";import*as M from"@clack/prompts";var bl=["packages/api/src/functions/maintenance/license-heartbeat.ts","packages/api/src/lib/cron-spread.ts","packages/api/src/lib/manifest.ts","packages/api/src/routes/internal/license.ts"],wl=[{file:"packages/api/src/routes/inngest.ts",removals:[`import { licenseHeartbeatFunction } from "../functions/maintenance/license-heartbeat";
|
|
1289
1498
|
`,` licenseHeartbeatFunction,
|
|
1290
1499
|
`]},{file:"packages/api/src/routes/internal/index.ts",removals:[`import licenseRoutes from "./license";
|
|
1291
1500
|
`,` .route("/license", licenseRoutes)
|
|
1292
|
-
`]}
|
|
1501
|
+
`]},{file:"packages/api/src/routes/public/v1/health.ts",removals:[`import { manifest } from "../../../lib/manifest";
|
|
1502
|
+
`],replacements:[{from:'c.json({ status: "success" as const, version: manifest?.version })',to:'c.json({ status: "success" as const })'}]}];function kl(){return $e.map(e=>Ve(e,Tr))}function Lr(e){return Qt(e)?(vl(e,{recursive:!0}),!0):!1}function El(e,t,r=[]){if(!Qt(e))return!1;let n=jr(e,"utf-8"),i=n;for(let o of t)i=i.replace(o,"");for(let{from:o,to:s}of r)i=i.replace(o,s);return i===n?!1:(as(e,i,"utf-8"),!0)}function Sl(e){let t=Ve(e,".gitignore");if(!Qt(t))return!1;let r=jr(t,"utf-8"),n=r.split(`
|
|
1293
1503
|
`).filter(i=>!i.includes(".generatesaas")).join(`
|
|
1294
|
-
`);return r
|
|
1504
|
+
`);return n===r?!1:(as(t,n,"utf-8"),!0)}function cs(e){e.command("eject").description("Remove all GenerateSaaS ties - manifest, license, heartbeat, skills").action(async()=>{let t=process.cwd(),r=Ve(t,ve),n;try{n=JSON.parse(jr(r,"utf-8"))}catch{M.cancel("No GenerateSaaS project found in this directory."),process.exit(1)}let i=await M.text({message:'Type "eject" to confirm (this cannot be undone):',validate:a=>{if(a!=="eject")return'Type "eject" to confirm, or press Ctrl+C to cancel.'}});if(M.isCancel(i)&&(M.cancel("Eject cancelled."),process.exit(0)),n.licenseToken)try{await fetch("https://generatesaas.com/api/v1/heartbeat",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n.licenseToken}`},body:JSON.stringify({event:"eject",version:n.version,frontend:n.frontend}),signal:AbortSignal.timeout(5e3)}),M.log.info("Recorded the opt-out with generatesaas.com (final event - nothing is sent after this).")}catch{M.log.warn("Could not reach generatesaas.com to record the opt-out. Ejecting anyway.")}let o=[],s=[];for(let a of kl())Lr(Ve(t,a))&&o.push(a);for(let a of bl)Lr(Ve(t,a))&&o.push(a);Lr(Ve(t,H))&&o.push(H+"/");for(let a of wl){let p=Ve(t,a.file);El(p,a.removals,a.replacements)?s.push(a.file):Qt(p)&&M.log.warn(`Could not auto-modify ${a.file} - manually remove license/heartbeat references.`)}Sl(t)&&s.push(".gitignore");for(let a of o)M.log.info(`Deleted ${a}`);for(let a of s)M.log.info(`Modified ${a}`);M.log.success("Ejected successfully. This project is now fully standalone.")})}var Fe=new Rl().name("generatesaas").description("CLI for scaffolding and managing GenerateSaaS projects").version("3.0.1").addHelpText("after",`
|
|
1295
1505
|
Examples:
|
|
1296
1506
|
$ generatesaas init Interactive setup
|
|
1297
1507
|
$ generatesaas init -n my-app -y Quick setup with defaults
|
|
1298
1508
|
$ generatesaas status Check for updates
|
|
1299
1509
|
$ generatesaas auth Set or update API key
|
|
1300
|
-
`);
|
|
1510
|
+
`);Ki(Fe);Qi(Fe);es(Fe);ss(Fe);os(Fe);cs(Fe);Fe.parseAsync().catch(e=>{ls.cancel("An unexpected error occurred."),console.error(e),process.exit(1)});
|