nebutra 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +107 -104
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as Cn}from"./chunk-PA4CKDRJ.js";import{b as s}from"./chunk-JDX5NXDX.js";import{a as h,b as O,c as z,d as we,e as
|
|
2
|
+
import{a as Cn}from"./chunk-PA4CKDRJ.js";import{b as s}from"./chunk-JDX5NXDX.js";import{a as h,b as O,c as z,d as we,e as Le,f as he}from"./chunk-LGUMYJ4Q.js";import{a as jo}from"./chunk-IYWUY3VA.js";import{readFileSync as xd,realpathSync as No}from"fs";import{dirname as Od,join as Ad,resolve as $o}from"path";import{fileURLToPath as wn}from"url";import{Command as _d}from"commander";import{execFileSync as Ft}from"child_process";import{promises as _e}from"fs";import X from"path";import*as w from"@clack/prompts";import Ke from"picocolors";var c={SUCCESS:0,ERROR:1,INVALID_ARGS:2,NOT_FOUND:3,PERMISSION_DENIED:4,CONFLICT:5,NETWORK_ERROR:6,TIMEOUT:7,CANCELLED:8,CONFIG_ERROR:9,DRY_RUN_OK:10,INCOMPATIBLE:11,RESOURCE_EXHAUSTED:12},En={[c.SUCCESS]:"Command completed successfully",[c.ERROR]:"General or unknown error occurred",[c.INVALID_ARGS]:"Invalid arguments or options provided",[c.NOT_FOUND]:"Requested resource not found",[c.PERMISSION_DENIED]:"Permission denied or authentication required",[c.CONFLICT]:"Resource already exists",[c.NETWORK_ERROR]:"Network or external service error (may be retryable)",[c.TIMEOUT]:"Operation timed out (may be retryable)",[c.CANCELLED]:"Operation cancelled by user",[c.CONFIG_ERROR]:"Configuration error or missing configuration",[c.DRY_RUN_OK]:"Dry-run completed successfully",[c.INCOMPATIBLE]:"Incompatible version or dependency conflict",[c.RESOURCE_EXHAUSTED]:"System resource exhausted"};import{existsSync as Lo,readdirSync as On,readFileSync as Do,statSync as Fo}from"fs";import{dirname as xn,join as Lt,parse as Bo}from"path";import{fileURLToPath as Mo}from"url";var kn={"@nebutra/ui":"^0.2.2","@nebutra/tokens":"^0.1.2","@nebutra/icons":"^0.1.2","@nebutra/brand":"^0.1.2","@nebutra/design-tokens":"^0.1.2","@nebutra/design-sync":"^0.1.2","@nebutra/identity":"^0.1.2","@nebutra/tenant":"^0.1.3","@nebutra/permissions":"^0.1.3","@nebutra/vault":"^0.1.2","@nebutra/audit":"^0.1.2","@nebutra/billing":"^0.1.3","@nebutra/contracts":"^0.1.2","@nebutra/license":"^0.1.3","@nebutra/metering":"^0.1.2","@nebutra/queue":"^0.1.3","@nebutra/search":"^0.1.2","@nebutra/cache":"^0.0.3","@nebutra/notifications":"^0.1.3","@nebutra/webhooks":"^0.1.3","@nebutra/uploads":"^0.1.2","@nebutra/email":"^0.1.2","@nebutra/agents":"^1.1.2","@nebutra/mcp":"^0.1.3","@nebutra/logger":"^0.1.2"};function lt(e){return kn[e]??null}var Go=`const featureEnvKeys = {{envKeysArray}} as const;
|
|
3
3
|
|
|
4
4
|
export const platformFeature = {
|
|
5
5
|
name: "{{feature}}",
|
|
@@ -31,7 +31,7 @@ Next steps:
|
|
|
31
31
|
1. Set the required environment variables in \`{{envFile}}\`.
|
|
32
32
|
2. Wire this starter into the generated package or app surface.
|
|
33
33
|
3. Replace the placeholder helper with your production adapter.
|
|
34
|
-
`,Ko="integrations";function
|
|
34
|
+
`,Ko="integrations";function De(e,t=Ko){let n=`packages/${t}/${e}`;return[{path:`${n}/src/index.ts`,content:Go},{path:`${n}/README.md`,content:Vo}]}var qo={queue:{name:"queue",description:"Background job queue starter for Nebutra-style monorepos.",envFile:".env.local",providers:[{id:"upstash",description:"HTTP queue transport powered by Upstash QStash.",dependencies:[{name:"@upstash/qstash",version:"latest"}],env:[{key:"QSTASH_TOKEN",description:"Upstash QStash REST token"},{key:"QSTASH_CURRENT_SIGNING_KEY",description:"Upstash current signing key for webhook verification"},{key:"QSTASH_NEXT_SIGNING_KEY",description:"Upstash next signing key for webhook rotation"}]},{id:"bullmq",description:"Redis-backed worker queue powered by BullMQ.",dependencies:[{name:"bullmq",version:"latest"},{name:"ioredis",version:"latest"}],env:[{key:"REDIS_URL",description:"Redis connection string for BullMQ workers"}]}],files:[{path:"packages/integrations/queue/src/index.ts",content:`const queueEnvKeys = {{envKeysArray}} as const;
|
|
35
35
|
|
|
36
36
|
export const queueFeature = {
|
|
37
37
|
name: "queue",
|
|
@@ -95,32 +95,32 @@ Next steps:
|
|
|
95
95
|
1. Add credentials to \`{{envFile}}\`.
|
|
96
96
|
2. Point your indexing jobs at the configured provider.
|
|
97
97
|
3. Replace the placeholder helpers with production query/index code.
|
|
98
|
-
`}]},cache:{name:"cache",description:"Cache adapter starter aligned with create-sailor cache providers.",envFile:".env.local",providers:[{id:"upstash-redis",description:"Serverless Redis cache powered by Upstash.",dependencies:[{name:"@upstash/redis",version:"latest"}],env:[{key:"UPSTASH_REDIS_REST_URL",description:"Upstash Redis REST URL"}]},{id:"vercel-kv",description:"Vercel KV compatible cache adapter.",dependencies:[{name:"@vercel/kv",version:"latest"}],env:[{key:"KV_REST_API_URL",description:"Vercel KV REST API URL"}]},{id:"redis",description:"Self-hosted Redis cache adapter.",dependencies:[{name:"ioredis",version:"latest"}],env:[{key:"REDIS_URL",description:"Redis connection URL"}]},{id:"dragonfly",description:"Dragonfly Redis-compatible cache adapter.",dependencies:[{name:"ioredis",version:"latest"}],env:[{key:"DRAGONFLY_URL",description:"Dragonfly connection URL"}]}],files:
|
|
99
|
-
`)}function Jo(e,t){let n=[];if(t["21st"]){let r=t["21st"],o=r.startsWith("http")?r:`https://21st.dev/r/${r}`;n.push({type:"run-command",source:"21st",component:r,resolvedUrl:o,command:`pnpm dlx shadcn@latest add "${o}"`})}return t.v0&&n.push({type:"run-command",source:"v0",component:"v0-component",resolvedUrl:t.v0,command:`pnpm dlx shadcn@latest add "${t.v0}"`}),e.length>0&&!t["21st"]&&!t.v0&&s.warn("Local feature installs are handled separately from external registry flows."),{mode:"dry-run",planType:"external-add",cwd:process.cwd(),timestamp:new Date().toISOString(),operations:n,summary:{execute:n.length}}}function $n(e,t){if(!t||t.length===0)return[];let n=new Map;for(let r of t)n.set(`${e}:${r.name}`,r);return Array.from(n.values())}function Tn(e){let t=new Map;for(let n of e)t.has(n.key)||t.set(n.key,n);return Array.from(t.values())}function Xo(e,t){let n=t.envEntries.map(r=>r.key);return e.replaceAll("{{feature}}",t.feature).replaceAll("{{provider}}",t.provider??"default").replaceAll("{{providerDescription}}",t.providerDescription??"No provider selected").replaceAll("{{envFile}}",t.envFile).replaceAll("{{envKeysCsv}}",n.join(", ")).replaceAll("{{envKeysArray}}",JSON.stringify(n))}async function
|
|
98
|
+
`}]},cache:{name:"cache",description:"Cache adapter starter aligned with create-sailor cache providers.",envFile:".env.local",providers:[{id:"upstash-redis",description:"Serverless Redis cache powered by Upstash.",dependencies:[{name:"@upstash/redis",version:"latest"}],env:[{key:"UPSTASH_REDIS_REST_URL",description:"Upstash Redis REST URL"}]},{id:"vercel-kv",description:"Vercel KV compatible cache adapter.",dependencies:[{name:"@vercel/kv",version:"latest"}],env:[{key:"KV_REST_API_URL",description:"Vercel KV REST API URL"}]},{id:"redis",description:"Self-hosted Redis cache adapter.",dependencies:[{name:"ioredis",version:"latest"}],env:[{key:"REDIS_URL",description:"Redis connection URL"}]},{id:"dragonfly",description:"Dragonfly Redis-compatible cache adapter.",dependencies:[{name:"ioredis",version:"latest"}],env:[{key:"DRAGONFLY_URL",description:"Dragonfly connection URL"}]}],files:De("cache")},notifications:{name:"notifications",description:"Notification workflow starter for product and lifecycle messages.",envFile:".env.local",providers:[{id:"novu",description:"Novu notification workflow provider.",dependencies:[{name:"@novu/node",version:"latest"}],env:[{key:"NOVU_API_KEY",description:"Novu API key"}]},{id:"knock",description:"Knock notification workflow provider.",dependencies:[{name:"@knocklabs/node",version:"latest"}],env:[{key:"KNOCK_API_KEY",description:"Knock API key"}]},{id:"custom",description:"Custom notification adapter surface.",env:[{key:"NOTIFICATIONS_WEBHOOK_URL",description:"Custom notification webhook URL"}]}],files:De("notifications")},webhooks:{name:"webhooks",description:"Outbound webhook starter with provider-specific signing hooks.",envFile:".env.local",providers:[{id:"svix",description:"Svix-backed outbound webhook delivery.",dependencies:[{name:"svix",version:"latest"}],env:[{key:"SVIX_AUTH_TOKEN",description:"Svix authentication token"}]},{id:"custom",description:"Custom outbound webhook adapter.",env:[{key:"WEBHOOK_SIGNING_SECRET",description:"Webhook signing secret"}]}],files:De("webhooks")},cms:{name:"cms",description:"Headless CMS integration starter for marketing and docs content.",envFile:".env.local",providers:[{id:"sanity",description:"Sanity content lake client starter.",dependencies:[{name:"next-sanity",version:"latest"}],env:[{key:"NEXT_PUBLIC_SANITY_PROJECT_ID",description:"Sanity project ID"},{key:"NEXT_PUBLIC_SANITY_DATASET",description:"Sanity dataset"}]},{id:"contentful",description:"Contentful content API starter.",dependencies:[{name:"contentful",version:"latest"}],env:[{key:"CONTENTFUL_SPACE_ID",description:"Contentful space ID"},{key:"CONTENTFUL_ACCESS_TOKEN",description:"Contentful access token"}]},{id:"strapi",description:"Strapi REST client starter.",env:[{key:"STRAPI_URL",description:"Strapi base URL"},{key:"STRAPI_API_TOKEN",description:"Strapi API token"}]}],files:De("cms")},"feature-flags":{name:"feature-flags",description:"Feature flag starter for gradual rollout and runtime controls.",envFile:".env.local",providers:[{id:"vercel-flags",description:"Vercel Flags SDK starter.",dependencies:[{name:"@vercel/flags",version:"latest"}],env:[{key:"FLAGS_SECRET",description:"Feature flag signing secret"}]},{id:"growthbook",description:"GrowthBook feature flag client starter.",dependencies:[{name:"@growthbook/growthbook",version:"latest"}],env:[{key:"GROWTHBOOK_CLIENT_KEY",description:"GrowthBook client key"}]},{id:"configcat",description:"ConfigCat feature flag client starter.",dependencies:[{name:"configcat-node",version:"latest"}],env:[{key:"CONFIGCAT_SDK_KEY",description:"ConfigCat SDK key"}]}],files:De("feature-flags","platform")},captcha:{name:"captcha",description:"Captcha verification starter for abuse prevention.",envFile:".env.local",providers:[{id:"turnstile",description:"Cloudflare Turnstile verification surface.",env:[{key:"NEXT_PUBLIC_TURNSTILE_SITE_KEY",description:"Turnstile site key"},{key:"TURNSTILE_SECRET_KEY",description:"Turnstile secret key"}]},{id:"hcaptcha",description:"hCaptcha verification surface.",env:[{key:"NEXT_PUBLIC_HCAPTCHA_SITE_KEY",description:"hCaptcha site key"},{key:"HCAPTCHA_SECRET_KEY",description:"hCaptcha secret key"}]},{id:"aliyun-slide",description:"Aliyun slide captcha verification surface.",env:[{key:"ALIYUN_CAPTCHA_SCENE_ID",description:"Aliyun captcha scene ID"},{key:"ALIYUN_CAPTCHA_SECRET",description:"Aliyun captcha secret"}]}],files:De("captcha","iam")}},zo=["iam","commerce","integrations","ai","design","platform","ops"];function Yo(){let e;try{e=xn(Mo(import.meta.url))}catch{e=process.cwd()}for(;e&&e!==Bo(e).root;){try{let t=On(e);if(t.includes("pnpm-workspace.yaml")||t.includes("packages")){let n=Lt(e,"packages");if(Lo(n)&&Fo(n).isDirectory())return n}}catch{}e=xn(e)}return null}function Ho(e,t,n,r,o){let a=(t.env??[]).map(l=>({key:l,description:`${l} (declared by ${o})`})),i=lt(o)??"latest";return{name:e,description:t.summary??n.description??`${e} feature`,group:t.category??r,dependencies:[{name:o,version:i}],env:a,envFile:t.envFile??".env.local",files:[]}}var dt=null;function Wo(){if(dt)return dt;let e={},t=Yo();if(!t)return dt=e,e;for(let n of zo){let r=Lt(t,n),o;try{o=On(r)}catch{continue}for(let a of o){let i=Lt(r,a,"package.json"),l;try{l=Do(i,"utf-8")}catch{continue}let u;try{u=JSON.parse(l)}catch{continue}let m=u.nebutra,f=m?.featureId;!m||!f||!u.name||(e[f]=Ho(f,m,u,n,u.name))}}return dt=e,e}function An(){return{...Wo(),...qo}}function _n(){return Object.values(An())}async function Pn(e){return An()[e]??null}function Dt(e){return e instanceof Error&&e.message.startsWith("EXIT:")}function In(e){try{return Ft("npm",["list",e],{stdio:"pipe"}),!0}catch{return!1}}function Nn(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
99
|
+
`)}function Jo(e,t){let n=[];if(t["21st"]){let r=t["21st"],o=r.startsWith("http")?r:`https://21st.dev/r/${r}`;n.push({type:"run-command",source:"21st",component:r,resolvedUrl:o,command:`pnpm dlx shadcn@latest add "${o}"`})}return t.v0&&n.push({type:"run-command",source:"v0",component:"v0-component",resolvedUrl:t.v0,command:`pnpm dlx shadcn@latest add "${t.v0}"`}),e.length>0&&!t["21st"]&&!t.v0&&s.warn("Local feature installs are handled separately from external registry flows."),{mode:"dry-run",planType:"external-add",cwd:process.cwd(),timestamp:new Date().toISOString(),operations:n,summary:{execute:n.length}}}function $n(e,t){if(!t||t.length===0)return[];let n=new Map;for(let r of t)n.set(`${e}:${r.name}`,r);return Array.from(n.values())}function Tn(e){let t=new Map;for(let n of e)t.has(n.key)||t.set(n.key,n);return Array.from(t.values())}function Xo(e,t){let n=t.envEntries.map(r=>r.key);return e.replaceAll("{{feature}}",t.feature).replaceAll("{{provider}}",t.provider??"default").replaceAll("{{providerDescription}}",t.providerDescription??"No provider selected").replaceAll("{{envFile}}",t.envFile).replaceAll("{{envKeysCsv}}",n.join(", ")).replaceAll("{{envKeysArray}}",JSON.stringify(n))}async function ut(e){try{return await _e.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Qo(e,t){if(t)return X.join(e,t);let n=[".env.local",".env"];for(let r of n)try{return await _e.access(X.join(e,r)),X.join(e,r)}catch{}return X.join(e,".env.local")}function Zo(e){let t=new Set;for(let n of e.matchAll(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/gm))n[1]&&t.add(n[1]);return t}function es(e){return e?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n))):{}}function Un(e,t){if(!(!e.providers||e.providers.length===0))return t?e.providers.find(n=>n.id===t):e.providers[0]}async function ts(e,t,n){let r=X.join(t,"package.json"),o=await ut(r);if(!o)throw new Error(`No package.json found in ${t}. Run this command from a project root.`);let a=JSON.parse(o),i=Tn(e.flatMap(p=>[...p.descriptor.env??[],...p.provider?.env??[]])),l=await Qo(t,e[0]?.descriptor.envFile),u=await ut(l)??"",m=Zo(u),f=i.filter(p=>!m.has(p.key)),y=i.filter(p=>m.has(p.key)),E=[];for(let p of e){let B=Tn([...p.descriptor.env??[],...p.provider?.env??[]]),je={feature:p.name,provider:p.provider?.id,providerDescription:p.provider?.description,envFile:X.relative(t,l)||X.basename(l),envEntries:B};for(let Ut of p.descriptor.files??[]){let jt=X.join(t,Ut.path),Uo=X.relative(t,jt)||Ut.path,Sn=Xo(Ut.content,je),Rn=await ut(jt),it,ct;Rn===null?(it="create",ct="file missing"):Rn===Sn?(it="skip",ct="already matches registry template"):(it="conflict",ct="file exists with different content"),E.push({type:"write-file",feature:p.name,path:jt,relativePath:Uo,status:it,reason:ct,content:Sn})}}let D=$n("dependencies",e.flatMap(p=>[...p.descriptor.dependencies??[],...p.provider?.dependencies??[]])),F=$n("devDependencies",e.flatMap(p=>[...p.descriptor.devDependencies??[],...p.provider?.devDependencies??[]])),q=[];for(let p of D){let B=a.dependencies?.[p.name];q.push({section:"dependencies",name:p.name,action:B?B===p.version?"keep":"update":"add",from:B,to:p.version})}for(let p of F){let B=a.devDependencies?.[p.name];q.push({section:"devDependencies",name:p.name,action:B?B===p.version?"keep":"update":"add",from:B,to:p.version})}let ue={type:"merge-env",path:l,relativePath:X.relative(t,l)||X.basename(l),created:u.length===0,add:f,keep:y},me={type:"update-package-json",path:r,relativePath:X.relative(t,r)||"package.json",changes:q},Ae={create:E.filter(p=>p.status==="create").length,update:q.filter(p=>p.action==="add"||p.action==="update").length,append:f.length,skip:E.filter(p=>p.status==="skip").length+q.filter(p=>p.action==="keep").length+y.length,conflict:E.filter(p=>p.status==="conflict").length};return{mode:n,planType:"local-feature-install",cwd:t,timestamp:new Date().toISOString(),features:e.map(p=>({name:p.name,description:p.descriptor.description,provider:p.provider?.id,providerDescription:p.provider?.description})),operations:[...E,ue,me],summary:Ae}}function jn(e){return e.summary.create>0||e.summary.update>0||e.summary.append>0}function ns(e){return e.summary.conflict>0}async function rs(e){let t=e.operations.find(o=>o.type==="update-package-json"),n=e.operations.find(o=>o.type==="merge-env"),r=e.operations.filter(o=>o.type==="write-file");for(let o of r)o.status==="create"&&(await _e.mkdir(X.dirname(o.path),{recursive:!0}),await _e.writeFile(o.path,o.content,"utf8"));if(n&&n.add.length>0){let o=await ut(n.path)??"",a=n.add.map(u=>`# ${u.description}
|
|
100
100
|
${u.key}=`),i=o.trim().length>0?`
|
|
101
101
|
|
|
102
102
|
`:"",l=`${o.replace(/\s+$/,"")}${i}${a.join(`
|
|
103
103
|
|
|
104
104
|
`)}
|
|
105
|
-
`;await
|
|
106
|
-
`,"utf8")}}async function os(e,t,n){let r=[];for(let o of e){let a=await Pn(o);a||(s.error(`Feature '${o}' not found in the local registry.`),s.info("Use one of the supported local features or choose --21st / --v0 for external UI installs."),process.exit(c.INVALID_ARGS));let i=Un(a,t.provider);if(t.provider&&!i&&(s.error(`Provider '${t.provider}' is not supported for feature '${o}'.`),process.exit(c.INVALID_ARGS)),!i&&a.providers&&a.providers.length>0)if(n)i=a.providers[0];else{let l=await w.select({message:`Select a provider for ${o}`,options:a.providers.map(u=>({value:u.id,label:u.id,hint:u.description}))});w.isCancel(l)&&(w.log.info("Installation cancelled."),process.exit(c.CANCELLED)),i=Un(a,String(l))}r.push({name:o,descriptor:a,provider:i})}return r}function ss(e){w.log.info(
|
|
107
|
-
`)}function cs(e){return JSON.stringify(e)}function Bn(e){if(!Array.isArray(e))return
|
|
105
|
+
`;await _e.writeFile(n.path,l,"utf8")}if(t){let o=await _e.readFile(t.path,"utf8"),a=JSON.parse(o);for(let i of t.changes){if(i.action==="keep")continue;let l=i.section==="dependencies"?"dependencies":"devDependencies";a[l]={...a[l]??{},[i.name]:i.to},a[l]=es(a[l])}await _e.writeFile(t.path,`${JSON.stringify(a,null,2)}
|
|
106
|
+
`,"utf8")}}async function os(e,t,n){let r=[];for(let o of e){let a=await Pn(o);a||(s.error(`Feature '${o}' not found in the local registry.`),s.info("Use one of the supported local features or choose --21st / --v0 for external UI installs."),process.exit(c.INVALID_ARGS));let i=Un(a,t.provider);if(t.provider&&!i&&(s.error(`Provider '${t.provider}' is not supported for feature '${o}'.`),process.exit(c.INVALID_ARGS)),!i&&a.providers&&a.providers.length>0)if(n)i=a.providers[0];else{let l=await w.select({message:`Select a provider for ${o}`,options:a.providers.map(u=>({value:u.id,label:u.id,hint:u.description}))});w.isCancel(l)&&(w.log.info("Installation cancelled."),process.exit(c.CANCELLED)),i=Un(a,String(l))}r.push({name:o,descriptor:a,provider:i})}return r}function ss(e){w.log.info(Ke.yellow("Planned local install:"));for(let t of e.features)w.log.message(` - ${t.name}${t.provider?` (${t.provider})`:""}: ${t.description}`);for(let t of e.operations)if(t.type==="write-file"&&w.log.message(` - ${t.status.toUpperCase()} ${t.relativePath}`),t.type==="merge-env"&&t.add.length>0&&w.log.message(` - APPEND ${t.add.map(n=>n.key).join(", ")} to ${t.relativePath}`),t.type==="update-package-json"){let n=t.changes.filter(r=>r.action==="add"||r.action==="update");n.length>0&&w.log.message(` - UPDATE ${t.relativePath}: ${n.map(r=>`${r.name}@${r.to}`).join(", ")}`)}}async function Ln(e,t){t.dryRun||w.intro(Ke.bgCyan(Ke.black(" nebutra add ")));let n=t.yes||!process.stdin.isTTY;if(e.length===0&&!t["21st"]&&!t.v0&&(t.dryRun?s.warn("No components specified."):(w.log.warn("No components specified."),w.outro("Operation aborted.")),process.exit(c.INVALID_ARGS)),t.dryRun&&(t["21st"]||t.v0)&&(Nn(Jo(e,t)),process.exit(c.DRY_RUN_OK)),t.ifNotExists&&(t["21st"]||t.v0)&&(t["21st"]&&In(t["21st"])||t.v0&&In("shadcn-component"))&&(s.info("Component already exists. Skipping installation."),process.exit(c.SUCCESS)),t["21st"]){let r=n||await w.confirm({message:`Install 21st.dev component: ${t["21st"]}?`,initialValue:!0});(w.isCancel(r)||!r)&&(w.log.info("Installation cancelled."),process.exit(c.CANCELLED)),w.log.info(Ke.cyan(`Invoking shadcn integration for 21st.dev component: ${t["21st"]}...`));try{let o=t["21st"],a=o.startsWith("http")?o:`https://21st.dev/r/${o}`;Ft("pnpm",["dlx","shadcn@latest","add",a],{stdio:"inherit"}),s.success(`Successfully installed ${o}`),process.exit(c.SUCCESS)}catch(o){if(Dt(o))throw o;s.error(`Failed to install component: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(c.ERROR)}}if(t.v0){let r=n||await w.confirm({message:`Install v0 component from: ${t.v0}?`,initialValue:!0});(w.isCancel(r)||!r)&&(w.log.info("Installation cancelled."),process.exit(c.CANCELLED)),w.log.info(Ke.cyan(`Invoking shadcn integration for v0 URL: ${t.v0}...`));try{Ft("pnpm",["dlx","shadcn@latest","add",t.v0],{stdio:"inherit"}),s.success("Successfully installed v0 component"),process.exit(c.SUCCESS)}catch(o){if(Dt(o))throw o;s.error(`Failed to install component: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(c.ERROR)}}try{let r=await os(e,t,n),o=await ts(r,process.cwd(),t.dryRun?"dry-run":"apply");if(t.dryRun&&(Nn(o),process.exit(c.DRY_RUN_OK)),ns(o)){let i=o.operations.filter(l=>l.type==="write-file"&&l.status==="conflict").map(l=>l.relativePath);t.ifNotExists&&!jn(o)&&(s.info("Feature already appears to be installed. Skipping because --if-not-exists was set."),process.exit(c.SUCCESS)),s.error(`Refusing to overwrite existing files: ${i.join(", ")}`),process.exit(c.CONFLICT)}jn(o)||(s.info("Feature install already satisfied. No files, env keys, or dependencies needed changes."),process.exit(c.SUCCESS)),ss(o);let a=n||await w.confirm({message:`Proceed with installing ${o.features.map(i=>i.name).join(", ")}?`,initialValue:!0});(w.isCancel(a)||!a)&&(w.log.info("Installation cancelled."),process.exit(c.CANCELLED)),await rs(o),s.success(`Installed ${o.features.map(i=>i.name).join(", ")} into ${o.cwd}`),process.exit(c.SUCCESS)}catch(r){if(Dt(r))throw r;s.error(r instanceof Error?r.message:String(r)),process.exit(c.CONFIG_ERROR)}}import T from"picocolors";import{stderr as Se,stdout as Dn}from"process";import pe from"picocolors";function as(){return process.env.NEBUTRA_NON_TTY||process.env.CI||process.env.GITHUB_ACTIONS?!1:process.stderr.isTTY===!0}function Fn(e){if(e)return e;let t=process.env.NEBUTRA_OUTPUT_FORMAT;return t&&["json","table","plain"].includes(t)?t:as()?"plain":"json"}function is(e,t){if(e.length===0)return"";let n=t||Object.keys(e[0]),r={};for(let l of n){r[String(l)]=String(l).length;for(let u of e){let m=String(u[l]??"");r[String(l)]=Math.max(r[String(l)],m.length)}}let o=n.map(l=>String(l).padEnd(r[String(l)])).join(" | "),a=n.map(l=>"-".repeat(r[String(l)])).join("-+-"),i=[o,a];for(let l of e){let u=n.map(m=>String(l[m]??"").padEnd(r[String(m)])).join(" | ");i.push(u)}return i.join(`
|
|
107
|
+
`)}function cs(e){return JSON.stringify(e)}function Bn(e){if(!Array.isArray(e))return Bt(e);if(e.length===0)return"(empty)";if(typeof e[0]!="object"||e[0]===null)return Bt(e);let t=is(e);return pe.gray(t)}function Bt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):e==null?"":Array.isArray(e)?e.length===0?"(empty list)":e.every(t=>typeof t=="string"||typeof t=="number")?e.join(", "):JSON.stringify(e,null,2):typeof e=="object"?JSON.stringify(e,null,2):String(e)}function R(e,t){let n=Fn(t?.format),r=t?.stream==="stderr"?Se:Dn,o;switch(n){case"json":o=cs(e);break;case"table":o=Bn(e);break;default:o=Bt(e);break}r.write(o+`
|
|
108
108
|
`)}function A(e,t={}){let n=Fn(t.format),r;switch(n){case"json":r=JSON.stringify(e);break;case"table":r=Bn(e);break;default:r=JSON.stringify(e,null,2);break}Dn.write(r+`
|
|
109
|
-
`)}function d(e,t="info"){let n;switch(t){case"error":n=
|
|
110
|
-
`)}function k(e,t){if(!(process.env.NEBUTRA_DEBUG||process.argv.includes("--debug")))return;let r=
|
|
111
|
-
`),t&&Object.keys(t).length>0&&
|
|
112
|
-
`)}function
|
|
113
|
-
`),
|
|
114
|
-
`),
|
|
115
|
-
`),
|
|
116
|
-
`)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function
|
|
117
|
-
Tenants:`),a.tenants.forEach(i=>{let l=U(i);console.log(` ${T.blue(
|
|
118
|
-
Top tenants:`),a.topTenants.forEach((i,l)=>{let u=U(i);console.log(` ${l+1}. ${
|
|
119
|
-
Messages:`),r.messages.forEach(o=>{let a=U(o);console.log(` ${T.blue(
|
|
120
|
-
Flags:`),r.flags.forEach(o=>{let a=U(o),i=a.override!==void 0?T.yellow(String(a.override)):T.gray(String(a.default??""));console.log(` ${T.blue(
|
|
121
|
-
Audit entries:`),a.entries.forEach(i=>{let l=U(i);console.log(` ${
|
|
122
|
-
Services:`),Object.entries(r.services).forEach(([a,i])=>{let l=U(i),u=l.status==="healthy"?T.green("\u2713"):T.red("\u2717");console.log(` ${u} ${a}: ${R(l.status)}`),l.latency&&console.log(` Latency: ${R(l.latency)}ms`),l.error&&console.log(` Error: ${R(l.error)}`)}))}}function Mn(e){let t=e.command("admin").description("Platform admin operations");t.command("tenants").description("List all tenants/organizations").option("--limit <n>","Maximum number of tenants to return",o=>parseInt(o,10)).option("--offset <n>","Offset for pagination",o=>parseInt(o,10)).option("--status <status>","Filter by status (active|suspended)").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ls({limit:o.limit,offset:o.offset,status:o.status,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),t.command("tenant <id>").description("Get tenant details").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await ds(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("suspend <id>").description("Suspend a tenant (requires --yes)").option("--yes","Confirm suspension").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await us(o,{yes:a.yes||i.yes,format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("unsuspend <id>").description("Unsuspend a tenant").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await ms(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("usage").description("Cross-tenant usage report").option("--period <period>","Report period (daily|weekly|monthly)").option("--top <n>","Show top N tenants",o=>parseInt(o,10)).option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ps({period:o.period,top:o.top,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})});let n=t.command("dlq").description("Dead letter queue management");n.command("list").description("List failed messages in DLQ").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await fs({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),n.command("replay <id>").description("Replay a failed message").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await gs(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),n.command("purge").description("Purge the dead letter queue (requires --yes)").option("--yes","Confirm purge").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ys({yes:o.yes||a.yes,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})});let r=t.command("flags").description("Feature flag management");r.command("list").description("List all feature flags").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await hs({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),r.command("set <flag> <value>").description("Set a feature flag override").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a,i)=>{let l=i.optsWithGlobals?.()||i;await bs(o,a,{format:i.format||l.format,dryRun:i.dryRun||l.dryRun})}),r.command("unset <flag>").description("Remove a feature flag override").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await vs(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("audit").description("Query audit log with optional filters").option("--actor <userId>","Filter by actor/user ID").option("--action <type>","Filter by action type").option("--since <date>","Filter entries since date (ISO format)").option("--limit <n>","Maximum number of entries to return",o=>parseInt(o,10)).option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ws({actor:o.actor,action:o.action,since:o.since,limit:o.limit,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),t.command("health").description("Platform-wide health check").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await Rs({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})})}import{existsSync as Cs,readFileSync as Es,writeFileSync as ks}from"fs";import{resolve as Vt}from"path";var b={pm:["npm","pnpm","yarn","bun"],region:["global","cn","hybrid"],orm:["prisma","drizzle","none"],db:["postgres","mysql","sqlite","none"],auth:["clerk","betterauth","none"],socialLogin:["wechat","qq","dingtalk","workweixin","feishu","weibo"],payment:["stripe","lemon","wechat","alipay","none"],ai:["openai","anthropic","deepseek","xai","moonshot","google","mistral","cohere","perplexity","ai21","upstage","siliconflow","volcengine-ark","bailian","zhipu","baichuan","minimax","stepfun","sensetime","tencent","lingyi","openrouter","vercel-gateway","litellm","portkey","aws-bedrock","azure-openai","gcp-vertex","groq","fireworks","together","huggingface","replicate","lepton","anyscale","octoai","deepinfra","novita","custom","none"],deploy:["vercel","railway","cloudflare","selfhost","none"],docs:["fumadocs","mintlify","docusaurus","nextra","vitepress","none"],email:["resend","postmark","ses","aliyun-dm","tencent-ses","netease","none"],storage:["r2","s3","supabase-storage","aliyun-oss","tencent-cos","qiniu","none"],monitoring:["sentry","datadog","bugsnag","aliyun-arms","tingyun","none"],analytics:["posthog","plausible","umami","mixpanel","baidu","sensors","growingio","none"],sms:["twilio","messagebird","plivo","aliyun-sms","tencent-sms","yunpian","none"],queue:["qstash","bullmq","upstash","sqs","none"],search:["meilisearch","typesense","algolia","pgvector","none"],cache:["upstash-redis","vercel-kv","redis","dragonfly","none"],notifications:["novu","knock","custom","none"],webhooks:["svix","custom","none"],cms:["sanity","contentful","strapi","none"],featureFlags:["vercel-flags","growthbook","configcat","none"],captcha:["turnstile","hcaptcha","aliyun-slide","none"],mcp:["on","off"],metering:["auto","on","off"],billingMode:["usage","seat","credits"],idp:["clerk","oauth-server"]},Ss=[{flags:"-p, --pm <id>",description:"Package manager: npm, pnpm, yarn, or bun"},{flags:"--region <id>",description:"Target region: global, cn, or hybrid"},{flags:"--orm <id>",description:"ORM: prisma, drizzle, or none"},{flags:"--db <id>",description:"Database: postgres, mysql, sqlite, or none"},{flags:"--auth <id>",description:"Auth provider: clerk, betterauth, or none"},{flags:"--social-login <ids>",description:"Comma-separated CN social login providers"},{flags:"--payment <id>",description:"Payment provider: stripe, lemon, wechat, alipay, or none"},{flags:"--ai <ids>",description:"Expert/non-interactive AI provider seed ids"},{flags:"--deploy <target>",description:"Deploy target: vercel, railway, cloudflare, selfhost, or none"},{flags:"--docs <id>",description:"Docs framework: fumadocs, mintlify, docusaurus, nextra, vitepress, or none"},{flags:"--email <id>",description:"Transactional email provider"},{flags:"--storage <id>",description:"Object storage provider"},{flags:"--monitoring <id>",description:"Monitoring provider"},{flags:"--analytics <id>",description:"Analytics provider"},{flags:"--sms <id>",description:"SMS provider"},{flags:"--queue <id>",description:"Queue provider"},{flags:"--search <id>",description:"Search provider"},{flags:"--cache <id>",description:"Cache provider"},{flags:"--notifications <id>",description:"Notifications provider"},{flags:"--webhooks <id>",description:"Outbound webhooks provider"},{flags:"--cms <id>",description:"Headless CMS provider"},{flags:"--feature-flags <id>",description:"Feature flag provider"},{flags:"--captcha <id>",description:"Captcha provider"},{flags:"--mcp <mode>",description:"MCP server mode: on or off"},{flags:"--metering <mode>",description:"Metering mode: auto, on, or off"},{flags:"--billing-mode <mode>",description:"Billing mode: usage, seat, or credits"},{flags:"--idp <id>",description:"Identity provider: clerk or oauth-server"},{flags:"--i18n",description:"Enable i18n",default:!0},{flags:"--no-i18n",description:"Disable i18n"},{flags:"--no-install",description:"Skip package install"},{flags:"--no-git",description:"Skip git init"},{flags:"--dry-run",description:"Preview project scaffolding without creating files (exit code 10)"},{flags:"--json",description:"Emit machine-readable JSON events"},{flags:"--yes",description:"Skip all interactive prompts (Agent mode)"}],pe={name:"nebutra",description:"Governance-first CLI for Nebutra Sailor scaffolding, registry-backed features, and platform operations",usage:"nebutra [command] [options]",options:[{flags:"--format <type>",description:"Output format: json, table, plain"},{flags:"--yes, --no-interactive",description:"Skip all interactive prompts (Agent mode)"},{flags:"--no-color",description:"Disable colored output"},{flags:"--verbose",description:"Enable verbose output"},{flags:"--quiet",description:"Suppress non-essential output"}],subcommands:[{name:"init",description:"Initialize a Nebutra project and create nebutra.config.json",usage:"nebutra init [options]",options:[{flags:"--dry-run",description:"Preview changes without writing files (exits with code 10)"},{flags:"--yes",description:"Skip all interactive prompts (Agent mode)"},{flags:"--if-not-exists",description:"Skip initialization if nebutra.config.json already exists"}],arguments:[],examples:[{command:"nebutra init",description:"Initialize Nebutra configuration in the current directory"},{command:"nebutra init --dry-run",description:"Preview initialization changes without writing files"},{command:"nebutra init --yes --if-not-exists",description:"Initialize without prompts, skip if already configured"}]},{name:"add",description:"Add a registry-backed platform feature or external UI component",usage:"nebutra add [components...] [options]",arguments:[{name:"components",description:"Local feature names to install from the Nebutra registry",required:!1,variadic:!0}],options:[{flags:"--21st <id>",description:"Fetch and install a component from 21st.dev registry"},{flags:"--v0 <url>",description:"Fetch and install a component from v0.dev by URL"},{flags:"--dry-run",description:"Preview what would be installed without making changes (exit code 10)"},{flags:"--yes",description:"Skip all interactive prompts and use defaults (Agent mode)"},{flags:"--if-not-exists",description:"Skip installation if component already exists"}],examples:[{command:"nebutra add cache --provider upstash-redis --yes",description:"Install the local cache feature with the Upstash Redis provider"},{command:"nebutra add --21st button-01",description:"Add a component from 21st.dev (shadcn-style registry)"},{command:'nebutra add --v0 "https://v0.dev/r/..." --dry-run',description:"Preview adding a component from v0.dev without making changes"},{command:"nebutra add webhooks --provider svix --yes --if-not-exists",description:"Install webhooks without prompts, skip if already configured"}]},{name:"create",description:"Scaffold a topology-first Nebutra Sailor project with governed defaults",usage:"nebutra create [dir] [options]",arguments:[{name:"dir",description:"Target directory for the new project (optional, will prompt if not provided)",required:!1}],options:Ss,examples:[{command:"nebutra create my-saas-app --region=hybrid --ai=openai,deepseek",description:"Create a topology-first project with hybrid defaults and selected AI providers"},{command:"nebutra create my-cn-app --region=cn --payment=wechat --storage=aliyun-oss --deploy=selfhost -y",description:"Create a non-interactive China-ready scaffold"},{command:"nebutra create my-app --storage=supabase-storage --dry-run --json",description:"Preview scaffolding with structured JSON output"}]},{name:"mcp",description:"Start the Nebutra MCP server for AI agents and editors",usage:"nebutra mcp [options]",arguments:[],options:[{flags:"--stdio",description:"Use stdio transport for communication (default: enabled)",default:!0},{flags:"--verbose",description:"Enable verbose logging for MCP server"}],examples:[{command:"nebutra mcp",description:"Start the MCP server for AI-powered project context integration"},{command:"nebutra mcp --verbose",description:"Start the MCP server with detailed logging output"}]},{name:"schema",description:"Show command schema and argument documentation (Agent-friendly JSON output)",usage:"nebutra schema [command] [options]",arguments:[{name:"command",description:"Command name to show schema for (e.g., init, add, create)",required:!1}],options:[{flags:"--all",description:"Show full schema for all commands as JSON",default:!1},{flags:"--list",description:"List all available command names",default:!1},{flags:"--exit-codes",description:"Show exit codes reference",default:!1}],examples:[{command:"nebutra schema --all",description:"Show complete JSON of all commands, args, options, value domains"},{command:"nebutra schema init",description:"Show schema for init command (arguments, options, defaults, examples)"},{command:"nebutra schema add",description:"Show schema for add command with enum values"},{command:"nebutra schema --list",description:"List just the command names (quick discovery)"},{command:"nebutra schema --exit-codes",description:"Show exit codes reference for all possible exit codes"}]},{name:"brand",description:"Manage governed brand tokens, palettes, and visual system outputs",usage:"nebutra brand [subcommand]",examples:[{command:"nebutra brand palette --primary=#0047FF",description:"Generate a token-aligned blue palette"}]},{name:"i18n",description:"Manage localization files and multilingual product copy",usage:"nebutra i18n [subcommand]"},{name:"infra",description:"Manage local infrastructure services for Nebutra development",usage:"nebutra infra [subcommand]",examples:[{command:"nebutra infra up --lite",description:"Start lightweight local infrastructure"}]},{name:"env",description:"Validate and manage environment variables across apps and packages",usage:"nebutra env [subcommand]"},{name:"license",description:"Manage Nebutra Sailor commercial license activation and status",usage:"nebutra license [subcommand]",arguments:[],options:[],subcommands:[{name:"activate",description:"Activate a commercial license key for local development",usage:"nebutra license activate <key>",arguments:[{name:"key",description:"Your Nebutra Sailor commercial license key",required:!0}],options:[{flags:"--quiet",description:"Suppress output"}],examples:[{command:"nebutra license activate liz_1234567890",description:"Activate your license key globally"}]},{name:"status",description:"Check the locally configured license status",usage:"nebutra license status",arguments:[],options:[{flags:"--quiet",description:"Suppress output"}],examples:[{command:"nebutra license status",description:"Check if you have an active license"}]}]},{name:"ai",description:"Configure AI providers, gateway routing, and agent-ready defaults",usage:"nebutra ai [subcommand]"},{name:"auth",description:"Configure authentication providers and tenant access defaults",usage:"nebutra auth [subcommand]"},{name:"billing",description:"Manage billing providers, subscriptions, usage, and return flows",usage:"nebutra billing [subcommand]"},{name:"stats",description:"Show monorepo statistics, health signals, and platform inventory",usage:"nebutra stats [options]"},{name:"db",description:"Manage database schema, migrations, seeds, and generated clients",usage:"nebutra db [subcommand]"},{name:"generate",description:"Generate apps, modules, API surfaces, and typed project artifacts",usage:"nebutra generate [type] [name]"},{name:"dev",description:"Start development workflows for selected Nebutra apps or presets",usage:"nebutra dev [options]"},{name:"build",description:"Run build workflows through the Nebutra CLI",usage:"nebutra build [options]"},{name:"lint",description:"Run lint workflows through the Nebutra CLI",usage:"nebutra lint [options]"},{name:"typecheck",description:"Run TypeScript checks through the Nebutra CLI",usage:"nebutra typecheck [options]"},{name:"test",description:"Run unit, architecture, and E2E verification workflows",usage:"nebutra test [scope]"},{name:"workflow",description:"Initialize and inspect workflow runtime adapters",usage:"nebutra workflow [subcommand]"},{name:"backend",description:"Manage backend runtime service workflows",usage:"nebutra backend [subcommand]"},{name:"e2e",description:"Run browser end-to-end verification suites",usage:"nebutra e2e [suite]"},{name:"theme",description:"Inspect registry-backed Nebutra themes and governance metadata",usage:"nebutra theme [subcommand]"},{name:"ui",description:"Search, inspect, validate, and plan migrations for @nebutra/ui components",usage:"nebutra ui [subcommand]"},{name:"admin",description:"Operate tenant, platform health, and administrative workflows",usage:"nebutra admin [subcommand]"},{name:"community",description:"Inspect community health, showcases, and external adoption signals",usage:"nebutra community [subcommand]"},{name:"growth",description:"Analyze product growth, funnels, retention, and lifecycle signals",usage:"nebutra growth [subcommand]"},{name:"ecosystem",description:"Manage template marketplace, ideas, project showcase, and ecosystem sync",usage:"nebutra ecosystem [subcommand]"},{name:"services",description:"Inspect and manage microservice health, logs, scaling, and rollouts",usage:"nebutra services [subcommand]"},{name:"search",description:"Manage search indexes, reindexing, and search diagnostics",usage:"nebutra search [subcommand]"},{name:"secrets",description:"Manage encrypted tenant and platform secrets",usage:"nebutra secrets [subcommand]"},{name:"completions",description:"Generate shell completions for the current Nebutra command surface",usage:"nebutra completions [shell]",arguments:[{name:"shell",description:"Shell to generate completions for: bash, zsh, fish, or install",required:!1}]},{name:"logout",description:"Clear local Nebutra CLI session state",usage:"nebutra logout"},{name:"upgrade",description:"Upgrade local Nebutra CLI tooling",usage:"nebutra upgrade"},{name:"link",description:"Link a local project to Nebutra platform metadata",usage:"nebutra link"},{name:"unlink",description:"Unlink local Nebutra project metadata",usage:"nebutra unlink"},{name:"doctor",description:"Check local project setup and common Nebutra configuration issues",usage:"nebutra doctor"}]};var Vn="nebutra.config.json",xs=b.ai.filter(e=>e!=="none"),Gn={"aws-bedrock":["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"],"azure-openai":["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],"gcp-vertex":["GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"],"vercel-gateway":["AI_GATEWAY_API_KEY"],"volcengine-ark":["VOLCENGINE_ARK_API_KEY"],bailian:["DASHSCOPE_API_KEY"],litellm:["LITELLM_API_KEY","LITELLM_BASE_URL"],portkey:["PORTKEY_API_KEY"],custom:["AI_CUSTOM_API_KEY","AI_CUSTOM_BASE_URL"]};function ce(e,t,n){if(t==="json"){let r={command:n||"ai",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function Os(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function As(e){return Gn[e]?Gn[e]:[`${e.replace(/-/g,"_").toUpperCase()}_API_KEY`]}function gt(){return Object.fromEntries(xs.map(e=>[e,{id:e,name:Os(e),envVars:As(e)}]))}function fe(){return Vt(process.cwd(),Vn)}function Ie(){let e=fe();if(!Cs(e))return{$schema:"https://nebutra.com/schema.json"};try{return JSON.parse(Es(e,"utf-8"))}catch(t){s.error(`Failed to parse ${Vn}: ${t instanceof Error?t.message:String(t)}`),process.exit(c.ERROR)}}function yt(e){ks(fe(),`${JSON.stringify(e,null,2)}
|
|
123
|
-
`)}function Se(e){return e.ai={providers:{},routes:{},...e.ai},e.ai.providers={...e.ai.providers},e.ai.routes={...e.ai.routes},e.ai}function Kn(e){let t=gt(),n=[...new Set(e.map(o=>o.toLowerCase()))],r=n.filter(o=>!t[o]);return r.length>0&&(s.error(`Unknown AI provider(s): ${r.join(", ")}. Valid providers: ${Object.keys(t).join(", ")}`),process.exit(c.INVALID_ARGS)),n}function _s(e){let t=e?.split(",").map(r=>r.trim()).filter(Boolean)??[];t.length===0&&(s.error("Route fallback cannot be empty. Use --fallback provider:model,provider:model"),process.exit(c.INVALID_ARGS));let n=t.filter(r=>!/^[a-z0-9-]+:[^,\s]+$/i.test(r));return n.length>0&&(s.error(`Invalid fallback target(s): ${n.join(", ")}. Expected provider:model.`),process.exit(c.INVALID_ARGS)),t}function qn(e){let t=Se(e),n=t.providers??{},r=t.routes??{},o=Object.entries(n).filter(([,a])=>a.enabled).map(([a])=>a);return{path:fe(),gateway:t.gateway??null,providers:n,enabledProviders:o,routes:r}}function ie(e){let t=typeof e.opts=="function"?e.opts():e,n=typeof e.optsWithGlobals=="function"?e.optsWithGlobals():t,r=t.format??n.format??Ps();return{...n,...t,...r?{format:r}:{}}}function Ps(){let e=process.argv.find(n=>n.startsWith("--format="));if(e)return e.slice(9);let t=process.argv.indexOf("--format");if(t>=0)return process.argv[t+1]}function He(e){return e?e.length<=8?"***":`${e.substring(0,8)}***`:"not set"}async function Is(e){e.format!=="json"&&s.info("Checking configured AI models and providers...");let t={openai:{name:"OpenAI",keyVars:["OPENAI_API_KEY"],configured:!1},anthropic:{name:"Anthropic Claude",keyVars:["ANTHROPIC_API_KEY"],configured:!1},openrouter:{name:"OpenRouter",keyVars:["OPENROUTER_API_KEY"],configured:!1},vercel:{name:"Vercel AI SDK",keyVars:["VERCEL_AI_API_KEY"],configured:!1}};for(let r of Object.values(t))r.configured=r.keyVars.some(o=>process.env[o]);let n={providers:Object.entries(t).map(([r,o])=>({id:r,name:o.name,configured:o.configured,keys:o.keyVars.map(a=>({name:a,value:He(process.env[a])}))})),configuredCount:Object.values(t).filter(r=>r.configured).length,totalProviders:Object.keys(t).length};e.dryRun||(n.configuredCount===0?s.warn("No AI providers configured. Set API keys to enable AI features."):s.success(`${n.configuredCount} AI provider(s) configured`)),ce(n,e.format,"ai:models")}async function Ns(e){e.format!=="json"&&s.info("Scanning for available agents...");try{let t=Vt(process.cwd(),"backends/gateway/src/routes/agents"),n=[];try{let o=await import("fs");o.existsSync(t)&&(n=o.readdirSync(t).filter(i=>i.endsWith(".ts")&&!i.endsWith(".d.ts")).map(i=>({name:i.replace(".ts",""),path:`backends/gateway/src/routes/agents/${i}`})))}catch{n=[]}let r={agents:n.length>0?n:[{name:"No agents found",path:"create agents in backends/gateway/src/routes/agents/"}],count:n.length};e.dryRun||(r.count===0?s.info("No agents configured. Create agents in backends/gateway/src/routes/agents/"):s.success(`Found ${r.count} agent(s)`)),ce(r,e.format,"ai:agents")}catch(t){s.error(`Failed to scan agents: ${t instanceof Error?t.message:String(t)}`),process.exit(c.ERROR)}}async function $s(e,t){(!e||e.trim().length===0)&&(s.error("Prompt cannot be empty"),process.exit(c.INVALID_ARGS)),t.format!=="json"&&(s.info("Testing AI prompt against default model..."),s.info("Note: Ensure API gateway is running on http://localhost:3001"));let n={prompt:e,note:"To execute this test, the API gateway must be running locally. Run: pnpm --filter @nebutra/gateway dev",endpoint:"http://localhost:3001/api/ai/test",method:"POST",payload:{prompt:e.substring(0,100)}};t.dryRun||s.warn("AI test execution requires a running API gateway. Start it with: pnpm --filter @nebutra/gateway dev"),ce(n,t.format,"ai:test")}async function Ts(e){e.format!=="json"&&s.info("Checking AI configuration...");let t={providers:{openai:{key:He(process.env.OPENAI_API_KEY),configured:!!process.env.OPENAI_API_KEY},anthropic:{key:He(process.env.ANTHROPIC_API_KEY),configured:!!process.env.ANTHROPIC_API_KEY},openrouter:{key:He(process.env.OPENROUTER_API_KEY),configured:!!process.env.OPENROUTER_API_KEY}},environment:{NODE_ENV:process.env.NODE_ENV||"development",NEBUTRA_LOG_LEVEL:process.env.NEBUTRA_LOG_LEVEL||"info"}};try{let r=Vt(process.cwd(),"nebutra.config.ts"),o=await import("fs");if(o.existsSync(r)){let i=o.readFileSync(r,"utf-8").match(/preset:\s*["']([^"']+)["']/);i&&(t.preset=i[1])}}catch{}let n=Object.entries(t.providers).filter(([,r])=>r.configured).map(([r])=>r);e.dryRun||(n.length===0?s.warn("No AI providers configured. Set environment variables to enable AI features."):s.success(`Configuration loaded: ${n.join(", ")}`)),ce(t,e.format,"ai:config")}async function Us(e){let t=Ie(),n=Se(t),r=gt(),o=Object.values(r).map(i=>{let l=n.providers?.[i.id];return{id:i.id,name:i.name,enabled:l?.enabled===!0,configured:i.envVars.some(u=>!!process.env[u]),envVars:i.envVars.map(u=>({name:u,value:He(process.env[u])}))}}),a={configPath:fe(),providers:o,enabledCount:o.filter(i=>i.enabled).length,totalProviders:o.length};if(e.format!=="json"){let i=o.filter(l=>l.enabled);i.length===0?s.warn("No runtime AI providers enabled in nebutra.config.json."):s.success(`Enabled AI providers: ${i.map(l=>l.id).join(", ")}`)}ce(a,e.format,"ai:provider:list")}async function js(e,t){let n=Kn(e),r=Ie(),o=Se(r),a=gt(),i=new Date().toISOString();for(let u of n)o.providers[u]={enabled:!0,envVars:a[u].envVars,enabledAt:o.providers?.[u]?.enabledAt??i};yt(r);let l={configPath:fe(),enabled:n,env:t.env===!0?n.flatMap(u=>a[u].envVars.map(m=>({provider:u,name:m,example:`${m}=`}))):void 0,ai:qn(r)};if(t.format!=="json"&&(s.success(`Enabled AI provider(s): ${n.join(", ")}`),t.env)){s.info("Required environment variables:");for(let u of n)for(let m of a[u].envVars)console.log(`${m}=`)}ce(l,t.format,"ai:provider:enable")}async function Ls(e,t){let n=Kn(e),r=Ie(),o=Se(r),a=gt(),i=new Date().toISOString();for(let u of n)o.providers[u]={enabled:!1,envVars:o.providers?.[u]?.envVars??a[u].envVars,disabledAt:i};yt(r);let l={configPath:fe(),disabled:n,ai:qn(r)};t.format!=="json"&&s.success(`Disabled AI provider(s): ${n.join(", ")}`),ce(l,t.format,"ai:provider:disable")}async function Ds(e){let t=Ie(),n=Se(t),r=new Date().toISOString();n.gateway={enabled:!0,mode:"local",initializedAt:n.gateway?.initializedAt??r,updatedAt:r},yt(t);let o={configPath:fe(),gateway:n.gateway};e.format!=="json"&&s.success("AI gateway governance initialized in nebutra.config.json"),ce(o,e.format,"ai:gateway:init")}async function Fs(e){let t=Ie(),n=Se(t),r={configPath:fe(),gateway:n.gateway??null,initialized:n.gateway?.enabled===!0};e.format!=="json"&&(r.initialized?s.success("AI gateway governance is initialized"):s.warn("AI gateway governance is not initialized. Run: nebutra ai gateway init")),ce(r,e.format,"ai:gateway:status")}async function Bs(e,t){(!e||e.trim().length===0)&&(s.error("Route name cannot be empty"),process.exit(c.INVALID_ARGS)),t.policy||(s.error("Route policy is required. Use --policy <policy>."),process.exit(c.INVALID_ARGS));let n=_s(t.fallback),r=Ie(),o=Se(r);o.routes[e]={policy:t.policy,fallback:n,updatedAt:new Date().toISOString()},yt(r);let a={configPath:fe(),route:{name:e,...o.routes[e]},routes:o.routes};t.format!=="json"&&s.success(`AI route '${e}' set with policy '${t.policy}'`),ce(a,t.format,"ai:route:set")}async function Ms(e){let t=Ie(),n=Se(t),r=Object.entries(n.routes??{}).map(([a,i])=>({name:a,...i})),o={configPath:fe(),routes:r,count:r.length};e.format!=="json"&&(r.length===0?s.warn("No AI routes configured. Run: nebutra ai route set chat --policy cost-latency-balanced --fallback openai:gpt-5.4"):s.success(`Configured AI routes: ${r.map(a=>a.name).join(", ")}`)),ce(o,e.format,"ai:route:list")}function zn(e){let t=e.command("ai").description("Manage AI models, agents, and configuration"),n=t.command("provider").description("Manage runtime AI provider governance");n.command("list").description("List supported and enabled AI providers").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Us({format:i.format,interactive:i.yes!==!0})}),n.command("enable <providers...>").description("Enable one or more runtime AI providers in nebutra.config.json").option("--env","Print required environment variable placeholders").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await js(a,{env:l.env===!0,format:l.format,interactive:l.yes!==!0})}),n.command("disable <providers...>").description("Disable one or more runtime AI providers in nebutra.config.json").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await Ls(a,{format:l.format,interactive:l.yes!==!0})});let r=t.command("gateway").description("Manage local AI gateway governance");r.command("init").description("Initialize the local AI gateway governance block").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ds({format:i.format,interactive:i.yes!==!0})}),r.command("status").description("Show local AI gateway governance status").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Fs({format:i.format,interactive:i.yes!==!0})});let o=t.command("route").description("Manage AI routing policies");o.command("set <name>").description("Create or update an AI route policy").requiredOption("--policy <policy>","Routing policy id").requiredOption("--fallback <list>","Comma-separated provider:model fallback chain").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await Bs(a,{policy:l.policy,fallback:l.fallback,format:l.format,interactive:l.yes!==!0})}),o.command("list").description("List configured AI routes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ms({format:i.format,interactive:i.yes!==!0})}),t.command("models").description("List configured AI models and providers").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Is({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})}),t.command("agents").description("List available agents in the project").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ns({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})}),t.command("test <prompt>").description("Send a test prompt to the default AI model (requires running API gateway)").option("--dry-run","Preview without executing").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await $s(a,{dryRun:l.dryRun===!0,format:l.format,interactive:l.yes!==!0})}),t.command("config").description("Show current AI configuration and provider status").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ts({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})})}import{resolve as Gs}from"path";function Kt(e,t,n){if(t==="json"){let r={command:n||"auth",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function v(e,t){return e?e.length<=8?"***":`${e.substring(0,8)}*** (${t||e.length} chars)`:"not set"}function Vs(){try{let e=Gs(process.cwd(),"nebutra.config.ts"),t=jo("fs");if(t.existsSync(e)){let n=t.readFileSync(e,"utf-8");if(n.includes("clerk"))return"clerk";if(n.includes("better-auth"))return"better-auth";if(n.includes("nextauth"))return"nextauth";if(n.includes("supabase"))return"supabase"}}catch{}return"clerk"}async function Ks(e){s.info("Checking authentication configuration...");let t=Vs(),n={provider:t,configured:!1,keys:{}};t==="clerk"?(n.keys={CLERK_SECRET_KEY:v(process.env.CLERK_SECRET_KEY,"secret"),NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,"publishable"),CLERK_WEBHOOK_SECRET:v(process.env.CLERK_WEBHOOK_SECRET,"webhook")},n.configured=!!process.env.CLERK_SECRET_KEY&&!!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY):t==="better-auth"?(n.keys={BETTER_AUTH_SECRET:v(process.env.BETTER_AUTH_SECRET,"secret"),BETTER_AUTH_URL:process.env.BETTER_AUTH_URL||"not set"},n.configured=!!process.env.BETTER_AUTH_SECRET):t==="nextauth"?(n.keys={AUTH_SECRET:v(process.env.AUTH_SECRET,"secret"),NEXTAUTH_SECRET:v(process.env.NEXTAUTH_SECRET,"legacy secret"),NEXTAUTH_URL:process.env.NEXTAUTH_URL||"not set",AUTH_URL:process.env.AUTH_URL||"not set",GOOGLE_CLIENT_ID:v(process.env.GOOGLE_CLIENT_ID,"google client"),GITHUB_CLIENT_ID:v(process.env.GITHUB_CLIENT_ID,"github client")},n.configured=!!(process.env.AUTH_SECRET||process.env.NEXTAUTH_SECRET)):(n.keys={NEXT_PUBLIC_SUPABASE_URL:process.env.NEXT_PUBLIC_SUPABASE_URL||"not set",NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,"publishable"),NEXT_PUBLIC_SUPABASE_ANON_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,"anon"),SUPABASE_URL:process.env.SUPABASE_URL||"not set",SUPABASE_PUBLISHABLE_KEY:v(process.env.SUPABASE_PUBLISHABLE_KEY,"publishable"),SUPABASE_ANON_KEY:v(process.env.SUPABASE_ANON_KEY,"anon"),SUPABASE_SERVICE_ROLE_KEY:v(process.env.SUPABASE_SERVICE_ROLE_KEY,"service role"),SUPABASE_WEBHOOK_SECRET:v(process.env.SUPABASE_WEBHOOK_SECRET,"webhook")},n.configured=!!((process.env.SUPABASE_URL||process.env.NEXT_PUBLIC_SUPABASE_URL)&&(process.env.SUPABASE_PUBLISHABLE_KEY||process.env.SUPABASE_ANON_KEY||process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY||process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY)&&process.env.SUPABASE_SERVICE_ROLE_KEY)),e.dryRun||(n.configured?s.success(`Auth provider configured: ${t}`):s.warn(`Auth provider ${t} is not fully configured`)),Kt({...n},e.format,"auth:status")}async function qs(e,t){let n=["clerk","better-auth","nextauth","supabase"];n.includes(e.toLowerCase())||(s.error(`Invalid provider: ${e}. Choose from: ${n.join(", ")}`),process.exit(c.INVALID_ARGS));let r=e.toLowerCase();s.info(`Setting up ${r} authentication...`),r==="clerk"?(s.info("Clerk setup requires:"),s.info("1. A Clerk account (https://clerk.com)"),s.info("2. A Clerk application created"),s.info("3. API keys from the Clerk dashboard"),s.info(""),s.info("To complete setup:"),s.info("1. Go to https://dashboard.clerk.com"),s.info("2. Copy your Secret Key and Publishable Key"),s.info("3. Add them to .env.local:"),s.info(' CLERK_SECRET_KEY="sk_..."'),s.info(' NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_..."'),s.info(""),s.info("Webhook setup (optional):"),s.info("1. In Clerk dashboard, go to Webhooks"),s.info("2. Create endpoint: https://yourdomain.com/api/webhooks/clerk"),s.info("3. Copy the signing secret to .env.local:"),s.info(' CLERK_WEBHOOK_SECRET="whsec_..."')):r==="better-auth"?(s.info("Better Auth setup requires:"),s.info("1. Database URL configured (DATABASE_URL env var)"),s.info("2. A generated auth secret"),s.info(""),s.info("To complete setup:"),s.info("1. Ensure DATABASE_URL is set in .env.local"),s.info("2. Generate a new secret:"),s.info(" openssl rand -base64 32"),s.info("3. Add to .env.local:"),s.info(' BETTER_AUTH_SECRET="<generated_secret>"'),s.info(' BETTER_AUTH_URL="http://localhost:3000"'),s.info(""),s.info("4. Run database migration:"),s.info(" pnpm --filter @nebutra/web db:push")):r==="nextauth"?(s.info("NextAuth / Auth.js setup requires:"),s.info("1. A generated Auth.js secret"),s.info("2. NEXTAUTH_URL or AUTH_URL pointing at the web app origin"),s.info("3. OAuth provider credentials for each enabled provider"),s.info(""),s.info("To complete setup:"),s.info("1. Generate a new secret:"),s.info(" openssl rand -base64 32"),s.info("2. Add to the production environment:"),s.info(' AUTH_PROVIDER="nextauth"'),s.info(' NEXT_PUBLIC_AUTH_PROVIDER="nextauth"'),s.info(' AUTH_SECRET="<generated_secret>"'),s.info(' NEXTAUTH_URL="https://app.nebutra.com"'),s.info(' GOOGLE_CLIENT_ID="..."'),s.info(' GOOGLE_CLIENT_SECRET="..."')):(s.info("Supabase Auth setup requires:"),s.info("1. Supabase project URL"),s.info("2. Public anon key for browser auth"),s.info("3. Service role key for server-side user/session validation"),s.info(""),s.info("To complete setup:"),s.info(' AUTH_PROVIDER="supabase"'),s.info(' NEXT_PUBLIC_AUTH_PROVIDER="supabase"'),s.info(' NEXT_PUBLIC_SUPABASE_URL="https://xxx.supabase.co"'),s.info(' NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY="sb_publishable_..."'),s.info(' NEXT_PUBLIC_SUPABASE_ANON_KEY="..."'),s.info(' SUPABASE_URL="https://xxx.supabase.co"'),s.info(' SUPABASE_PUBLISHABLE_KEY="sb_publishable_..."'),s.info(' SUPABASE_ANON_KEY="..."'),s.info(' SUPABASE_SERVICE_ROLE_KEY="..."')),t.dryRun||s.success(`Setup instructions for ${r} displayed above`),Kt({provider:r,setupGuide:"Complete setup by following the instructions above",documentationUrl:r==="clerk"?"https://clerk.com/docs":r==="better-auth"?"https://www.better-auth.com":r==="nextauth"?"https://authjs.dev":"https://supabase.com/docs/guides/auth"},t.format,"auth:setup")}async function zs(e){s.info("Checking authentication keys and secrets...");let n={keys:{clerk:{CLERK_SECRET_KEY:v(process.env.CLERK_SECRET_KEY,"secret key"),NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,"publishable key"),CLERK_WEBHOOK_SECRET:v(process.env.CLERK_WEBHOOK_SECRET,"webhook secret")},betterAuth:{BETTER_AUTH_SECRET:v(process.env.BETTER_AUTH_SECRET,"secret"),BETTER_AUTH_URL:process.env.BETTER_AUTH_URL||"not set"},nextAuth:{AUTH_SECRET:v(process.env.AUTH_SECRET,"secret"),NEXTAUTH_SECRET:v(process.env.NEXTAUTH_SECRET,"legacy secret"),NEXTAUTH_URL:process.env.NEXTAUTH_URL||"not set",AUTH_URL:process.env.AUTH_URL||"not set",GOOGLE_CLIENT_ID:v(process.env.GOOGLE_CLIENT_ID,"google client"),GITHUB_CLIENT_ID:v(process.env.GITHUB_CLIENT_ID,"github client")},supabase:{NEXT_PUBLIC_SUPABASE_URL:process.env.NEXT_PUBLIC_SUPABASE_URL||"not set",NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,"publishable"),NEXT_PUBLIC_SUPABASE_ANON_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,"anon"),SUPABASE_URL:process.env.SUPABASE_URL||"not set",SUPABASE_PUBLISHABLE_KEY:v(process.env.SUPABASE_PUBLISHABLE_KEY,"publishable"),SUPABASE_ANON_KEY:v(process.env.SUPABASE_ANON_KEY,"anon"),SUPABASE_SERVICE_ROLE_KEY:v(process.env.SUPABASE_SERVICE_ROLE_KEY,"service role")},common:{DATABASE_URL:v(process.env.DATABASE_URL,"database url"),JWT_SECRET:v(process.env.JWT_SECRET,"jwt secret")}},configured:{clerk:{secret:!!process.env.CLERK_SECRET_KEY,publishable:!!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY},betterAuth:{secret:!!process.env.BETTER_AUTH_SECRET,url:!!process.env.BETTER_AUTH_URL},nextAuth:{secret:!!(process.env.AUTH_SECRET||process.env.NEXTAUTH_SECRET),url:!!(process.env.NEXTAUTH_URL||process.env.AUTH_URL)},supabase:{url:!!(process.env.SUPABASE_URL||process.env.NEXT_PUBLIC_SUPABASE_URL),publishableKey:!!(process.env.SUPABASE_PUBLISHABLE_KEY||process.env.SUPABASE_ANON_KEY||process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY||process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY),serviceRole:!!process.env.SUPABASE_SERVICE_ROLE_KEY}}};if(!e.dryRun){let r=n.configured.clerk.secret&&n.configured.clerk.publishable,o=n.configured.betterAuth.secret&&n.configured.betterAuth.url,a=n.configured.nextAuth.secret&&n.configured.nextAuth.url,i=n.configured.supabase.url&&n.configured.supabase.publishableKey&&n.configured.supabase.serviceRole;!r&&!o&&!a&&!i?s.warn("No authentication keys configured"):(s.info("Auth keys status:"),r&&s.success("Clerk configured"),o&&s.success("Better Auth configured"),a&&s.success("NextAuth configured"),i&&s.success("Supabase configured"))}Kt(n,e.format,"auth:keys")}function Yn(e){let t=e.command("auth").description("Manage authentication configuration (Clerk, Better Auth, NextAuth, or Supabase)");t.command("status").description("Check current authentication provider configuration").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await Ks({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("setup <provider>").description("Configure Clerk, Better Auth, NextAuth, or Supabase (interactive wizard)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async(n,r)=>{let o=r.optsWithGlobals?.()||r;await qs(n,{dryRun:r.dryRun||!1,format:r.format||o.format,interactive:o.yes!==!0})}),t.command("keys").description("Show authentication-related environment variables (masked)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await zs({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}import Ce from"fs";import le from"path";import*as ht from"@clack/prompts";import Jn from"picocolors";function x(e,t){let n=typeof e.optsWithGlobals=="function"?e.optsWithGlobals():void 0;return{...t&&typeof t.optsWithGlobals=="function"?t.optsWithGlobals():void 0,...n,...e}}var Hn=["ts","py"],Ys=`{
|
|
109
|
+
`)}function d(e,t="info"){let n;switch(t){case"error":n=pe.red("\u2716");break;case"warn":n=pe.yellow("\u26A0");break;case"success":n=pe.green("\u2713");break;default:n=pe.blue("\u2139");break}let r=`${n} ${e}`;Se.write(r+`
|
|
110
|
+
`)}function k(e,t){if(!(process.env.NEBUTRA_DEBUG||process.argv.includes("--debug")))return;let r=pe.dim(`[debug] ${e}`);Se.write(r+`
|
|
111
|
+
`),t&&Object.keys(t).length>0&&Se.write(pe.dim(JSON.stringify(t,null,2))+`
|
|
112
|
+
`)}function mt(e){Se.write(`
|
|
113
|
+
`),Se.write(pe.bold(pe.cyan(e))+`
|
|
114
|
+
`),Se.write(pe.gray("-".repeat(e.length))+`
|
|
115
|
+
`),Se.write(`
|
|
116
|
+
`)}function U(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ze(e){return Array.isArray(e)?e:[]}function qe(e,t){return U(e)[t]}function Fe(e,t,n=0){let r=qe(e,t);return typeof r=="number"?r:n}function S(e,t=""){return e==null?t:String(e)}async function Q(e,t={}){let n=process.env.NEBUTRA_API_URL||"http://localhost:3100",r=process.env.NEBUTRA_ADMIN_KEY;if(!r)return{ok:!1,status:401,error:"NEBUTRA_ADMIN_KEY environment variable not set. Set it to your admin API key."};let o=new URL(e,n).toString(),a=t.method||"GET",i=t.body?JSON.stringify(t.body):void 0;if(t.dryRun){let l={mode:"dry-run",timestamp:new Date().toISOString(),method:a,url:o,...i&&{body:JSON.parse(i)},headers:{"X-Admin-Key":"***","Content-Type":"application/json"}};return A(l),{ok:!0,status:0,data:l}}try{let l=await fetch(o,{method:a,headers:{"X-Admin-Key":r,"Content-Type":"application/json"},...i&&{body:i}}),u=await l.json().catch(()=>null);if(!l.ok){let m=qe(u,"error");return{ok:!1,status:l.status,error:typeof m=="string"?m:`HTTP ${l.status}`}}return{ok:!0,status:l.status,data:u}}catch(l){return{ok:!1,status:0,error:`Network error: ${l instanceof Error?l.message:String(l)}`}}}function Y(e,t,n){if(t==="json"){let r={command:n||"admin",...e};console.log(JSON.stringify(r,null,2))}else console.log(JSON.stringify(e,null,2))}function Z(e,t,n){Y(U(e),t,n)}async function ls(e){s.info("Fetching tenants...");let t=new URLSearchParams;e.limit&&t.append("limit",String(e.limit)),e.offset&&t.append("offset",String(e.offset)),e.status&&t.append("status",e.status);let n=`/api/v1/admin/tenants${t.toString()?`?${t.toString()}`:""}`,r=await Q(n,{dryRun:e.dryRun});if(r.ok||(s.error(`Failed to fetch tenants: ${r.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(r.data,e.format,"admin:tenants");return}let o=U(r.data),a={tenants:ze(o.tenants??o.data),total:Fe(o,"total")||Fe(o.meta,"total"),limit:o.limit??qe(o.meta,"limit"),offset:o.offset??qe(o.meta,"offset")};e.format==="json"?Y(a,e.format,"admin:tenants"):(s.info(`Found ${a.total} tenant(s)`),a.tenants.length>0&&(console.log(`
|
|
117
|
+
Tenants:`),a.tenants.forEach(i=>{let l=U(i);console.log(` ${T.blue(S(l.id))} \u2014 ${S(l.name,"(unnamed)")}`),console.log(` Status: ${S(l.status)}`),l.plan&&console.log(` Plan: ${S(l.plan)}`)})))}async function ds(e,t){s.info(`Fetching tenant ${e}...`);let n=await Q(`/api/v1/admin/tenants/${e}`,{dryRun:t.dryRun});if(n.ok||(s.error(`Failed to fetch tenant: ${n.error}`),process.exit(c.NETWORK_ERROR)),t.dryRun){Z(n.data,t.format,"admin:tenant");return}if(t.format==="json")Y({tenant:U(n.data)},t.format,"admin:tenant");else{let r=U(n.data);s.success(`Tenant ${T.blue(S(r.id))}`),console.log(` Name: ${S(r.name)}`),console.log(` Status: ${S(r.status)}`),console.log(` Plan: ${S(r.plan)}`),console.log(` Created: ${S(r.createdAt)}`),r.suspendedAt&&console.log(` Suspended: ${S(r.suspendedAt)}`)}}async function us(e,t){t.yes||(s.warn(`Suspending tenant ${e} will disable all operations`),s.info("Use --yes to confirm"),process.exit(c.CANCELLED)),s.info(`Suspending tenant ${e}...`);let n=await Q(`/api/v1/admin/tenants/${e}/suspend`,{method:"POST",dryRun:t.dryRun});if(n.ok||(s.error(`Failed to suspend tenant: ${n.error}`),process.exit(c.NETWORK_ERROR)),t.dryRun){Z(n.data,t.format,"admin:suspend");return}s.success(`Tenant ${T.blue(e)} suspended`),t.format==="json"&&Y({suspended:!0,tenantId:e},t.format,"admin:suspend")}async function ms(e,t){s.info(`Unsuspending tenant ${e}...`);let n=await Q(`/api/v1/admin/tenants/${e}/unsuspend`,{method:"POST",dryRun:t.dryRun});if(n.ok||(s.error(`Failed to unsuspend tenant: ${n.error}`),process.exit(c.NETWORK_ERROR)),t.dryRun){Z(n.data,t.format,"admin:unsuspend");return}s.success(`Tenant ${T.blue(e)} unsuspended`),t.format==="json"&&Y({unsuspended:!0,tenantId:e},t.format,"admin:unsuspend")}async function ps(e){s.info("Fetching usage report...");let t=new URLSearchParams;e.period&&t.append("period",e.period),e.top&&t.append("top",String(e.top));let n=`/api/v1/admin/usage/report${t.toString()?`?${t.toString()}`:""}`,r=await Q(n,{dryRun:e.dryRun});if(r.ok||(s.error(`Failed to fetch usage report: ${r.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(r.data,e.format,"admin:usage");return}let o=U(r.data),a={period:o.period,topTenants:ze(o.topTenants??o.data),totalUsage:o.totalUsage};e.format==="json"?Y(a,e.format,"admin:usage"):(s.info(`Usage report for period: ${S(a.period)}`),console.log(`Total usage: ${S(a.totalUsage)}`),a.topTenants.length>0&&(console.log(`
|
|
118
|
+
Top tenants:`),a.topTenants.forEach((i,l)=>{let u=U(i);console.log(` ${l+1}. ${S(u.tenantName||u.tenantId||u.name)} \u2014 ${S(u.usage)}`)})))}async function fs(e){s.info("Fetching dead letter queue...");let t=await Q("/api/v1/admin/dlq/list",{dryRun:e.dryRun});if(t.ok||(s.error(`Failed to fetch DLQ: ${t.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(t.data,e.format,"admin:dlq:list");return}let n=U(t.data),r={messages:ze(n.messages??n.data),count:Fe(n,"count")||Fe(n,"total")};e.format==="json"?Y(r,e.format,"admin:dlq:list"):(s.info(`Found ${r.count} message(s) in DLQ`),r.messages.length>0&&(console.log(`
|
|
119
|
+
Messages:`),r.messages.forEach(o=>{let a=U(o);console.log(` ${T.blue(S(a.id))}`),console.log(` Type: ${S(a.type)}`),console.log(` Error: ${S(a.error)}`),console.log(` Created: ${S(a.createdAt)}`)})))}async function gs(e,t){s.info(`Replaying DLQ message ${e}...`);let n=await Q(`/api/v1/admin/dlq/replay/${e}`,{method:"POST",dryRun:t.dryRun});if(n.ok||(s.error(`Failed to replay message: ${n.error}`),process.exit(c.NETWORK_ERROR)),t.dryRun){Z(n.data,t.format,"admin:dlq:replay");return}s.success(`Message ${T.blue(e)} replayed`),t.format==="json"&&Y({replayed:!0,messageId:e},t.format,"admin:dlq:replay")}async function ys(e){e.yes||(s.warn("This will permanently delete all messages in the DLQ"),s.info("Use --yes to confirm"),process.exit(c.CANCELLED)),s.info("Purging DLQ...");let t=await Q("/api/v1/admin/dlq/purge",{method:"POST",dryRun:e.dryRun});if(t.ok||(s.error(`Failed to purge DLQ: ${t.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(t.data,e.format,"admin:dlq:purge");return}s.success("DLQ purged"),e.format==="json"&&Y({purged:!0,count:qe(t.data,"count")},e.format,"admin:dlq:purge")}async function hs(e){s.info("Fetching feature flags...");let t=await Q("/api/v1/admin/feature-flags",{dryRun:e.dryRun});if(t.ok||(s.error(`Failed to fetch flags: ${t.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(t.data,e.format,"admin:flags:list");return}let n=U(t.data),r={flags:ze(n.flags??n.data),total:Fe(n,"total")};e.format==="json"?Y(r,e.format,"admin:flags:list"):(s.info(`Found ${r.total} flag(s)`),r.flags.length>0&&(console.log(`
|
|
120
|
+
Flags:`),r.flags.forEach(o=>{let a=U(o),i=a.override!==void 0?T.yellow(String(a.override)):T.gray(String(a.default??""));console.log(` ${T.blue(S(a.name))} = ${i}`)})))}async function bs(e,t,n){s.info(`Setting flag ${e}...`);let r=t;t==="true"?r=!0:t==="false"?r=!1:Number.isNaN(Number(t))||(r=Number(t));let o=await Q(`/api/v1/admin/feature-flags/${e}`,{method:"POST",body:{value:r},dryRun:n.dryRun});if(o.ok||(s.error(`Failed to set flag: ${o.error}`),process.exit(c.NETWORK_ERROR)),n.dryRun){Z(o.data,n.format,"admin:flags:set");return}s.success(`Flag ${T.blue(e)} set to ${r}`),n.format==="json"&&Y({flag:e,value:r},n.format,"admin:flags:set")}async function vs(e,t){s.info(`Unsetting flag ${e}...`);let n=await Q(`/api/v1/admin/feature-flags/${e}`,{method:"DELETE",dryRun:t.dryRun});if(n.ok||(s.error(`Failed to unset flag: ${n.error}`),process.exit(c.NETWORK_ERROR)),t.dryRun){Z(n.data,t.format,"admin:flags:unset");return}s.success(`Flag ${T.blue(e)} unset`),t.format==="json"&&Y({flag:e,unset:!0},t.format,"admin:flags:unset")}async function ws(e){s.info("Fetching audit log...");let t=new URLSearchParams;e.actor&&t.append("actor",e.actor),e.action&&t.append("action",e.action),e.since&&t.append("since",e.since),e.limit&&t.append("limit",String(e.limit));let n=`/api/v1/admin/audit${t.toString()?`?${t.toString()}`:""}`,r=await Q(n,{dryRun:e.dryRun});if(r.ok||(s.error(`Failed to fetch audit log: ${r.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(r.data,e.format,"admin:audit");return}let o=U(r.data),a={entries:ze(o.entries??o.data),total:Fe(o,"total")};e.format==="json"?Y(a,e.format,"admin:audit"):(s.info(`Found ${a.total} audit log entries`),a.entries.length>0&&(console.log(`
|
|
121
|
+
Audit entries:`),a.entries.forEach(i=>{let l=U(i);console.log(` ${S(l.timestamp)} \u2014 ${T.blue(S(l.action))} by ${S(l.actor)}`),l.details&&console.log(` ${S(l.details)}`)})))}async function Ss(e){s.info("Running platform health check...");let t=await Q("/api/v1/system/status",{dryRun:e.dryRun});if(t.ok||(s.error(`Failed to fetch health status: ${t.error}`),process.exit(c.NETWORK_ERROR)),e.dryRun){Z(t.data,e.format,"admin:health");return}let n=U(t.data),r={status:S(n.status,"unknown"),services:U(n.services),timestamp:n.timestamp};if(e.format==="json")Y(r,e.format,"admin:health");else{let o=r.status==="healthy"?T.green:r.status==="degraded"?T.yellow:T.red;s.info(`Platform status: ${o(r.status)}`),Object.keys(r.services).length>0&&(console.log(`
|
|
122
|
+
Services:`),Object.entries(r.services).forEach(([a,i])=>{let l=U(i),u=l.status==="healthy"?T.green("\u2713"):T.red("\u2717");console.log(` ${u} ${a}: ${S(l.status)}`),l.latency&&console.log(` Latency: ${S(l.latency)}ms`),l.error&&console.log(` Error: ${S(l.error)}`)}))}}function Mn(e){let t=e.command("admin").description("Platform admin operations");t.command("tenants").description("List all tenants/organizations").option("--limit <n>","Maximum number of tenants to return",o=>parseInt(o,10)).option("--offset <n>","Offset for pagination",o=>parseInt(o,10)).option("--status <status>","Filter by status (active|suspended)").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ls({limit:o.limit,offset:o.offset,status:o.status,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),t.command("tenant <id>").description("Get tenant details").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await ds(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("suspend <id>").description("Suspend a tenant (requires --yes)").option("--yes","Confirm suspension").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await us(o,{yes:a.yes||i.yes,format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("unsuspend <id>").description("Unsuspend a tenant").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await ms(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("usage").description("Cross-tenant usage report").option("--period <period>","Report period (daily|weekly|monthly)").option("--top <n>","Show top N tenants",o=>parseInt(o,10)).option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ps({period:o.period,top:o.top,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})});let n=t.command("dlq").description("Dead letter queue management");n.command("list").description("List failed messages in DLQ").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await fs({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),n.command("replay <id>").description("Replay a failed message").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await gs(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),n.command("purge").description("Purge the dead letter queue (requires --yes)").option("--yes","Confirm purge").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ys({yes:o.yes||a.yes,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})});let r=t.command("flags").description("Feature flag management");r.command("list").description("List all feature flags").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await hs({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),r.command("set <flag> <value>").description("Set a feature flag override").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a,i)=>{let l=i.optsWithGlobals?.()||i;await bs(o,a,{format:i.format||l.format,dryRun:i.dryRun||l.dryRun})}),r.command("unset <flag>").description("Remove a feature flag override").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async(o,a)=>{let i=a.optsWithGlobals?.()||a;await vs(o,{format:a.format||i.format,dryRun:a.dryRun||i.dryRun})}),t.command("audit").description("Query audit log with optional filters").option("--actor <userId>","Filter by actor/user ID").option("--action <type>","Filter by action type").option("--since <date>","Filter entries since date (ISO format)").option("--limit <n>","Maximum number of entries to return",o=>parseInt(o,10)).option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await ws({actor:o.actor,action:o.action,since:o.since,limit:o.limit,format:o.format||a.format,dryRun:o.dryRun||a.dryRun})}),t.command("health").description("Platform-wide health check").option("--format <type>","Output format: json or plain").option("--dry-run","Show request without executing").action(async o=>{let a=o.optsWithGlobals?.()||o;await Ss({format:o.format||a.format,dryRun:o.dryRun||a.dryRun})})}import{existsSync as Cs,readFileSync as Es,writeFileSync as ks}from"fs";import{resolve as Mt}from"path";var b={pm:["npm","pnpm","yarn","bun"],region:["global","cn","hybrid"],orm:["prisma","drizzle","none"],db:["postgres","mysql","sqlite","none"],auth:["clerk","betterauth","none"],socialLogin:["wechat","qq","dingtalk","workweixin","feishu","weibo"],payment:["stripe","lemon","wechat","alipay","none"],ai:["openai","anthropic","deepseek","xai","moonshot","google","mistral","cohere","perplexity","ai21","upstage","siliconflow","volcengine-ark","bailian","zhipu","baichuan","minimax","stepfun","sensetime","tencent","lingyi","openrouter","vercel-gateway","litellm","portkey","aws-bedrock","azure-openai","gcp-vertex","groq","fireworks","together","huggingface","replicate","lepton","anyscale","octoai","deepinfra","novita","custom","none"],deploy:["vercel","railway","cloudflare","selfhost","none"],docs:["fumadocs","mintlify","docusaurus","nextra","vitepress","none"],email:["resend","postmark","ses","aliyun-dm","tencent-ses","netease","none"],storage:["r2","s3","supabase-storage","aliyun-oss","tencent-cos","qiniu","none"],monitoring:["sentry","datadog","bugsnag","aliyun-arms","tingyun","none"],analytics:["posthog","plausible","umami","mixpanel","baidu","sensors","growingio","none"],sms:["twilio","messagebird","plivo","aliyun-sms","tencent-sms","yunpian","none"],queue:["qstash","bullmq","upstash","sqs","none"],search:["meilisearch","typesense","algolia","pgvector","none"],cache:["upstash-redis","vercel-kv","redis","dragonfly","none"],notifications:["novu","knock","custom","none"],webhooks:["svix","custom","none"],cms:["sanity","contentful","strapi","none"],featureFlags:["vercel-flags","growthbook","configcat","none"],captcha:["turnstile","hcaptcha","aliyun-slide","none"],mcp:["on","off"],metering:["auto","on","off"],billingMode:["usage","seat","credits"],idp:["clerk","oauth-server"]},Rs=[{flags:"-p, --pm <id>",description:"Package manager: npm, pnpm, yarn, or bun"},{flags:"--region <id>",description:"Target region: global, cn, or hybrid"},{flags:"--orm <id>",description:"ORM: prisma, drizzle, or none"},{flags:"--db <id>",description:"Database: postgres, mysql, sqlite, or none"},{flags:"--auth <id>",description:"Auth provider: clerk, betterauth, or none"},{flags:"--social-login <ids>",description:"Comma-separated CN social login providers"},{flags:"--payment <id>",description:"Payment provider: stripe, lemon, wechat, alipay, or none"},{flags:"--ai <ids>",description:"Expert/non-interactive AI provider seed ids"},{flags:"--deploy <target>",description:"Deploy target: vercel, railway, cloudflare, selfhost, or none"},{flags:"--docs <id>",description:"Docs framework: fumadocs, mintlify, docusaurus, nextra, vitepress, or none"},{flags:"--email <id>",description:"Transactional email provider"},{flags:"--storage <id>",description:"Object storage provider"},{flags:"--monitoring <id>",description:"Monitoring provider"},{flags:"--analytics <id>",description:"Analytics provider"},{flags:"--sms <id>",description:"SMS provider"},{flags:"--queue <id>",description:"Queue provider"},{flags:"--search <id>",description:"Search provider"},{flags:"--cache <id>",description:"Cache provider"},{flags:"--notifications <id>",description:"Notifications provider"},{flags:"--webhooks <id>",description:"Outbound webhooks provider"},{flags:"--cms <id>",description:"Headless CMS provider"},{flags:"--feature-flags <id>",description:"Feature flag provider"},{flags:"--captcha <id>",description:"Captcha provider"},{flags:"--mcp <mode>",description:"MCP server mode: on or off"},{flags:"--metering <mode>",description:"Metering mode: auto, on, or off"},{flags:"--billing-mode <mode>",description:"Billing mode: usage, seat, or credits"},{flags:"--idp <id>",description:"Identity provider: clerk or oauth-server"},{flags:"--i18n",description:"Enable i18n",default:!0},{flags:"--no-i18n",description:"Disable i18n"},{flags:"--no-install",description:"Skip package install"},{flags:"--no-git",description:"Skip git init"},{flags:"--dry-run",description:"Preview project scaffolding without creating files (exit code 10)"},{flags:"--json",description:"Emit machine-readable JSON events"},{flags:"--yes",description:"Skip all interactive prompts (Agent mode)"}],fe={name:"nebutra",description:"Governance-first CLI for Nebutra Sailor scaffolding, registry-backed features, and platform operations",usage:"nebutra [command] [options]",options:[{flags:"--format <type>",description:"Output format: json, table, plain"},{flags:"--yes, --no-interactive",description:"Skip all interactive prompts (Agent mode)"},{flags:"--no-color",description:"Disable colored output"},{flags:"--verbose",description:"Enable verbose output"},{flags:"--quiet",description:"Suppress non-essential output"}],subcommands:[{name:"init",description:"Initialize a Nebutra project and create nebutra.config.json",usage:"nebutra init [options]",options:[{flags:"--dry-run",description:"Preview changes without writing files (exits with code 10)"},{flags:"--yes",description:"Skip all interactive prompts (Agent mode)"},{flags:"--if-not-exists",description:"Skip initialization if nebutra.config.json already exists"}],arguments:[],examples:[{command:"nebutra init",description:"Initialize Nebutra configuration in the current directory"},{command:"nebutra init --dry-run",description:"Preview initialization changes without writing files"},{command:"nebutra init --yes --if-not-exists",description:"Initialize without prompts, skip if already configured"}]},{name:"add",description:"Add a registry-backed platform feature or external UI component",usage:"nebutra add [components...] [options]",arguments:[{name:"components",description:"Local feature names to install from the Nebutra registry",required:!1,variadic:!0}],options:[{flags:"--21st <id>",description:"Fetch and install a component from 21st.dev registry"},{flags:"--v0 <url>",description:"Fetch and install a component from v0.dev by URL"},{flags:"--dry-run",description:"Preview what would be installed without making changes (exit code 10)"},{flags:"--yes",description:"Skip all interactive prompts and use defaults (Agent mode)"},{flags:"--if-not-exists",description:"Skip installation if component already exists"}],examples:[{command:"nebutra add cache --provider upstash-redis --yes",description:"Install the local cache feature with the Upstash Redis provider"},{command:"nebutra add --21st button-01",description:"Add a component from 21st.dev (shadcn-style registry)"},{command:'nebutra add --v0 "https://v0.dev/r/..." --dry-run',description:"Preview adding a component from v0.dev without making changes"},{command:"nebutra add webhooks --provider svix --yes --if-not-exists",description:"Install webhooks without prompts, skip if already configured"}]},{name:"create",description:"Scaffold a topology-first Nebutra Sailor project with governed defaults",usage:"nebutra create [dir] [options]",arguments:[{name:"dir",description:"Target directory for the new project (optional, will prompt if not provided)",required:!1}],options:Rs,examples:[{command:"nebutra create my-saas-app --region=hybrid --ai=openai,deepseek",description:"Create a topology-first project with hybrid defaults and selected AI providers"},{command:"nebutra create my-cn-app --region=cn --payment=wechat --storage=aliyun-oss --deploy=selfhost -y",description:"Create a non-interactive China-ready scaffold"},{command:"nebutra create my-app --storage=supabase-storage --dry-run --json",description:"Preview scaffolding with structured JSON output"}]},{name:"mcp",description:"Start the Nebutra MCP server for AI agents and editors",usage:"nebutra mcp [options]",arguments:[],options:[{flags:"--stdio",description:"Use stdio transport for communication (default: enabled)",default:!0},{flags:"--verbose",description:"Enable verbose logging for MCP server"}],examples:[{command:"nebutra mcp",description:"Start the MCP server for AI-powered project context integration"},{command:"nebutra mcp --verbose",description:"Start the MCP server with detailed logging output"}]},{name:"schema",description:"Show command schema and argument documentation (Agent-friendly JSON output)",usage:"nebutra schema [command] [options]",arguments:[{name:"command",description:"Command name to show schema for (e.g., init, add, create)",required:!1}],options:[{flags:"--all",description:"Show full schema for all commands as JSON",default:!1},{flags:"--list",description:"List all available command names",default:!1},{flags:"--exit-codes",description:"Show exit codes reference",default:!1}],examples:[{command:"nebutra schema --all",description:"Show complete JSON of all commands, args, options, value domains"},{command:"nebutra schema init",description:"Show schema for init command (arguments, options, defaults, examples)"},{command:"nebutra schema add",description:"Show schema for add command with enum values"},{command:"nebutra schema --list",description:"List just the command names (quick discovery)"},{command:"nebutra schema --exit-codes",description:"Show exit codes reference for all possible exit codes"}]},{name:"brand",description:"Manage governed brand tokens, palettes, and visual system outputs",usage:"nebutra brand [subcommand]",examples:[{command:"nebutra brand palette --primary=#0047FF",description:"Generate a token-aligned blue palette"}]},{name:"i18n",description:"Manage localization files and multilingual product copy",usage:"nebutra i18n [subcommand]"},{name:"infra",description:"Manage local infrastructure services for Nebutra development",usage:"nebutra infra [subcommand]",examples:[{command:"nebutra infra up --lite",description:"Start lightweight local infrastructure"}]},{name:"env",description:"Validate and manage environment variables across apps and packages",usage:"nebutra env [subcommand]"},{name:"license",description:"Manage Nebutra Sailor commercial license activation and status",usage:"nebutra license [subcommand]",arguments:[],options:[],subcommands:[{name:"activate",description:"Activate a commercial license key for local development",usage:"nebutra license activate <key>",arguments:[{name:"key",description:"Your Nebutra Sailor commercial license key",required:!0}],options:[{flags:"--quiet",description:"Suppress output"}],examples:[{command:"nebutra license activate liz_1234567890",description:"Activate your license key globally"}]},{name:"status",description:"Check the locally configured license status",usage:"nebutra license status",arguments:[],options:[{flags:"--quiet",description:"Suppress output"}],examples:[{command:"nebutra license status",description:"Check if you have an active license"}]}]},{name:"ai",description:"Configure AI providers, gateway routing, and agent-ready defaults",usage:"nebutra ai [subcommand]"},{name:"auth",description:"Configure authentication providers and tenant access defaults",usage:"nebutra auth [subcommand]"},{name:"billing",description:"Manage billing providers, subscriptions, usage, and return flows",usage:"nebutra billing [subcommand]"},{name:"stats",description:"Show monorepo statistics, health signals, and platform inventory",usage:"nebutra stats [options]"},{name:"db",description:"Manage database schema, migrations, seeds, and generated clients",usage:"nebutra db [subcommand]"},{name:"generate",description:"Generate apps, modules, API surfaces, and typed project artifacts",usage:"nebutra generate [type] [name]"},{name:"dev",description:"Start development workflows for selected Nebutra apps or presets",usage:"nebutra dev [options]"},{name:"build",description:"Run build workflows through the Nebutra CLI",usage:"nebutra build [options]"},{name:"lint",description:"Run lint workflows through the Nebutra CLI",usage:"nebutra lint [options]"},{name:"typecheck",description:"Run TypeScript checks through the Nebutra CLI",usage:"nebutra typecheck [options]"},{name:"test",description:"Run unit, architecture, and E2E verification workflows",usage:"nebutra test [scope]"},{name:"workflow",description:"Initialize and inspect workflow runtime adapters",usage:"nebutra workflow [subcommand]"},{name:"backend",description:"Manage backend runtime service workflows",usage:"nebutra backend [subcommand]"},{name:"e2e",description:"Run browser end-to-end verification suites",usage:"nebutra e2e [suite]"},{name:"theme",description:"Inspect registry-backed Nebutra themes and governance metadata",usage:"nebutra theme [subcommand]"},{name:"ui",description:"Search, inspect, validate, and plan migrations for @nebutra/ui components",usage:"nebutra ui [subcommand]"},{name:"admin",description:"Operate tenant, platform health, and administrative workflows",usage:"nebutra admin [subcommand]"},{name:"community",description:"Inspect community health, showcases, and external adoption signals",usage:"nebutra community [subcommand]"},{name:"growth",description:"Analyze product growth, funnels, retention, and lifecycle signals",usage:"nebutra growth [subcommand]"},{name:"ecosystem",description:"Manage template marketplace, ideas, project showcase, and ecosystem sync",usage:"nebutra ecosystem [subcommand]"},{name:"services",description:"Inspect and manage microservice health, logs, scaling, and rollouts",usage:"nebutra services [subcommand]"},{name:"search",description:"Manage search indexes, reindexing, and search diagnostics",usage:"nebutra search [subcommand]"},{name:"secrets",description:"Manage encrypted tenant and platform secrets",usage:"nebutra secrets [subcommand]"},{name:"completions",description:"Generate shell completions for the current Nebutra command surface",usage:"nebutra completions [shell]",arguments:[{name:"shell",description:"Shell to generate completions for: bash, zsh, fish, or install",required:!1}]},{name:"logout",description:"Clear local Nebutra CLI session state",usage:"nebutra logout"},{name:"upgrade",description:"Upgrade local Nebutra CLI tooling",usage:"nebutra upgrade"},{name:"link",description:"Link a local project to Nebutra platform metadata",usage:"nebutra link"},{name:"unlink",description:"Unlink local Nebutra project metadata",usage:"nebutra unlink"},{name:"doctor",description:"Check local project setup and common Nebutra configuration issues",usage:"nebutra doctor"}]};var Vn="nebutra.config.json",xs=b.ai.filter(e=>e!=="none"),Gn={"aws-bedrock":["AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_REGION"],"azure-openai":["AZURE_OPENAI_API_KEY","AZURE_OPENAI_ENDPOINT"],"gcp-vertex":["GOOGLE_APPLICATION_CREDENTIALS","GOOGLE_CLOUD_PROJECT"],"vercel-gateway":["AI_GATEWAY_API_KEY"],"volcengine-ark":["VOLCENGINE_ARK_API_KEY"],bailian:["DASHSCOPE_API_KEY"],litellm:["LITELLM_API_KEY","LITELLM_BASE_URL"],portkey:["PORTKEY_API_KEY"],custom:["AI_CUSTOM_API_KEY","AI_CUSTOM_BASE_URL"]};function ce(e,t,n){if(t==="json"){let r={command:n||"ai",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function Os(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function As(e){return Gn[e]?Gn[e]:[`${e.replace(/-/g,"_").toUpperCase()}_API_KEY`]}function pt(){return Object.fromEntries(xs.map(e=>[e,{id:e,name:Os(e),envVars:As(e)}]))}function ge(){return Mt(process.cwd(),Vn)}function Pe(){let e=ge();if(!Cs(e))return{$schema:"https://nebutra.com/schema.json"};try{return JSON.parse(Es(e,"utf-8"))}catch(t){s.error(`Failed to parse ${Vn}: ${t instanceof Error?t.message:String(t)}`),process.exit(c.ERROR)}}function ft(e){ks(ge(),`${JSON.stringify(e,null,2)}
|
|
123
|
+
`)}function Re(e){return e.ai={providers:{},routes:{},...e.ai},e.ai.providers={...e.ai.providers},e.ai.routes={...e.ai.routes},e.ai}function Kn(e){let t=pt(),n=[...new Set(e.map(o=>o.toLowerCase()))],r=n.filter(o=>!t[o]);return r.length>0&&(s.error(`Unknown AI provider(s): ${r.join(", ")}. Valid providers: ${Object.keys(t).join(", ")}`),process.exit(c.INVALID_ARGS)),n}function _s(e){let t=e?.split(",").map(r=>r.trim()).filter(Boolean)??[];t.length===0&&(s.error("Route fallback cannot be empty. Use --fallback provider:model,provider:model"),process.exit(c.INVALID_ARGS));let n=t.filter(r=>!/^[a-z0-9-]+:[^,\s]+$/i.test(r));return n.length>0&&(s.error(`Invalid fallback target(s): ${n.join(", ")}. Expected provider:model.`),process.exit(c.INVALID_ARGS)),t}function qn(e){let t=Re(e),n=t.providers??{},r=t.routes??{},o=Object.entries(n).filter(([,a])=>a.enabled).map(([a])=>a);return{path:ge(),gateway:t.gateway??null,providers:n,enabledProviders:o,routes:r}}function ie(e){let t=typeof e.opts=="function"?e.opts():e,n=typeof e.optsWithGlobals=="function"?e.optsWithGlobals():t,r=t.format??n.format??Ps();return{...n,...t,...r?{format:r}:{}}}function Ps(){let e=process.argv.find(n=>n.startsWith("--format="));if(e)return e.slice(9);let t=process.argv.indexOf("--format");if(t>=0)return process.argv[t+1]}function Ye(e){return e?e.length<=8?"***":`${e.substring(0,8)}***`:"not set"}async function Is(e){e.format!=="json"&&s.info("Checking configured AI models and providers...");let t={openai:{name:"OpenAI",keyVars:["OPENAI_API_KEY"],configured:!1},anthropic:{name:"Anthropic Claude",keyVars:["ANTHROPIC_API_KEY"],configured:!1},openrouter:{name:"OpenRouter",keyVars:["OPENROUTER_API_KEY"],configured:!1},vercel:{name:"Vercel AI SDK",keyVars:["VERCEL_AI_API_KEY"],configured:!1}};for(let r of Object.values(t))r.configured=r.keyVars.some(o=>process.env[o]);let n={providers:Object.entries(t).map(([r,o])=>({id:r,name:o.name,configured:o.configured,keys:o.keyVars.map(a=>({name:a,value:Ye(process.env[a])}))})),configuredCount:Object.values(t).filter(r=>r.configured).length,totalProviders:Object.keys(t).length};e.dryRun||(n.configuredCount===0?s.warn("No AI providers configured. Set API keys to enable AI features."):s.success(`${n.configuredCount} AI provider(s) configured`)),ce(n,e.format,"ai:models")}async function Ns(e){e.format!=="json"&&s.info("Scanning for available agents...");try{let t=Mt(process.cwd(),"backends/gateway/src/routes/agents"),n=[];try{let o=await import("fs");o.existsSync(t)&&(n=o.readdirSync(t).filter(i=>i.endsWith(".ts")&&!i.endsWith(".d.ts")).map(i=>({name:i.replace(".ts",""),path:`backends/gateway/src/routes/agents/${i}`})))}catch{n=[]}let r={agents:n.length>0?n:[{name:"No agents found",path:"create agents in backends/gateway/src/routes/agents/"}],count:n.length};e.dryRun||(r.count===0?s.info("No agents configured. Create agents in backends/gateway/src/routes/agents/"):s.success(`Found ${r.count} agent(s)`)),ce(r,e.format,"ai:agents")}catch(t){s.error(`Failed to scan agents: ${t instanceof Error?t.message:String(t)}`),process.exit(c.ERROR)}}async function $s(e,t){(!e||e.trim().length===0)&&(s.error("Prompt cannot be empty"),process.exit(c.INVALID_ARGS)),t.format!=="json"&&(s.info("Testing AI prompt against default model..."),s.info("Note: Ensure API gateway is running on http://localhost:3001"));let n={prompt:e,note:"To execute this test, the API gateway must be running locally. Run: pnpm --filter @nebutra/gateway dev",endpoint:"http://localhost:3001/api/ai/test",method:"POST",payload:{prompt:e.substring(0,100)}};t.dryRun||s.warn("AI test execution requires a running API gateway. Start it with: pnpm --filter @nebutra/gateway dev"),ce(n,t.format,"ai:test")}async function Ts(e){e.format!=="json"&&s.info("Checking AI configuration...");let t={providers:{openai:{key:Ye(process.env.OPENAI_API_KEY),configured:!!process.env.OPENAI_API_KEY},anthropic:{key:Ye(process.env.ANTHROPIC_API_KEY),configured:!!process.env.ANTHROPIC_API_KEY},openrouter:{key:Ye(process.env.OPENROUTER_API_KEY),configured:!!process.env.OPENROUTER_API_KEY}},environment:{NODE_ENV:process.env.NODE_ENV||"development",NEBUTRA_LOG_LEVEL:process.env.NEBUTRA_LOG_LEVEL||"info"}};try{let r=Mt(process.cwd(),"nebutra.config.ts"),o=await import("fs");if(o.existsSync(r)){let i=o.readFileSync(r,"utf-8").match(/preset:\s*["']([^"']+)["']/);i&&(t.preset=i[1])}}catch{}let n=Object.entries(t.providers).filter(([,r])=>r.configured).map(([r])=>r);e.dryRun||(n.length===0?s.warn("No AI providers configured. Set environment variables to enable AI features."):s.success(`Configuration loaded: ${n.join(", ")}`)),ce(t,e.format,"ai:config")}async function Us(e){let t=Pe(),n=Re(t),r=pt(),o=Object.values(r).map(i=>{let l=n.providers?.[i.id];return{id:i.id,name:i.name,enabled:l?.enabled===!0,configured:i.envVars.some(u=>!!process.env[u]),envVars:i.envVars.map(u=>({name:u,value:Ye(process.env[u])}))}}),a={configPath:ge(),providers:o,enabledCount:o.filter(i=>i.enabled).length,totalProviders:o.length};if(e.format!=="json"){let i=o.filter(l=>l.enabled);i.length===0?s.warn("No runtime AI providers enabled in nebutra.config.json."):s.success(`Enabled AI providers: ${i.map(l=>l.id).join(", ")}`)}ce(a,e.format,"ai:provider:list")}async function js(e,t){let n=Kn(e),r=Pe(),o=Re(r),a=pt(),i=new Date().toISOString();for(let u of n)o.providers[u]={enabled:!0,envVars:a[u].envVars,enabledAt:o.providers?.[u]?.enabledAt??i};ft(r);let l={configPath:ge(),enabled:n,env:t.env===!0?n.flatMap(u=>a[u].envVars.map(m=>({provider:u,name:m,example:`${m}=`}))):void 0,ai:qn(r)};if(t.format!=="json"&&(s.success(`Enabled AI provider(s): ${n.join(", ")}`),t.env)){s.info("Required environment variables:");for(let u of n)for(let m of a[u].envVars)console.log(`${m}=`)}ce(l,t.format,"ai:provider:enable")}async function Ls(e,t){let n=Kn(e),r=Pe(),o=Re(r),a=pt(),i=new Date().toISOString();for(let u of n)o.providers[u]={enabled:!1,envVars:o.providers?.[u]?.envVars??a[u].envVars,disabledAt:i};ft(r);let l={configPath:ge(),disabled:n,ai:qn(r)};t.format!=="json"&&s.success(`Disabled AI provider(s): ${n.join(", ")}`),ce(l,t.format,"ai:provider:disable")}async function Ds(e){let t=Pe(),n=Re(t),r=new Date().toISOString();n.gateway={enabled:!0,mode:"local",initializedAt:n.gateway?.initializedAt??r,updatedAt:r},ft(t);let o={configPath:ge(),gateway:n.gateway};e.format!=="json"&&s.success("AI gateway governance initialized in nebutra.config.json"),ce(o,e.format,"ai:gateway:init")}async function Fs(e){let t=Pe(),n=Re(t),r={configPath:ge(),gateway:n.gateway??null,initialized:n.gateway?.enabled===!0};e.format!=="json"&&(r.initialized?s.success("AI gateway governance is initialized"):s.warn("AI gateway governance is not initialized. Run: nebutra ai gateway init")),ce(r,e.format,"ai:gateway:status")}async function Bs(e,t){(!e||e.trim().length===0)&&(s.error("Route name cannot be empty"),process.exit(c.INVALID_ARGS)),t.policy||(s.error("Route policy is required. Use --policy <policy>."),process.exit(c.INVALID_ARGS));let n=_s(t.fallback),r=Pe(),o=Re(r);o.routes[e]={policy:t.policy,fallback:n,updatedAt:new Date().toISOString()},ft(r);let a={configPath:ge(),route:{name:e,...o.routes[e]},routes:o.routes};t.format!=="json"&&s.success(`AI route '${e}' set with policy '${t.policy}'`),ce(a,t.format,"ai:route:set")}async function Ms(e){let t=Pe(),n=Re(t),r=Object.entries(n.routes??{}).map(([a,i])=>({name:a,...i})),o={configPath:ge(),routes:r,count:r.length};e.format!=="json"&&(r.length===0?s.warn("No AI routes configured. Run: nebutra ai route set chat --policy cost-latency-balanced --fallback openai:gpt-5.4"):s.success(`Configured AI routes: ${r.map(a=>a.name).join(", ")}`)),ce(o,e.format,"ai:route:list")}function zn(e){let t=e.command("ai").description("Manage AI models, agents, and configuration"),n=t.command("provider").description("Manage runtime AI provider governance");n.command("list").description("List supported and enabled AI providers").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Us({format:i.format,interactive:i.yes!==!0})}),n.command("enable <providers...>").description("Enable one or more runtime AI providers in nebutra.config.json").option("--env","Print required environment variable placeholders").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await js(a,{env:l.env===!0,format:l.format,interactive:l.yes!==!0})}),n.command("disable <providers...>").description("Disable one or more runtime AI providers in nebutra.config.json").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await Ls(a,{format:l.format,interactive:l.yes!==!0})});let r=t.command("gateway").description("Manage local AI gateway governance");r.command("init").description("Initialize the local AI gateway governance block").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ds({format:i.format,interactive:i.yes!==!0})}),r.command("status").description("Show local AI gateway governance status").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Fs({format:i.format,interactive:i.yes!==!0})});let o=t.command("route").description("Manage AI routing policies");o.command("set <name>").description("Create or update an AI route policy").requiredOption("--policy <policy>","Routing policy id").requiredOption("--fallback <list>","Comma-separated provider:model fallback chain").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await Bs(a,{policy:l.policy,fallback:l.fallback,format:l.format,interactive:l.yes!==!0})}),o.command("list").description("List configured AI routes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ms({format:i.format,interactive:i.yes!==!0})}),t.command("models").description("List configured AI models and providers").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Is({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})}),t.command("agents").description("List available agents in the project").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ns({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})}),t.command("test <prompt>").description("Send a test prompt to the default AI model (requires running API gateway)").option("--dry-run","Preview without executing").option("--format <type>","Output format: json or plain").action(async(a,i)=>{let l=ie(i);await $s(a,{dryRun:l.dryRun===!0,format:l.format,interactive:l.yes!==!0})}),t.command("config").description("Show current AI configuration and provider status").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async a=>{let i=ie(a);await Ts({dryRun:i.dryRun===!0,format:i.format,interactive:i.yes!==!0})})}import{resolve as Gs}from"path";function Gt(e,t,n){if(t==="json"){let r={command:n||"auth",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function v(e,t){return e?e.length<=8?"***":`${e.substring(0,8)}*** (${t||e.length} chars)`:"not set"}function Vs(){try{let e=Gs(process.cwd(),"nebutra.config.ts"),t=jo("fs");if(t.existsSync(e)){let n=t.readFileSync(e,"utf-8");if(n.includes("clerk"))return"clerk";if(n.includes("better-auth"))return"better-auth";if(n.includes("nextauth"))return"nextauth";if(n.includes("supabase"))return"supabase"}}catch{}return"clerk"}async function Ks(e){s.info("Checking authentication configuration...");let t=Vs(),n={provider:t,configured:!1,keys:{}};t==="clerk"?(n.keys={CLERK_SECRET_KEY:v(process.env.CLERK_SECRET_KEY,"secret"),NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,"publishable"),CLERK_WEBHOOK_SECRET:v(process.env.CLERK_WEBHOOK_SECRET,"webhook")},n.configured=!!process.env.CLERK_SECRET_KEY&&!!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY):t==="better-auth"?(n.keys={BETTER_AUTH_SECRET:v(process.env.BETTER_AUTH_SECRET,"secret"),BETTER_AUTH_URL:process.env.BETTER_AUTH_URL||"not set"},n.configured=!!process.env.BETTER_AUTH_SECRET):t==="nextauth"?(n.keys={AUTH_SECRET:v(process.env.AUTH_SECRET,"secret"),NEXTAUTH_SECRET:v(process.env.NEXTAUTH_SECRET,"legacy secret"),NEXTAUTH_URL:process.env.NEXTAUTH_URL||"not set",AUTH_URL:process.env.AUTH_URL||"not set",GOOGLE_CLIENT_ID:v(process.env.GOOGLE_CLIENT_ID,"google client"),GITHUB_CLIENT_ID:v(process.env.GITHUB_CLIENT_ID,"github client")},n.configured=!!(process.env.AUTH_SECRET||process.env.NEXTAUTH_SECRET)):(n.keys={NEXT_PUBLIC_SUPABASE_URL:process.env.NEXT_PUBLIC_SUPABASE_URL||"not set",NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,"publishable"),NEXT_PUBLIC_SUPABASE_ANON_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,"anon"),SUPABASE_URL:process.env.SUPABASE_URL||"not set",SUPABASE_PUBLISHABLE_KEY:v(process.env.SUPABASE_PUBLISHABLE_KEY,"publishable"),SUPABASE_ANON_KEY:v(process.env.SUPABASE_ANON_KEY,"anon"),SUPABASE_SERVICE_ROLE_KEY:v(process.env.SUPABASE_SERVICE_ROLE_KEY,"service role"),SUPABASE_WEBHOOK_SECRET:v(process.env.SUPABASE_WEBHOOK_SECRET,"webhook")},n.configured=!!((process.env.SUPABASE_URL||process.env.NEXT_PUBLIC_SUPABASE_URL)&&(process.env.SUPABASE_PUBLISHABLE_KEY||process.env.SUPABASE_ANON_KEY||process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY||process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY)&&process.env.SUPABASE_SERVICE_ROLE_KEY)),e.dryRun||(n.configured?s.success(`Auth provider configured: ${t}`):s.warn(`Auth provider ${t} is not fully configured`)),Gt({...n},e.format,"auth:status")}async function qs(e,t){let n=["clerk","better-auth","nextauth","supabase"];n.includes(e.toLowerCase())||(s.error(`Invalid provider: ${e}. Choose from: ${n.join(", ")}`),process.exit(c.INVALID_ARGS));let r=e.toLowerCase();s.info(`Setting up ${r} authentication...`),r==="clerk"?(s.info("Clerk setup requires:"),s.info("1. A Clerk account (https://clerk.com)"),s.info("2. A Clerk application created"),s.info("3. API keys from the Clerk dashboard"),s.info(""),s.info("To complete setup:"),s.info("1. Go to https://dashboard.clerk.com"),s.info("2. Copy your Secret Key and Publishable Key"),s.info("3. Add them to .env.local:"),s.info(' CLERK_SECRET_KEY="sk_..."'),s.info(' NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_..."'),s.info(""),s.info("Webhook setup (optional):"),s.info("1. In Clerk dashboard, go to Webhooks"),s.info("2. Create endpoint: https://yourdomain.com/api/webhooks/clerk"),s.info("3. Copy the signing secret to .env.local:"),s.info(' CLERK_WEBHOOK_SECRET="whsec_..."')):r==="better-auth"?(s.info("Better Auth setup requires:"),s.info("1. Database URL configured (DATABASE_URL env var)"),s.info("2. A generated auth secret"),s.info(""),s.info("To complete setup:"),s.info("1. Ensure DATABASE_URL is set in .env.local"),s.info("2. Generate a new secret:"),s.info(" openssl rand -base64 32"),s.info("3. Add to .env.local:"),s.info(' BETTER_AUTH_SECRET="<generated_secret>"'),s.info(' BETTER_AUTH_URL="http://localhost:3000"'),s.info(""),s.info("4. Run database migration:"),s.info(" pnpm --filter @nebutra/web db:push")):r==="nextauth"?(s.info("NextAuth / Auth.js setup requires:"),s.info("1. A generated Auth.js secret"),s.info("2. NEXTAUTH_URL or AUTH_URL pointing at the web app origin"),s.info("3. OAuth provider credentials for each enabled provider"),s.info(""),s.info("To complete setup:"),s.info("1. Generate a new secret:"),s.info(" openssl rand -base64 32"),s.info("2. Add to the production environment:"),s.info(' AUTH_PROVIDER="nextauth"'),s.info(' NEXT_PUBLIC_AUTH_PROVIDER="nextauth"'),s.info(' AUTH_SECRET="<generated_secret>"'),s.info(' NEXTAUTH_URL="https://app.nebutra.com"'),s.info(' GOOGLE_CLIENT_ID="..."'),s.info(' GOOGLE_CLIENT_SECRET="..."')):(s.info("Supabase Auth setup requires:"),s.info("1. Supabase project URL"),s.info("2. Public anon key for browser auth"),s.info("3. Service role key for server-side user/session validation"),s.info(""),s.info("To complete setup:"),s.info(' AUTH_PROVIDER="supabase"'),s.info(' NEXT_PUBLIC_AUTH_PROVIDER="supabase"'),s.info(' NEXT_PUBLIC_SUPABASE_URL="https://xxx.supabase.co"'),s.info(' NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY="sb_publishable_..."'),s.info(' NEXT_PUBLIC_SUPABASE_ANON_KEY="..."'),s.info(' SUPABASE_URL="https://xxx.supabase.co"'),s.info(' SUPABASE_PUBLISHABLE_KEY="sb_publishable_..."'),s.info(' SUPABASE_ANON_KEY="..."'),s.info(' SUPABASE_SERVICE_ROLE_KEY="..."')),t.dryRun||s.success(`Setup instructions for ${r} displayed above`),Gt({provider:r,setupGuide:"Complete setup by following the instructions above",documentationUrl:r==="clerk"?"https://clerk.com/docs":r==="better-auth"?"https://www.better-auth.com":r==="nextauth"?"https://authjs.dev":"https://supabase.com/docs/guides/auth"},t.format,"auth:setup")}async function zs(e){s.info("Checking authentication keys and secrets...");let n={keys:{clerk:{CLERK_SECRET_KEY:v(process.env.CLERK_SECRET_KEY,"secret key"),NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,"publishable key"),CLERK_WEBHOOK_SECRET:v(process.env.CLERK_WEBHOOK_SECRET,"webhook secret")},betterAuth:{BETTER_AUTH_SECRET:v(process.env.BETTER_AUTH_SECRET,"secret"),BETTER_AUTH_URL:process.env.BETTER_AUTH_URL||"not set"},nextAuth:{AUTH_SECRET:v(process.env.AUTH_SECRET,"secret"),NEXTAUTH_SECRET:v(process.env.NEXTAUTH_SECRET,"legacy secret"),NEXTAUTH_URL:process.env.NEXTAUTH_URL||"not set",AUTH_URL:process.env.AUTH_URL||"not set",GOOGLE_CLIENT_ID:v(process.env.GOOGLE_CLIENT_ID,"google client"),GITHUB_CLIENT_ID:v(process.env.GITHUB_CLIENT_ID,"github client")},supabase:{NEXT_PUBLIC_SUPABASE_URL:process.env.NEXT_PUBLIC_SUPABASE_URL||"not set",NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY,"publishable"),NEXT_PUBLIC_SUPABASE_ANON_KEY:v(process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,"anon"),SUPABASE_URL:process.env.SUPABASE_URL||"not set",SUPABASE_PUBLISHABLE_KEY:v(process.env.SUPABASE_PUBLISHABLE_KEY,"publishable"),SUPABASE_ANON_KEY:v(process.env.SUPABASE_ANON_KEY,"anon"),SUPABASE_SERVICE_ROLE_KEY:v(process.env.SUPABASE_SERVICE_ROLE_KEY,"service role")},common:{DATABASE_URL:v(process.env.DATABASE_URL,"database url"),JWT_SECRET:v(process.env.JWT_SECRET,"jwt secret")}},configured:{clerk:{secret:!!process.env.CLERK_SECRET_KEY,publishable:!!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY},betterAuth:{secret:!!process.env.BETTER_AUTH_SECRET,url:!!process.env.BETTER_AUTH_URL},nextAuth:{secret:!!(process.env.AUTH_SECRET||process.env.NEXTAUTH_SECRET),url:!!(process.env.NEXTAUTH_URL||process.env.AUTH_URL)},supabase:{url:!!(process.env.SUPABASE_URL||process.env.NEXT_PUBLIC_SUPABASE_URL),publishableKey:!!(process.env.SUPABASE_PUBLISHABLE_KEY||process.env.SUPABASE_ANON_KEY||process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY||process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY),serviceRole:!!process.env.SUPABASE_SERVICE_ROLE_KEY}}};if(!e.dryRun){let r=n.configured.clerk.secret&&n.configured.clerk.publishable,o=n.configured.betterAuth.secret&&n.configured.betterAuth.url,a=n.configured.nextAuth.secret&&n.configured.nextAuth.url,i=n.configured.supabase.url&&n.configured.supabase.publishableKey&&n.configured.supabase.serviceRole;!r&&!o&&!a&&!i?s.warn("No authentication keys configured"):(s.info("Auth keys status:"),r&&s.success("Clerk configured"),o&&s.success("Better Auth configured"),a&&s.success("NextAuth configured"),i&&s.success("Supabase configured"))}Gt(n,e.format,"auth:keys")}function Yn(e){let t=e.command("auth").description("Manage authentication configuration (Clerk, Better Auth, NextAuth, or Supabase)");t.command("status").description("Check current authentication provider configuration").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await Ks({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("setup <provider>").description("Configure Clerk, Better Auth, NextAuth, or Supabase (interactive wizard)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async(n,r)=>{let o=r.optsWithGlobals?.()||r;await qs(n,{dryRun:r.dryRun||!1,format:r.format||o.format,interactive:o.yes!==!0})}),t.command("keys").description("Show authentication-related environment variables (masked)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await zs({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}import Ce from"fs";import le from"path";import*as gt from"@clack/prompts";import Jn from"picocolors";function x(e,t){let n=typeof e.optsWithGlobals=="function"?e.optsWithGlobals():void 0;return{...t&&typeof t.optsWithGlobals=="function"?t.optsWithGlobals():void 0,...n,...e}}var Hn=["ts","py"],Ys=`{
|
|
124
124
|
"name": "@nebutra/gateway",
|
|
125
125
|
"version": "0.1.0",
|
|
126
126
|
"private": true,
|
|
@@ -205,14 +205,14 @@ async def healthz() -> HealthResponse:
|
|
|
205
205
|
return HealthResponse(status="ok")
|
|
206
206
|
`;async function Zs(e,t){let n=le.join(e,"backends/gateway");Ce.existsSync(n)&&(s.info(`backends/gateway already exists in this monorepo \u2014 nothing to do.
|
|
207
207
|
(This command is primarily for downstream consumers using create-sailor.)`),process.exit(c.SUCCESS)),t.dryRun&&(process.stdout.write(JSON.stringify({mode:"dry-run",command:"backend init ts",files:["backends/gateway/package.json","backends/gateway/src/index.ts","backends/gateway/README.md"]},null,2)+`
|
|
208
|
-
`),process.exit(c.DRY_RUN_OK)),Ce.mkdirSync(le.join(n,"src"),{recursive:!0}),Ce.writeFileSync(le.join(n,"package.json"),Ys),Ce.writeFileSync(le.join(n,"src/index.ts"),Hs),Ce.writeFileSync(le.join(n,"README.md"),Ws),s.success("Created backends/gateway scaffold"),process.exit(c.SUCCESS)}function Wn(e){return/^[a-z][a-z0-9_-]{0,40}$/.test(e)}async function ea(e,t){let n=t.name,r=process.stdout.isTTY===!0&&!t.yes;if(!n&&r){let i=await
|
|
209
|
-
`),process.exit(c.DRY_RUN_OK));for(let[i,l]of a)Ce.mkdirSync(le.dirname(i),{recursive:!0}),Ce.writeFileSync(i,l);s.success(`Created backends/python/${n} scaffold`),s.info("Update README.md to cite which ADR justification applies (batch | ML | specialized libs)."),process.exit(c.SUCCESS)}async function ta(e,t={}){Hn.includes(e)||(s.error(`Invalid runtime: ${Jn.red(e)}. Valid: ${Hn.join(", ")}`),process.exit(c.INVALID_ARGS));let n=h();e==="ts"?await Zs(n,t):await ea(n,t)}var Xn=e=>{e.command("backend").description("Scaffold backend services (ts | py)").command("init <runtime>").description("Scaffold a backend service (runtime: ts | py)").option("--name <name>","Service name (Python only; prompted if omitted)").option("--dry-run","Preview files that would be created (exit code 10)").action(async(n,r,o)=>{let a=x(r,o);await ta(n,{name:typeof r.name=="string"?r.name:void 0,dryRun:!!r.dryRun,yes:!!a.yes,quiet:!!a.quiet})})};function qt(e,t,n){if(t==="json"){let r={command:n||"billing",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function na(e,t){return e?e.length<=8?"***":`${e.substring(0,8)}*** (${t||e.length} chars)`:"not set"}var bt={stripe:{name:"Stripe",keyVars:["STRIPE_SECRET_KEY","STRIPE_PUBLISHABLE_KEY"],webhookUrl:"/api/webhooks/stripe",setupUrl:"https://dashboard.stripe.com"},lemonsqueezy:{name:"Lemon Squeezy",keyVars:["LEMONSQUEEZY_API_KEY"],webhookUrl:"/api/webhooks/lemonsqueezy",setupUrl:"https://app.lemonsqueezy.com/settings/api"},polar:{name:"Polar",keyVars:["POLAR_ACCESS_TOKEN"],webhookUrl:"/api/webhooks/polar",setupUrl:"https://app.polar.sh/settings/api"},chinapay:{name:"ChinaPay",keyVars:["CHINAPAY_MERCHANT_ID","CHINAPAY_SECRET_KEY"],webhookUrl:"/api/webhooks/chinapay",setupUrl:"https://www.chinapay.com"}};async function ra(e){s.info("Checking payment provider configuration...");let t=Object.entries(bt).map(([o,a])=>{let i=a.keyVars.every(l=>process.env[l]);return{id:o,name:a.name,configured:i,keys:a.keyVars.map(l=>({name:l,value:na(process.env[l],"key")}))}}),n=t.filter(o=>o.configured),r={providers:t,configuredCount:n.length,totalProviders:t.length,configuredList:n.map(o=>o.name)};e.dryRun||(r.configuredCount===0?s.warn("No payment providers configured. Set API keys to enable billing."):s.success(`${r.configuredCount} payment provider(s) configured`)),qt(r,e.format,"billing:status")}async function oa(e,t){let n=Object.keys(bt);n.includes(e.toLowerCase())||(s.error(`Invalid provider: ${e}. Choose from: ${n.join(", ")}`),process.exit(c.INVALID_ARGS));let r=e.toLowerCase(),o=bt[r];s.info(`Setting up ${o.name} payment provider...`),s.info(""),s.info("Setup steps:"),s.info(`1. Go to ${o.setupUrl}`),s.info("2. Create or log in to your account"),s.info("3. Generate API credentials"),s.info("4. Add the following to .env.local:"),s.info(""),o.keyVars.forEach(i=>{s.info(` ${i}="<your_${i.toLowerCase()}>"`.padStart(45))}),s.info(""),s.info("5. (Optional) Configure webhook in provider dashboard:"),s.info(` Webhook URL: https://yourdomain.com${o.webhookUrl}`),t.dryRun||s.success(`Setup instructions for ${o.name} displayed above`);let a={provider:r,name:o.name,requiredKeys:o.keyVars,webhookUrl:o.webhookUrl,setupGuide:"Follow the instructions above to complete setup",documentationUrl:o.setupUrl};qt(a,t.format,"billing:setup")}async function sa(e){s.info("Checking billing webhook configuration...");let t=process.env.NEXT_PUBLIC_APP_URL||"https://yourdomain.com",n=Object.entries(bt).map(([o,a])=>({provider:o,name:a.name,url:`${t}${a.webhookUrl}`,endpoint:a.webhookUrl,configured:a.keyVars.every(i=>process.env[i])})),r={baseUrl:t,webhooks:n,configurationSteps:["1. Set NEXT_PUBLIC_APP_URL in .env.local to your domain","2. Copy the webhook URL for each provider","3. Configure in the provider's dashboard","4. Ensure the API key is also set"]};e.dryRun||(s.info("Webhook endpoints:"),n.forEach(o=>{o.configured?s.success(`${o.name}: configured`):s.warn(`${o.name}: not configured (missing API key)`)})),qt(r,e.format,"billing:webhooks")}function Qn(e){let t=e.command("billing").description("Manage payment providers and billing configuration");t.command("status").description("Check which payment providers are configured").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ra({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("setup <provider>").description("Configure payment provider (Stripe, Lemon Squeezy, Polar, or ChinaPay)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async(n,r)=>{let o=r.optsWithGlobals?.()||r;await oa(n,{dryRun:r.dryRun||!1,format:r.format||o.format,interactive:o.yes!==!0})}),t.command("webhooks").description("Show webhook endpoints for each payment provider").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await sa({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}function We(e,t,n){if(t==="json"){let r={command:n||"brand",exitCode:e.exitCode,success:e.exitCode===0,...e.stdout&&{stdout:e.stdout},...e.stderr&&{stderr:e.stderr}};console.log(JSON.stringify(r,null,2))}else e.stdout&&console.log(e.stdout),e.stderr&&e.exitCode!==0&&console.error(e.stderr)}function Zn(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}async function aa(e){s.info("Initializing brand system...");let t=await z("brand:init",{dryRun:e.dryRun,interactive:e.interactive??!0});We(t,e.format,"brand:init"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand system initialized successfully")}async function ia(e){s.info("Applying brand configuration...");let t=await z("brand:apply",{dryRun:e.dryRun,interactive:e.interactive??!0});We(t,e.format,"brand:apply"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand applied successfully")}async function ca(e){let t=[];e.primary&&(Zn(e.primary)||(s.error(`Invalid primary color format: ${e.primary}. Expected hex format like #0033FE`),process.exit(c.INVALID_ARGS)),t.push(`--primary=${e.primary}`)),e.secondary&&(Zn(e.secondary)||(s.error(`Invalid secondary color format: ${e.secondary}. Expected hex format like #0BF1C3`),process.exit(c.INVALID_ARGS)),t.push(`--secondary=${e.secondary}`)),t.length===0&&(s.warn("No colors specified. Usage: nebutra brand palette --primary=#HEX --secondary=#HEX"),s.info("Example: nebutra brand palette --primary=#0033FE --secondary=#0BF1C3"),process.exit(c.INVALID_ARGS)),s.info(`Generating color palette: ${t.join(" ")}`);let n=await O({command:"node",args:["scripts/generate-palette.mjs",...t],dryRun:e.dryRun,interactive:e.interactive??!0,label:"Generate brand palette"});We(n,e.format,"brand:palette"),n.exitCode!==0&&process.exit(n.exitCode),e.dryRun||s.success("Color palette generated successfully")}async function la(e){s.info("Syncing brand tokens across packages...");let t=await z("brand:sync",{dryRun:e.dryRun,interactive:e.interactive??!0});We(t,e.format,"brand:sync"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand tokens synced successfully")}async function da(e){s.info("Verifying brand token consistency...");let t=await z("brand:verify-tokens",{dryRun:e.dryRun,interactive:e.interactive??!0});We(t,e.format,"brand:verify-tokens"),t.exitCode!==0&&(s.error("Brand token verification failed. There are inconsistencies in your design tokens."),process.exit(t.exitCode)),e.dryRun||s.success("All brand tokens are consistent")}function er(e){let t=e.command("brand").description("Manage Nebutra brand system and design tokens");t.command("init").description("Initialize brand system configuration").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await aa({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("apply").description("Apply brand configuration to the project").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ia({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("palette").description("Generate brand color palette from custom colors").option("--primary <hex>","Primary brand color (hex format, e.g. #0033FE)").option("--secondary <hex>","Secondary brand color (hex format, e.g. #0BF1C3)").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ca({primary:n.primary,secondary:n.secondary,dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("sync").description("Synchronize brand tokens across all packages").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await la({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("verify").description("Verify brand token consistency across the project").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await da({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}import be from"picocolors";var ua=process.env.NEBUTRA_API_URL||"http://localhost:3001/api";function ee(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&!Array.isArray(t)?t:{}):[]}function ma(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r=="number"&&(t[n]=r);return t}async function j(e,t={}){let n=`${ua}${e}`,r=await fetch(n,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${process.env.NEBUTRA_ADMIN_TOKEN||""}`,...t.headers}});if(!r.ok){let a=await r.text().catch(()=>r.statusText);throw new Error(`API Error (${r.status}): ${a}`)}let o=await r.json();return o&&typeof o=="object"&&!Array.isArray(o)?o:{value:o}}function pa(e){let t={dau_retention:.25,engagement_rate:.25,content_velocity:.2,response_time:.15,member_retention:.15},n={},r=0;for(let[o,a]of Object.entries(t)){let i=Math.min(100,(e[o]||0)*100);n[o]=i,r+=i*a}return{score:Math.round(r),breakdown:n}}async function fa(e){try{s.info("Fetching showcase submissions...");let t=new URLSearchParams;e.status&&t.append("status",e.status),e.category&&t.append("category",e.category);let n=await j(`/community/showcase?${t.toString()}`);if(ee(n.submissions).length===0)return s.warn("No showcase submissions found"),c.SUCCESS;s.info(`
|
|
208
|
+
`),process.exit(c.DRY_RUN_OK)),Ce.mkdirSync(le.join(n,"src"),{recursive:!0}),Ce.writeFileSync(le.join(n,"package.json"),Ys),Ce.writeFileSync(le.join(n,"src/index.ts"),Hs),Ce.writeFileSync(le.join(n,"README.md"),Ws),s.success("Created backends/gateway scaffold"),process.exit(c.SUCCESS)}function Wn(e){return/^[a-z][a-z0-9_-]{0,40}$/.test(e)}async function ea(e,t){let n=t.name,r=process.stdout.isTTY===!0&&!t.yes;if(!n&&r){let i=await gt.text({message:"Service name (lowercase, hyphens or underscores):",placeholder:"translator",validate:l=>Wn(l)?void 0:"Invalid name"});gt.isCancel(i)&&(s.warn("Cancelled."),process.exit(c.CANCELLED)),n=i}n||(s.error("Missing --name. Required in non-interactive mode."),process.exit(c.INVALID_ARGS)),Wn(n)||(s.error(`Invalid name: ${Jn.red(n)}. Use lowercase letters, digits, hyphen, underscore.`),process.exit(c.INVALID_ARGS));let o=le.join(e,"backends/python",n);Ce.existsSync(o)&&(s.error(`backends/python/${n} already exists \u2014 refusing to overwrite.`),process.exit(c.CONFLICT));let a=[[le.join(o,"pyproject.toml"),Js(n)],[le.join(o,"README.md"),Xs(n)],[le.join(o,"src/main.py"),Qs],[le.join(o,"src/__init__.py"),""]];t.dryRun&&(process.stdout.write(JSON.stringify({mode:"dry-run",command:`backend init py --name ${n}`,files:a.map(([i])=>i)},null,2)+`
|
|
209
|
+
`),process.exit(c.DRY_RUN_OK));for(let[i,l]of a)Ce.mkdirSync(le.dirname(i),{recursive:!0}),Ce.writeFileSync(i,l);s.success(`Created backends/python/${n} scaffold`),s.info("Update README.md to cite which ADR justification applies (batch | ML | specialized libs)."),process.exit(c.SUCCESS)}async function ta(e,t={}){Hn.includes(e)||(s.error(`Invalid runtime: ${Jn.red(e)}. Valid: ${Hn.join(", ")}`),process.exit(c.INVALID_ARGS));let n=h();e==="ts"?await Zs(n,t):await ea(n,t)}var Xn=e=>{e.command("backend").description("Scaffold backend services (ts | py)").command("init <runtime>").description("Scaffold a backend service (runtime: ts | py)").option("--name <name>","Service name (Python only; prompted if omitted)").option("--dry-run","Preview files that would be created (exit code 10)").action(async(n,r,o)=>{let a=x(r,o);await ta(n,{name:typeof r.name=="string"?r.name:void 0,dryRun:!!r.dryRun,yes:!!a.yes,quiet:!!a.quiet})})};function Vt(e,t,n){if(t==="json"){let r={command:n||"billing",...e&&typeof e=="object"&&"exitCode"in e?{exitCode:e.exitCode}:{},...e};console.log(JSON.stringify(r,null,2))}else e&&typeof e=="object"&&"stdout"in e&&e.stdout&&console.log(e.stdout),e&&typeof e=="object"&&"stderr"in e&&e.stderr&&(e.exitCode??0)!==0&&console.error(e.stderr)}function na(e,t){return e?e.length<=8?"***":`${e.substring(0,8)}*** (${t||e.length} chars)`:"not set"}var yt={stripe:{name:"Stripe",keyVars:["STRIPE_SECRET_KEY","STRIPE_PUBLISHABLE_KEY"],webhookUrl:"/api/webhooks/stripe",setupUrl:"https://dashboard.stripe.com"},lemonsqueezy:{name:"Lemon Squeezy",keyVars:["LEMONSQUEEZY_API_KEY"],webhookUrl:"/api/webhooks/lemonsqueezy",setupUrl:"https://app.lemonsqueezy.com/settings/api"},polar:{name:"Polar",keyVars:["POLAR_ACCESS_TOKEN"],webhookUrl:"/api/webhooks/polar",setupUrl:"https://app.polar.sh/settings/api"},chinapay:{name:"ChinaPay",keyVars:["CHINAPAY_MERCHANT_ID","CHINAPAY_SECRET_KEY"],webhookUrl:"/api/webhooks/chinapay",setupUrl:"https://www.chinapay.com"}};async function ra(e){s.info("Checking payment provider configuration...");let t=Object.entries(yt).map(([o,a])=>{let i=a.keyVars.every(l=>process.env[l]);return{id:o,name:a.name,configured:i,keys:a.keyVars.map(l=>({name:l,value:na(process.env[l],"key")}))}}),n=t.filter(o=>o.configured),r={providers:t,configuredCount:n.length,totalProviders:t.length,configuredList:n.map(o=>o.name)};e.dryRun||(r.configuredCount===0?s.warn("No payment providers configured. Set API keys to enable billing."):s.success(`${r.configuredCount} payment provider(s) configured`)),Vt(r,e.format,"billing:status")}async function oa(e,t){let n=Object.keys(yt);n.includes(e.toLowerCase())||(s.error(`Invalid provider: ${e}. Choose from: ${n.join(", ")}`),process.exit(c.INVALID_ARGS));let r=e.toLowerCase(),o=yt[r];s.info(`Setting up ${o.name} payment provider...`),s.info(""),s.info("Setup steps:"),s.info(`1. Go to ${o.setupUrl}`),s.info("2. Create or log in to your account"),s.info("3. Generate API credentials"),s.info("4. Add the following to .env.local:"),s.info(""),o.keyVars.forEach(i=>{s.info(` ${i}="<your_${i.toLowerCase()}>"`.padStart(45))}),s.info(""),s.info("5. (Optional) Configure webhook in provider dashboard:"),s.info(` Webhook URL: https://yourdomain.com${o.webhookUrl}`),t.dryRun||s.success(`Setup instructions for ${o.name} displayed above`);let a={provider:r,name:o.name,requiredKeys:o.keyVars,webhookUrl:o.webhookUrl,setupGuide:"Follow the instructions above to complete setup",documentationUrl:o.setupUrl};Vt(a,t.format,"billing:setup")}async function sa(e){s.info("Checking billing webhook configuration...");let t=process.env.NEXT_PUBLIC_APP_URL||"https://yourdomain.com",n=Object.entries(yt).map(([o,a])=>({provider:o,name:a.name,url:`${t}${a.webhookUrl}`,endpoint:a.webhookUrl,configured:a.keyVars.every(i=>process.env[i])})),r={baseUrl:t,webhooks:n,configurationSteps:["1. Set NEXT_PUBLIC_APP_URL in .env.local to your domain","2. Copy the webhook URL for each provider","3. Configure in the provider's dashboard","4. Ensure the API key is also set"]};e.dryRun||(s.info("Webhook endpoints:"),n.forEach(o=>{o.configured?s.success(`${o.name}: configured`):s.warn(`${o.name}: not configured (missing API key)`)})),Vt(r,e.format,"billing:webhooks")}function Qn(e){let t=e.command("billing").description("Manage payment providers and billing configuration");t.command("status").description("Check which payment providers are configured").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ra({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("setup <provider>").description("Configure payment provider (Stripe, Lemon Squeezy, Polar, or ChinaPay)").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async(n,r)=>{let o=r.optsWithGlobals?.()||r;await oa(n,{dryRun:r.dryRun||!1,format:r.format||o.format,interactive:o.yes!==!0})}),t.command("webhooks").description("Show webhook endpoints for each payment provider").option("--dry-run","Preview without making changes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await sa({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}function He(e,t,n){if(t==="json"){let r={command:n||"brand",exitCode:e.exitCode,success:e.exitCode===0,...e.stdout&&{stdout:e.stdout},...e.stderr&&{stderr:e.stderr}};console.log(JSON.stringify(r,null,2))}else e.stdout&&console.log(e.stdout),e.stderr&&e.exitCode!==0&&console.error(e.stderr)}function Zn(e){return/^#[0-9A-Fa-f]{6}$/.test(e)}async function aa(e){s.info("Initializing brand system...");let t=await z("brand:init",{dryRun:e.dryRun,interactive:e.interactive??!0});He(t,e.format,"brand:init"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand system initialized successfully")}async function ia(e){s.info("Applying brand configuration...");let t=await z("brand:apply",{dryRun:e.dryRun,interactive:e.interactive??!0});He(t,e.format,"brand:apply"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand applied successfully")}async function ca(e){let t=[];e.primary&&(Zn(e.primary)||(s.error(`Invalid primary color format: ${e.primary}. Expected hex format like #0033FE`),process.exit(c.INVALID_ARGS)),t.push(`--primary=${e.primary}`)),e.secondary&&(Zn(e.secondary)||(s.error(`Invalid secondary color format: ${e.secondary}. Expected hex format like #0BF1C3`),process.exit(c.INVALID_ARGS)),t.push(`--secondary=${e.secondary}`)),t.length===0&&(s.warn("No colors specified. Usage: nebutra brand palette --primary=#HEX --secondary=#HEX"),s.info("Example: nebutra brand palette --primary=#0033FE --secondary=#0BF1C3"),process.exit(c.INVALID_ARGS)),s.info(`Generating color palette: ${t.join(" ")}`);let n=await O({command:"node",args:["scripts/generate-palette.mjs",...t],dryRun:e.dryRun,interactive:e.interactive??!0,label:"Generate brand palette"});He(n,e.format,"brand:palette"),n.exitCode!==0&&process.exit(n.exitCode),e.dryRun||s.success("Color palette generated successfully")}async function la(e){s.info("Syncing brand tokens across packages...");let t=await z("brand:sync",{dryRun:e.dryRun,interactive:e.interactive??!0});He(t,e.format,"brand:sync"),t.exitCode!==0&&process.exit(t.exitCode),e.dryRun||s.success("Brand tokens synced successfully")}async function da(e){s.info("Verifying brand token consistency...");let t=await z("brand:verify-tokens",{dryRun:e.dryRun,interactive:e.interactive??!0});He(t,e.format,"brand:verify-tokens"),t.exitCode!==0&&(s.error("Brand token verification failed. There are inconsistencies in your design tokens."),process.exit(t.exitCode)),e.dryRun||s.success("All brand tokens are consistent")}function er(e){let t=e.command("brand").description("Manage Nebutra brand system and design tokens");t.command("init").description("Initialize brand system configuration").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await aa({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("apply").description("Apply brand configuration to the project").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ia({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("palette").description("Generate brand color palette from custom colors").option("--primary <hex>","Primary brand color (hex format, e.g. #0033FE)").option("--secondary <hex>","Secondary brand color (hex format, e.g. #0BF1C3)").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ca({primary:n.primary,secondary:n.secondary,dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("sync").description("Synchronize brand tokens across all packages").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await la({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("verify").description("Verify brand token consistency across the project").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await da({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})})}import be from"picocolors";var ua=process.env.NEBUTRA_API_URL||"http://localhost:3001/api";function ee(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"&&!Array.isArray(t)?t:{}):[]}function ma(e){if(!e||typeof e!="object"||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r=="number"&&(t[n]=r);return t}async function j(e,t={}){let n=`${ua}${e}`,r=await fetch(n,{...t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${process.env.NEBUTRA_ADMIN_TOKEN||""}`,...t.headers}});if(!r.ok){let a=await r.text().catch(()=>r.statusText);throw new Error(`API Error (${r.status}): ${a}`)}let o=await r.json();return o&&typeof o=="object"&&!Array.isArray(o)?o:{value:o}}function pa(e){let t={dau_retention:.25,engagement_rate:.25,content_velocity:.2,response_time:.15,member_retention:.15},n={},r=0;for(let[o,a]of Object.entries(t)){let i=Math.min(100,(e[o]||0)*100);n[o]=i,r+=i*a}return{score:Math.round(r),breakdown:n}}async function fa(e){try{s.info("Fetching showcase submissions...");let t=new URLSearchParams;e.status&&t.append("status",e.status),e.category&&t.append("category",e.category);let n=await j(`/community/showcase?${t.toString()}`);if(ee(n.submissions).length===0)return s.warn("No showcase submissions found"),c.SUCCESS;s.info(`
|
|
210
210
|
Showcase Submissions (${ee(n.submissions).length})
|
|
211
211
|
`);for(let r of ee(n.submissions));return c.SUCCESS}catch(t){return s.error(`Failed to list showcase: ${t.message}`),c.ERROR}}async function ga(e,t){try{if(!t.yes)return s.warn(`Approve showcase submission ${e}? Use --yes to confirm`),c.SUCCESS;s.info(`Approving showcase submission ${e}...`);let n=await j(`/community/showcase/${e}/approve`,{method:"POST"});return s.success(`Approved: ${n.title}`),c.SUCCESS}catch(n){return s.error(`Failed to approve showcase: ${n.message}`),c.ERROR}}async function ya(e,t){try{if(!t.yes)return s.warn(`Reject showcase submission ${e}? Use --yes to confirm`),c.SUCCESS;let n=t.reason||"Does not meet guidelines";s.info(`Rejecting showcase submission ${e}...`);let r=await j(`/community/showcase/${e}/reject`,{method:"POST",body:JSON.stringify({reason:n})});return s.success(`Rejected: ${r.title}`),c.SUCCESS}catch(n){return s.error(`Failed to reject showcase: ${n.message}`),c.ERROR}}async function ha(e,t){try{if(!t.yes)return s.warn(`Mark showcase as featured: ${e}? Use --yes to confirm`),c.SUCCESS;s.info(`Featuring showcase submission ${e}...`);let n=await j(`/community/showcase/${e}/feature`,{method:"POST"});return s.success(`Featured: ${n.title}`),c.SUCCESS}catch(n){return s.error(`Failed to feature showcase: ${n.message}`),c.ERROR}}async function ba(e){try{s.info("Fetching showcase statistics...");let t=await j("/community/showcase/stats");return s.info(`
|
|
212
212
|
Showcase Statistics
|
|
213
213
|
`),c.SUCCESS}catch(t){return s.error(`Failed to fetch showcase stats: ${t.message}`),c.ERROR}}async function va(e){try{s.info("Fetching community content...");let t=new URLSearchParams;e.status&&t.append("status",e.status),e.type&&t.append("type",e.type);let n=await j(`/community/content?${t.toString()}`);if(ee(n.items).length===0)return s.warn("No content found"),c.SUCCESS;s.info(`
|
|
214
214
|
Community Content (${ee(n.items).length})
|
|
215
|
-
`);for(let r of ee(n.items));return c.SUCCESS}catch(t){return s.error(`Failed to list content: ${t.message}`),c.ERROR}}async function wa(e,t){try{let n=["approve","flag","archive","delete"];if(!t.action||!n.includes(t.action))return s.error(`Invalid action. Must be one of: ${n.join(", ")}`),c.ERROR;if(!t.yes)return s.warn(`${t.action} content ${e}? Use --yes to confirm`),c.SUCCESS;s.info(`Moderating content ${e} (${t.action})...`);let r=await j(`/community/content/${e}/moderate`,{method:"POST",body:JSON.stringify({action:t.action})});return s.success(`Content ${t.action}d: ${r.title}`),c.SUCCESS}catch(n){return s.error(`Failed to moderate content: ${n.message}`),c.ERROR}}async function
|
|
215
|
+
`);for(let r of ee(n.items));return c.SUCCESS}catch(t){return s.error(`Failed to list content: ${t.message}`),c.ERROR}}async function wa(e,t){try{let n=["approve","flag","archive","delete"];if(!t.action||!n.includes(t.action))return s.error(`Invalid action. Must be one of: ${n.join(", ")}`),c.ERROR;if(!t.yes)return s.warn(`${t.action} content ${e}? Use --yes to confirm`),c.SUCCESS;s.info(`Moderating content ${e} (${t.action})...`);let r=await j(`/community/content/${e}/moderate`,{method:"POST",body:JSON.stringify({action:t.action})});return s.success(`Content ${t.action}d: ${r.title}`),c.SUCCESS}catch(n){return s.error(`Failed to moderate content: ${n.message}`),c.ERROR}}async function Sa(e,t){try{if(!t.yes)return s.warn(`Publish content ${e}? Use --yes to confirm`),c.SUCCESS;s.info(`Publishing content ${e}...`);let n=await j(`/community/content/${e}/publish`,{method:"POST"});return s.success(`Published: ${n.title}`),c.SUCCESS}catch(n){return s.error(`Failed to publish content: ${n.message}`),c.ERROR}}async function Ra(e){try{s.info("Fetching content analytics...");let t=await j("/community/content/analytics");s.info(`
|
|
216
216
|
Content Performance Metrics
|
|
217
217
|
`);for(let n of ee(t.topContent).slice(0,5));return e.format,c.SUCCESS}catch(t){return s.error(`Failed to fetch analytics: ${t.message}`),c.ERROR}}async function Ca(e){try{s.info("Fetching community members...");let t=new URLSearchParams;e.role&&t.append("role",e.role),e.sort&&t.append("sort",e.sort);let n=await j(`/community/members?${t.toString()}`);if(ee(n.members).length===0)return s.warn("No members found"),c.SUCCESS;s.info(`
|
|
218
218
|
Community Members (${ee(n.members).length})
|
|
@@ -224,13 +224,13 @@ Community Health Report (${t}) \u2014 score ${r}
|
|
|
224
224
|
Moderation Queue (${ee(t.items).length} pending)
|
|
225
225
|
`);for(let n of ee(t.items)){let o={low:be.gray("\u25CF"),medium:be.yellow("\u25CF"),high:be.red("\u25CF")}[String(n.severity)]??"\u25CF"}return c.SUCCESS}catch(t){return s.error(`Failed to fetch queue: ${t.message}`),c.ERROR}}async function Pa(e){try{s.info("Running AI-assisted moderation sweep..."),e.dryRun&&s.warn("DRY RUN MODE - no changes will be made");let t=await j("/community/moderation/auto",{method:"POST",body:JSON.stringify({dryRun:e.dryRun||!1})});return s.info(`
|
|
226
226
|
Moderation Results
|
|
227
|
-
`),e.dryRun?s.info("DRY RUN COMPLETE - no changes committed"):s.success("Moderation sweep complete"),c.SUCCESS}catch(t){return s.error(`Failed to run moderation: ${t.message}`),c.ERROR}}function tr(e){let t=e.command("community").description("Manage Nebutra-Sailor community dimension"),n=t.command("showcase").description("Project showcase management");n.command("list").description("List submitted projects").option("--status <status>","Filter by status (pending|approved|rejected|featured)").option("--category <category>","Filter by category").action(i=>fa(i).then(process.exit)),n.command("approve <id>").description("Approve a showcase submission").option("--yes","Skip confirmation").action((i,l)=>ga(i,l).then(process.exit)),n.command("reject <id>").description("Reject a showcase submission").option("--reason <text>","Rejection reason").option("--yes","Skip confirmation").action((i,l)=>ya(i,l).then(process.exit)),n.command("feature <id>").description("Mark as featured").option("--yes","Skip confirmation").action((i,l)=>ha(i,l).then(process.exit)),n.command("stats").description("Showcase engagement metrics").action(i=>ba(i).then(process.exit));let r=t.command("content").description("Content moderation pipeline");r.command("list").description("List community content").option("--status <status>","Filter by status (draft|published|flagged|archived)").option("--type <type>","Filter by type (article|discussion|announcement)").action(i=>va(i).then(process.exit)),r.command("moderate <id>").description("Moderate content").option("--action <action>","Action (approve|flag|archive|delete)").option("--yes","Skip confirmation").action((i,l)=>wa(i,l).then(process.exit)),r.command("publish <id>").description("Publish approved content").option("--yes","Skip confirmation").action((i,l)=>
|
|
227
|
+
`),e.dryRun?s.info("DRY RUN COMPLETE - no changes committed"):s.success("Moderation sweep complete"),c.SUCCESS}catch(t){return s.error(`Failed to run moderation: ${t.message}`),c.ERROR}}function tr(e){let t=e.command("community").description("Manage Nebutra-Sailor community dimension"),n=t.command("showcase").description("Project showcase management");n.command("list").description("List submitted projects").option("--status <status>","Filter by status (pending|approved|rejected|featured)").option("--category <category>","Filter by category").action(i=>fa(i).then(process.exit)),n.command("approve <id>").description("Approve a showcase submission").option("--yes","Skip confirmation").action((i,l)=>ga(i,l).then(process.exit)),n.command("reject <id>").description("Reject a showcase submission").option("--reason <text>","Rejection reason").option("--yes","Skip confirmation").action((i,l)=>ya(i,l).then(process.exit)),n.command("feature <id>").description("Mark as featured").option("--yes","Skip confirmation").action((i,l)=>ha(i,l).then(process.exit)),n.command("stats").description("Showcase engagement metrics").action(i=>ba(i).then(process.exit));let r=t.command("content").description("Content moderation pipeline");r.command("list").description("List community content").option("--status <status>","Filter by status (draft|published|flagged|archived)").option("--type <type>","Filter by type (article|discussion|announcement)").action(i=>va(i).then(process.exit)),r.command("moderate <id>").description("Moderate content").option("--action <action>","Action (approve|flag|archive|delete)").option("--yes","Skip confirmation").action((i,l)=>wa(i,l).then(process.exit)),r.command("publish <id>").description("Publish approved content").option("--yes","Skip confirmation").action((i,l)=>Sa(i,l).then(process.exit)),r.command("analytics").description("Content performance metrics").option("--format <format>","Output format (json|text)").action(i=>Ra(i).then(process.exit));let o=t.command("members").description("Member management");o.command("list").description("List members").option("--role <role>","Filter by role (member|admin|owner|moderator)").option("--sort <sort>","Sort by (engagement|joined|name)").action(i=>Ca(i).then(process.exit)),o.command("profile <userId>").description("View member profile + activity").action((i,l)=>Ea(i,l).then(process.exit)),o.command("role <userId> <role>").description("Update member role").option("--yes","Skip confirmation").action((i,l,u)=>ka(i,l,u).then(process.exit)),o.command("invite <email>").description("Invite to community").action((i,l)=>xa(i,l).then(process.exit)),o.command("ban <userId>").description("Ban member").option("--reason <text>","Ban reason").option("--yes","Skip confirmation").action((i,l)=>Oa(i,l).then(process.exit)),t.command("health").description("Community health dashboard").option("--period <period>","Time period (7d|30d|90d)","30d").option("--format <format>","Output format (json|text)").action(i=>Aa(i).then(process.exit));let a=t.command("moderate").description("AI-assisted moderation queue");a.command("queue").description("Show pending moderation items").action(i=>_a(i).then(process.exit)),a.command("auto").description("Run AI moderation sweep").option("--dry-run","Preview without committing").action(i=>Pa(i).then(process.exit))}import{appendFileSync as Ia,existsSync as Na,readFileSync as $a,writeFileSync as Ta}from"fs";import{homedir as We}from"os";import{join as Be}from"path";import*as W from"@clack/prompts";import H from"picocolors";var ht=(fe.subcommands??[]).map(e=>e.name),nr={init:"Initialize a Nebutra project and create nebutra.config.json",add:"Add a registry-backed platform feature or external UI component",create:"Scaffold a topology-first Nebutra Sailor project",mcp:"Start the Nebutra MCP server for AI agents and editors",completions:"Generate shell completions",doctor:"Check your Nebutra project setup",schema:"Show command schema and argument documentation",brand:"Manage governed brand tokens and palettes",i18n:"Manage localization files and multilingual product copy",infra:"Manage local infrastructure services",env:"Validate and manage environment variables",license:"Manage Nebutra Sailor commercial license activation and status",db:"Database migration and management",generate:"Scaffold apps, modules, and code",dev:"Start development server",build:"Run build workflows",lint:"Run lint workflows",typecheck:"Run TypeScript checks",test:"Run unit and E2E tests",workflow:"Workflow provider scaffolding",backend:"Backend runtime service workflows",e2e:"Run browser E2E suites",theme:"Theme registry and governance metadata",ai:"AI provider and gateway routing configuration",auth:"Authentication setup",billing:"Billing and subscription management",stats:"Project statistics and health checks",admin:"Platform administration",community:"Community health and showcase",growth:"Growth analytics and insights",ecosystem:"Template marketplace, ideas, showcase, and ecosystem sync",services:"Microservice management",search:"Search index management",secrets:"Encrypted secrets management",logout:"Clear local session state",upgrade:"Upgrade local CLI tooling",link:"Link local project metadata",unlink:"Unlink local project metadata"},Ua=["--help","--version","--21st","--v0","--stdio","--format","--yes","--no-interactive","--no-color","--verbose","--quiet","--dry-run","--if-not-exists","--provider","-p","--pm","--region","--orm","--db","--auth","--social-login","--payment","--ai","--deploy","--docs","--email","--storage","--monitoring","--analytics","--sms","--queue","--search","--cache","--notifications","--webhooks","--cms","--feature-flags","--captcha","--mcp","--metering","--billing-mode","--idp","--i18n","--no-i18n","--no-install","--no-git","--json"],Kt=["-p","--pm","--region","--orm","--db","--auth","--social-login","--payment","--ai","--deploy","--docs","--email","--storage","--monitoring","--analytics","--sms","--queue","--search","--cache","--notifications","--webhooks","--cms","--feature-flags","--captcha","--mcp","--metering","--billing-mode","--idp","--i18n","--no-i18n","--no-install","--no-git","--dry-run","--json","--yes"],ja={"-p":b.pm,"--pm":b.pm,"--region":b.region,"--orm":b.orm,"--db":b.db,"--auth":b.auth,"--payment":b.payment,"--deploy":b.deploy,"--docs":b.docs,"--email":b.email,"--storage":b.storage,"--monitoring":b.monitoring,"--analytics":b.analytics,"--sms":b.sms,"--queue":b.queue,"--search":b.search,"--cache":b.cache,"--notifications":b.notifications,"--webhooks":b.webhooks,"--cms":b.cms,"--feature-flags":b.featureFlags,"--captcha":b.captcha,"--mcp":b.mcp,"--metering":b.metering,"--billing-mode":b.billingMode,"--idp":b.idp},La=Object.entries(ja).map(([e,t])=>` ${e})
|
|
228
228
|
COMPREPLY=( $(compgen -W "${t.join(" ")}" -- \${cur}) )
|
|
229
229
|
return 0
|
|
230
230
|
;;`).join(`
|
|
231
|
-
`),Da=
|
|
232
|
-
`),Fa=
|
|
233
|
-
`),Ba=
|
|
231
|
+
`),Da=Kt.map(e=>` "${e}"`).join(`
|
|
232
|
+
`),Fa=ht.map(e=>`complete -c nebutra -n "__fish_use_subcommand_only" -f -a "${e}" -d "${nr[e]}"`).join(`
|
|
233
|
+
`),Ba=Kt.map(e=>`complete -c nebutra -n "__fish_seen_subcommand_from create" -f -a "${e}" -d "create-sailor option"`).join(`
|
|
234
234
|
`);function rr(){return`#!/usr/bin/env bash
|
|
235
235
|
|
|
236
236
|
_nebutra_completions() {
|
|
@@ -240,7 +240,7 @@ _nebutra_completions() {
|
|
|
240
240
|
prev="\${COMP_WORDS[COMP_CWORD-1]}"
|
|
241
241
|
|
|
242
242
|
# Subcommands
|
|
243
|
-
local subcommands="${
|
|
243
|
+
local subcommands="${ht.join(" ")}"
|
|
244
244
|
|
|
245
245
|
# Flags
|
|
246
246
|
local flags="${Ua.join(" ")}"
|
|
@@ -260,7 +260,7 @@ ${La}
|
|
|
260
260
|
COMPREPLY=( $(compgen -W "--21st --v0 --provider --dry-run --yes --if-not-exists" -- \${cur}) )
|
|
261
261
|
elif [[ "\${prev}" == "create" ]]; then
|
|
262
262
|
# create delegates to create-sailor
|
|
263
|
-
COMPREPLY=( $(compgen -W "${
|
|
263
|
+
COMPREPLY=( $(compgen -W "${Kt.join(" ")}" -- \${cur}) )
|
|
264
264
|
elif [[ "\${prev}" == "completions" ]]; then
|
|
265
265
|
# completions command takes shell type
|
|
266
266
|
COMPREPLY=( $(compgen -W "bash zsh fish install" -- \${cur}) )
|
|
@@ -274,7 +274,7 @@ complete -o bashdefault -o default -o nospace -F _nebutra_completions nebutra
|
|
|
274
274
|
|
|
275
275
|
_nebutra() {
|
|
276
276
|
local -a commands=(
|
|
277
|
-
${
|
|
277
|
+
${ht.map(e=>`"${e}:${nr[e]}"`).join(`
|
|
278
278
|
`)}
|
|
279
279
|
)
|
|
280
280
|
|
|
@@ -334,7 +334,7 @@ ${Da}
|
|
|
334
334
|
_nebutra
|
|
335
335
|
`}function sr(){return`# Fish shell completions for nebutra
|
|
336
336
|
|
|
337
|
-
complete -c nebutra -f -n "__fish_seen_subcommand_from; and not __fish_seen_subcommand_from ${
|
|
337
|
+
complete -c nebutra -f -n "__fish_seen_subcommand_from; and not __fish_seen_subcommand_from ${ht.join(" ")}" -d "Nebutra governance CLI"
|
|
338
338
|
|
|
339
339
|
# Subcommands
|
|
340
340
|
${Fa}
|
|
@@ -364,16 +364,19 @@ complete -c nebutra -n "__fish_seen_subcommand_from completions" -f -a "install"
|
|
|
364
364
|
complete -c nebutra -n "__fish_seen_subcommand_from schema" -f -a "--all" -d "Show full schema for all commands"
|
|
365
365
|
complete -c nebutra -n "__fish_seen_subcommand_from schema" -f -a "--list" -d "List all available command names"
|
|
366
366
|
complete -c nebutra -n "__fish_seen_subcommand_from schema" -f -a "--exit-codes" -d "Show exit codes reference"
|
|
367
|
-
`}function ar(e){let n={bash:rr,zsh:or,fish:sr}[e.toLowerCase()];n||(console.error(H.red(`Error: Unknown shell '${e}'. Supported: bash, zsh, fish`)),process.exit(c.INVALID_ARGS)),console.log(n())}async function Ma(){let t=(process.env.SHELL||"/bin/bash").split("/").pop()||"bash";W.intro(H.bgCyan(H.black(" nebutra completions install ")));let n=W.spinner();n.start(H.cyan(`Detecting shell: ${t}...`));try{let r=null,o=null,a=null;if(t==="bash"?(r=
|
|
367
|
+
`}function ar(e){let n={bash:rr,zsh:or,fish:sr}[e.toLowerCase()];n||(console.error(H.red(`Error: Unknown shell '${e}'. Supported: bash, zsh, fish`)),process.exit(c.INVALID_ARGS)),console.log(n())}async function Ma(){let t=(process.env.SHELL||"/bin/bash").split("/").pop()||"bash";W.intro(H.bgCyan(H.black(" nebutra completions install ")));let n=W.spinner();n.start(H.cyan(`Detecting shell: ${t}...`));try{let r=null,o=null,a=null;if(t==="bash"?(r=Be(We(),".bashrc"),o=Be(We(),".bash_completion.d"),a="source ~/.bash_completion.d/nebutra"):t==="zsh"?(r=Be(We(),".zshrc"),o=Be(We(),".zsh/completions"),a="fpath=(~/.zsh/completions $fpath)"):t==="fish"?(o=Be(We(),".config/fish/completions"),a="# Completions installed to ~/.config/fish/completions/nebutra.fish"):(n.stop(),W.log.warn(H.yellow(`Warning: Unsupported shell '${t}'. Please install completions manually.`)),ar("bash"),W.outro(H.cyan("Run 'nebutra completions bash' (or zsh/fish) to generate completions for your shell.")),process.exit(c.SUCCESS)),o){(await import("fs")).mkdirSync(o,{recursive:!0});let l=Be(o,t==="fish"?"nebutra.fish":"nebutra"),u=t==="bash"?rr():t==="zsh"?or():sr();Ta(l,u),n.stop(H.green(`Completion script installed to ${l}`))}r&&a&&t!=="fish"&&(!Na(r)||!$a(r,"utf8").includes("nebutra"))&&(Ia(r,(t==="bash"?`
|
|
368
368
|
# nebutra completions
|
|
369
369
|
[[ -f ~/.bash_completion.d/nebutra ]] && source ~/.bash_completion.d/nebutra`:`
|
|
370
370
|
# nebutra completions
|
|
371
371
|
fpath=(~/.zsh/completions $fpath)
|
|
372
372
|
autoload -Uz compinit && compinit`)+`
|
|
373
|
-
`),W.log.info(H.green(`Added nebutra completions to ${r}`))),W.log.info(H.cyan("Completions installed! Restart your shell or run:")),W.log.info(H.dim(` source "${t==="bash"?"~/.bashrc":"~/.zshrc"}"`)),W.outro(H.green("Installation complete!"))}catch(r){n.stop(),W.log.error(H.red("Error installing completions. You can manually add them by running:")),W.log.info(H.cyan(` nebutra completions ${t} >> ~/.${t}rc`)),r instanceof Error&&console.error(H.dim(r.message)),process.exit(c.ERROR)}}function ir(e){e.command("completions [shell]").description("Generate or install shell completions").action(async t=>{!t||t==="install"?await Ma():ar(t)})}import{
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
373
|
+
`),W.log.info(H.green(`Added nebutra completions to ${r}`))),W.log.info(H.cyan("Completions installed! Restart your shell or run:")),W.log.info(H.dim(` source "${t==="bash"?"~/.bashrc":"~/.zshrc"}"`)),W.outro(H.green("Installation complete!"))}catch(r){n.stop(),W.log.error(H.red("Error installing completions. You can manually add them by running:")),W.log.info(H.cyan(` nebutra completions ${t} >> ~/.${t}rc`)),r instanceof Error&&console.error(H.dim(r.message)),process.exit(c.ERROR)}}function ir(e){e.command("completions [shell]").description("Generate or install shell completions").action(async t=>{!t||t==="install"?await Ma():ar(t)})}import{existsSync as Ga}from"fs";import{spawn as cr}from"child_process";import{dirname as Va,resolve as Ka}from"path";import{fileURLToPath as qa}from"url";import qt from"picocolors";var za=Va(qa(import.meta.url));function Ya(){let e=Ka(za,"../../../create-sailor/dist/index.js");return Ga(e)?e:"create-sailor"}function Ha(e){let t=process.argv.slice(2),n=t.findIndex(r=>r==="create");return n<0?e?[e]:[]:t.slice(n+1)}function lr(e){e.command("create [dir]").description("Scaffold a new Sailor project (delegates to create-sailor)").allowUnknownOption(!0).allowExcessArguments(!0).action(async t=>{let n=Ya(),r=Ha(t),a=n.endsWith(".js")?cr(process.execPath,[n,...r],{stdio:"inherit",env:{...process.env}}):cr(n,r,{stdio:"inherit",env:{...process.env},shell:!0});a.on("close",i=>{process.exit(i??0)}),a.on("error",i=>{s.error(`Failed to launch create-sailor: ${i.message}`),i.code==="ENOENT"&&(process.stderr.write(`
|
|
374
|
+
${qt.yellow("Tip:")} install the scaffolder:
|
|
375
|
+
${qt.cyan("npm i -g create-sailor")}
|
|
376
|
+
${qt.cyan("npx create-sailor@latest")}
|
|
377
|
+
|
|
378
|
+
`),process.exit(c.NOT_FOUND)),process.exit(c.ERROR)})})}import*as bt from"@clack/prompts";async function Wa(e){d("Generating Prisma client"+"...","info");let n=await he("generate",{dryRun:e.dryRun,interactive:!e.dryRun});n.exitCode===0?d("Prisma client generated successfully","success"):(d("Failed to generate Prisma client","error"),process.exit(n.exitCode||1))}async function zt(e,t){let n=t||{};if(e){d(`Creating migration: ${e}`,"info");let r=await he("migrate",{args:["dev","--name",e],dryRun:n.dryRun,interactive:!n.dryRun});r.exitCode===0?d(`Migration '${e}' created successfully`,"success"):(d(`Failed to create migration '${e}'`,"error"),process.exit(r.exitCode||1))}else{d("Running pending migrations...","info");let r=await he("migrate",{args:["deploy"],dryRun:n.dryRun,interactive:!n.dryRun});r.exitCode===0?d("All pending migrations completed","success"):(d("Migration deployment failed","error"),process.exit(r.exitCode||1))}}async function Ja(e){d("Pushing schema to database...","info");let t=await he("db",{args:["push"],dryRun:e.dryRun,interactive:!e.dryRun});t.exitCode===0?d("Schema pushed successfully","success"):(d("Failed to push schema","error"),process.exit(t.exitCode||1))}async function Xa(e){d("Seeding database...","info");let t=await he("db",{args:["seed"],dryRun:e.dryRun,interactive:!e.dryRun});t.exitCode===0?d("Database seeded successfully","success"):(d("Failed to seed database","error"),process.exit(t.exitCode||1))}async function Qa(e){d("Launching Prisma Studio...","info");let t=await he("studio",{dryRun:e.dryRun,interactive:!0});t.exitCode!==0&&(d("Failed to launch Prisma Studio","error"),process.exit(t.exitCode||1))}async function Za(e){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(!e.yes&&!e.dryRun)if(t){let r=await bt.confirm({message:"Reset database? This will delete all data.",initialValue:!1});(bt.isCancel(r)||!r)&&(d("Reset cancelled","warn"),process.exit(c.CANCELLED))}else d("Database reset requires explicit --yes confirmation (use: nebutra db reset --yes)","error"),process.exit(c.INVALID_ARGS);d("Resetting database...","warn");let n=await he("migrate",{args:["reset",...e.yes?["--force"]:[]],dryRun:e.dryRun,interactive:!e.dryRun});n.exitCode===0?d("Database reset successfully","success"):(d("Failed to reset database","error"),process.exit(n.exitCode||1))}async function ei(e){d("Checking migration status...","info");let t=await he("migrate",{args:["status"],dryRun:e.dryRun,interactive:!e.dryRun});if(t.exitCode===0){if(e.format==="json")try{let n=JSON.parse(t.stdout);process.stdout.write(JSON.stringify(n,null,2)+`
|
|
379
|
+
`)}catch{process.stdout.write(t.stdout)}}else d("Failed to check migration status","error"),process.exit(t.exitCode||1)}function dr(e){e.command("db <verb> [args...]").description("Manage database schema, migrations, and state").option("--dry-run","Show what would be run without executing").option("--yes","Skip confirmations (especially for reset)").option("--format <type>","Output format: json, plain","plain").action(async(n,r,o)=>{let a=o.optsWithGlobals?.(),i={dryRun:o.dryRun||a?.dryRun,yes:o.yes||a?.yes,format:o.format||a?.format};try{switch(n){case"generate":await Wa(i);break;case"migrate":r.length>0?r[0]==="create"&&r[1]?await zt(r[1],i):await zt(r[0],i):await zt(void 0,i);break;case"push":await Ja(i);break;case"seed":await Xa(i);break;case"studio":await Qa(i);break;case"reset":await Za(i);break;case"status":await ei(i);break;default:d(`Unknown db subcommand: ${n}. Valid commands: generate, migrate, migrate create, push, seed, studio, reset, status`,"error"),process.exit(c.INVALID_ARGS)}}catch(l){let u=l instanceof Error?l.message:String(l);d(`Database command failed: ${u}`,"error"),k("Full error",{error:l}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
377
380
|
Examples:
|
|
378
381
|
nebutra db generate Generate Prisma client
|
|
379
382
|
nebutra db migrate Run all pending migrations
|
|
@@ -388,53 +391,53 @@ Flags:
|
|
|
388
391
|
--dry-run Show what would be run without executing
|
|
389
392
|
--yes Skip confirmations
|
|
390
393
|
--format <type> Output format: json, plain (default: plain)
|
|
391
|
-
`)}import*as _ from"@clack/prompts";import C from"picocolors";function
|
|
392
|
-
${n}`)}return t}async function
|
|
394
|
+
`)}import*as _ from"@clack/prompts";import C from"picocolors";function Ee(e){if(e==="json"||e==="plain"||e==="table")return e}var Me=["landing","web","storybook","design-docs","sailor-docs","studio","docs","idp","mail-preview","gateway"];function vt(e){let t=`@nebutra/${e}`;if(!Me.includes(e)){let n=C.yellow(`Valid apps: ${Me.join(", ")}`);throw new Error(`Invalid app: ${C.red(e)}
|
|
395
|
+
${n}`)}return t}async function ti(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"dev",options:{app:e.app},task:e.app?"turbo dev":"turbo dev (all apps)"},{format:Ee(e.format)}),process.exit(c.DRY_RUN_OK));try{if(e.app){vt(e.app);let n=`@nebutra/${e.app}`;e.quiet||_.log.info(C.cyan(`Starting dev server for ${C.bold(n)}...`));let r=await we("dev",{filter:n});process.exit(r.exitCode)}e.quiet||_.log.info(C.cyan("Starting dev servers for all apps..."));let t=await we("dev");process.exit(t.exitCode)}catch(t){t instanceof Error?_.log.error(C.red(t.message)):_.log.error(C.red("Unknown error occurred")),process.exit(c.ERROR)}}async function ni(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"build",options:{app:e.app,strict:e.strict},task:e.strict?"pnpm build:strict":"pnpm build"},{format:Ee(e.format)}),process.exit(c.DRY_RUN_OK));try{if(e.app&&e.strict&&(_.log.error(C.red("Cannot use --strict with --app filter")),process.exit(c.INVALID_ARGS)),e.app){vt(e.app);let r=`@nebutra/${e.app}`;e.quiet||_.log.info(C.cyan(`Building ${C.bold(r)}...`));let o=await we("build",{filter:r});process.exit(o.exitCode)}let t=e.strict?"build:strict":"build";if(!e.quiet){let r=e.strict?"Running strict build (with UI governance verification)...":"Building all apps...";_.log.info(C.cyan(r))}let n=await z(t,{interactive:!0});process.exit(n.exitCode)}catch(t){t instanceof Error?_.log.error(C.red(t.message)):_.log.error(C.red("Unknown error occurred")),process.exit(c.ERROR)}}async function ri(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"lint",options:{app:e.app,fix:e.fix},task:e.fix?"pnpm lint:fix":"pnpm lint"},{format:Ee(e.format)}),process.exit(c.DRY_RUN_OK));try{if(e.app&&e.fix&&(_.log.error(C.red("Cannot use --fix with --app filter (lint:fix is global only)")),process.exit(c.INVALID_ARGS)),e.app){vt(e.app);let r=`@nebutra/${e.app}`;e.quiet||_.log.info(C.cyan(`Linting ${C.bold(r)}...`));let o=await O({command:"turbo",args:["run","lint","--filter",r],interactive:!0,label:`turbo lint --filter ${r}`,dryRun:e.dryRun});process.exit(o.exitCode)}let t=e.fix?"lint:fix":"lint";if(!e.quiet){let r=e.fix?"Fixing linting issues...":"Linting codebase...";_.log.info(C.cyan(r))}let n=await z(t,{interactive:!0});process.exit(n.exitCode)}catch(t){t instanceof Error?_.log.error(C.red(t.message)):_.log.error(C.red("Unknown error occurred")),process.exit(c.ERROR)}}async function oi(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"typecheck",options:{app:e.app},task:"turbo typecheck"},{format:Ee(e.format)}),process.exit(c.DRY_RUN_OK));try{if(e.app){vt(e.app);let n=`@nebutra/${e.app}`;e.quiet||_.log.info(C.cyan(`Type-checking ${C.bold(n)}...`));let r=await we("typecheck",{filter:n});process.exit(r.exitCode)}e.quiet||_.log.info(C.cyan("Type-checking all packages..."));let t=await we("typecheck");process.exit(t.exitCode)}catch(t){t instanceof Error?_.log.error(C.red(t.message)):_.log.error(C.red("Unknown error occurred")),process.exit(c.ERROR)}}var ur=e=>{e.command("dev").description("Start development servers (turbo dev)").option("--app <name>",`App to run: ${Me.join(", ")}`).option("--dry-run","Preview what would run (exit code 10)").action(async(t,n)=>{let r=x(t,n);await ti({app:typeof t.app=="string"?t.app:void 0,dryRun:!!t.dryRun,quiet:!!r.quiet,verbose:!!r.verbose,format:Ee(r.format)})}),e.command("build").description("Build all apps (pnpm build or turbo build)").option("--app <name>",`App to build: ${Me.join(", ")}`).option("--strict","Run strict build with UI governance verification (pnpm build:strict)").option("--dry-run","Preview what would run (exit code 10)").action(async(t,n)=>{let r=x(t,n);await ni({app:typeof t.app=="string"?t.app:void 0,dryRun:!!t.dryRun,strict:!!t.strict,quiet:!!r.quiet,verbose:!!r.verbose,format:Ee(r.format)})}),e.command("lint").description("Lint with Biome (pnpm lint or pnpm lint:fix)").option("--app <name>",`App to lint: ${Me.join(", ")}`).option("--fix","Fix linting issues automatically").option("--dry-run","Preview what would run (exit code 10)").action(async(t,n)=>{let r=x(t,n);await ri({app:typeof t.app=="string"?t.app:void 0,dryRun:!!t.dryRun,fix:!!t.fix,quiet:!!r.quiet,verbose:!!r.verbose,format:Ee(r.format)})}),e.command("typecheck").description("Type-check with TypeScript (turbo typecheck)").option("--app <name>",`App to typecheck: ${Me.join(", ")}`).option("--dry-run","Preview what would run (exit code 10)").action(async(t,n)=>{let r=x(t,n);await oi({app:typeof t.app=="string"?t.app:void 0,dryRun:!!t.dryRun,quiet:!!r.quiet,verbose:!!r.verbose,format:Ee(r.format)})})};import mr from"fs";import pr from"path";import Yt from"picocolors";var Ht=["smoke","golden","sleptons"],si={smoke:{config:"e2e/playwright.config.ts",suiteDir:"e2e/smoke"},golden:{config:"e2e/playwright.golden.config.ts",suiteDir:"e2e/golden"},sleptons:{config:"e2e/playwright.sleptons.config.ts",suiteDir:"e2e/sleptons"}};async function ai(e,t={}){Ht.includes(e)||(s.error(`Invalid suite: ${Yt.red(e)}. Valid: ${Ht.join(", ")}`),process.exit(c.INVALID_ARGS));let n=h(),{config:r,suiteDir:o}=si[e],a=pr.join(n,r),i=pr.join(n,o);(!mr.existsSync(i)||!mr.existsSync(a))&&(s.error(`Suite ${Yt.red(e)} not found at ${o}.
|
|
393
396
|
Expected config: ${r}
|
|
394
397
|
Remediation: scaffold the suite (analogous to 'nebutra workflow init <provider>')
|
|
395
|
-
or restore the directory from git.`),process.exit(c.NOT_FOUND)),t.dryRun&&(A({mode:"dry-run",command:`e2e ${e}`,task:`pnpm exec playwright test --config ${r}`}),process.exit(c.DRY_RUN_OK)),t.quiet||s.info(`Running Playwright suite: ${
|
|
396
|
-
`));try{let n=await(await P("/status")).json();return e.format,c.SUCCESS}catch(t){return s.error(`Failed to fetch ecosystem status: ${t}`),c.ERROR}}async function
|
|
397
|
-
`));let t=e.token||
|
|
398
|
+
or restore the directory from git.`),process.exit(c.NOT_FOUND)),t.dryRun&&(A({mode:"dry-run",command:`e2e ${e}`,task:`pnpm exec playwright test --config ${r}`}),process.exit(c.DRY_RUN_OK)),t.quiet||s.info(`Running Playwright suite: ${Yt.bold(e)}`);let l=await O({command:"pnpm",args:["exec","playwright","test","--config",r],interactive:!0,label:`playwright ${e}`});process.exit(l.exitCode)}var fr=e=>{e.command("e2e <suite>").description(`Run a Playwright suite (${Ht.join(" | ")})`).option("--dry-run","Preview the command that would run (exit code 10)").action(async(t,n,r)=>{let o=x(n,r);await ai(t,{dryRun:!!n.dryRun,quiet:!!o.quiet})})};import g from"picocolors";var ii=process.env.NEBUTRA_ECOSYSTEM_URL||"https://api.nebutra.com/ecosystem",gr=process.env.NEBUTRA_ECOSYSTEM_TOKEN||"";async function P(e,t={}){let{method:n="GET",body:r,dryRun:o=!1,token:a=gr}=t,i=`${ii}${e}`;if(o)return d(`[DRY RUN] ${n} ${i}`),r&&d(`Body: ${JSON.stringify(r)}`),A({mode:"dry-run",method:n,url:i,...r&&{body:r}}),{ok:!0,status:200,json:async()=>({dryRun:!0})};let l={"Content-Type":"application/json"};a&&(l.Authorization=`Bearer ${a}`);try{let u=await fetch(i,{method:n,headers:l,...r&&{body:JSON.stringify(r)}});if(!u.ok){let m=await u.text();throw new Error(`${u.status}: ${m}`)}return u}catch(u){throw s.error(`Ecosystem API error: ${u}`),u}}function ci(e={}){let t=[{name:"README.md exists",pass:!0},{name:"License file exists",pass:!0},{name:"package.json has description",pass:!0},{name:"No security vulnerabilities",pass:!0},{name:"TypeScript passes",pass:!0}];return e.skipChecks?{valid:!0,checks:t}:{valid:t.every(r=>r.pass),checks:t}}async function li(e){s.info(g.cyan(`\u{1F4CA} Ecosystem Status Dashboard
|
|
399
|
+
`));try{let n=await(await P("/status")).json();return e.format,c.SUCCESS}catch(t){return s.error(`Failed to fetch ecosystem status: ${t}`),c.ERROR}}async function di(e){s.info(g.cyan(`\u{1F517} Connect to Nebutra Ecosystem
|
|
400
|
+
`));let t=e.token||gr;!t&&!e.yes&&(s.warn(`No NEBUTRA_ECOSYSTEM_TOKEN found. Starting OAuth flow...
|
|
398
401
|
`),s.info("Visit: "+g.blue("https://nebutra.com/oauth/authorize?scope=ecosystem")),s.info("Then paste your token below:"),t="token_example_"+Math.random().toString(36).slice(2));let n=e.org||"org_default";try{let o=await(await P("/projects/connect",{method:"POST",body:{projectName:"My Project",repository:"https://github.com/user/project",orgId:n},dryRun:e.dryRun,token:t})).json();return e.dryRun?(d("[DRY RUN] Would connect project to ecosystem","success"),c.SUCCESS):(s.success(`\u2713 Connected to Nebutra Ecosystem
|
|
399
402
|
`),s.info(`Project ID: ${g.cyan(o.projectId)}`),s.info(`Organization: ${g.cyan(n)}`),s.info(`Ecosystem Config: ${g.cyan(".nebutra/ecosystem.json")}
|
|
400
|
-
`),s.info(`Next steps: Run ${g.yellow("nebutra ecosystem publish")} to share your project`),c.SUCCESS)}catch(r){return s.error(`Connection failed: ${r}`),c.ERROR}}async function
|
|
401
|
-
`));let t=e.tag||"latest",n=e.visibility||"public",r=
|
|
403
|
+
`),s.info(`Next steps: Run ${g.yellow("nebutra ecosystem publish")} to share your project`),c.SUCCESS)}catch(r){return s.error(`Connection failed: ${r}`),c.ERROR}}async function ui(e){s.info(g.cyan(`\u{1F4E4} Publish to Ecosystem Marketplace
|
|
404
|
+
`));let t=e.tag||"latest",n=e.visibility||"public",r=ci();s.info(`${g.bold("Pre-Publish Checklist")}
|
|
402
405
|
`);for(let o of r.checks){let a=o.pass?g.green("\u2713"):g.red("\u2717")}if(!r.valid)return s.error(`
|
|
403
406
|
Fix the checks above before publishing`),c.ERROR;if(n==="public"&&!e.yes&&(s.info(`This project will be ${g.yellow("publicly listed")} in the ecosystem`),s.info(`Continue? Run with ${g.yellow("--yes")} to skip confirmation`),!e.yes))return c.CANCELLED;try{let a=await(await P("/projects/publish",{method:"POST",body:{projectName:"My Template",description:"A production-ready SaaS template",repository:"https://github.com/user/project",tags:["saas","nextjs","ai"],tag:t,visibility:n},dryRun:e.dryRun})).json();return e.dryRun?(d("[DRY RUN] Would publish to ecosystem","success"),c.SUCCESS):(s.success(`\u2713 Published successfully!
|
|
404
407
|
`),s.info(`Marketplace URL: ${g.blue(`https://nebutra.com/templates/${a.projectId}`)}`),s.info(`Visibility: ${n}`),s.info(`Tag: ${t}
|
|
405
|
-
`),c.SUCCESS)}catch(o){return s.error(`Publish failed: ${o}`),c.ERROR}}async function
|
|
406
|
-
`));try{let n=await(await P(`/templates?category=${e.category||""}&sort=${e.sort||"downloads"}`)).json();return e.format==="json"||s.info(`Run ${g.yellow("nebutra ecosystem templates info <id>")} for details`),c.SUCCESS}catch(t){return s.error(`Failed to list templates: ${t}`),c.ERROR}}async function
|
|
407
|
-
`));try{let r=await(await P(`/templates/search?q=${encodeURIComponent(e)}`)).json();return t.format,c.SUCCESS}catch(n){return s.error(`Search failed: ${n}`),c.ERROR}}async function
|
|
408
|
-
`));try{let n=await(await P(`/templates/${e}`)).json();return s.info(`Install: ${g.yellow("nebutra ecosystem templates install multi-tenant-saas")}`),c.SUCCESS}catch(t){return s.error(`Failed to fetch template info: ${t}`),c.ERROR}}async function
|
|
408
|
+
`),c.SUCCESS)}catch(o){return s.error(`Publish failed: ${o}`),c.ERROR}}async function mi(e){s.info(g.cyan(`\u{1F4DA} Template Marketplace
|
|
409
|
+
`));try{let n=await(await P(`/templates?category=${e.category||""}&sort=${e.sort||"downloads"}`)).json();return e.format==="json"||s.info(`Run ${g.yellow("nebutra ecosystem templates info <id>")} for details`),c.SUCCESS}catch(t){return s.error(`Failed to list templates: ${t}`),c.ERROR}}async function pi(e,t){s.info(g.cyan(`\u{1F50D} Searching templates for "${e}"
|
|
410
|
+
`));try{let r=await(await P(`/templates/search?q=${encodeURIComponent(e)}`)).json();return t.format,c.SUCCESS}catch(n){return s.error(`Search failed: ${n}`),c.ERROR}}async function fi(e){s.info(g.cyan(`\u{1F4D6} Template Details
|
|
411
|
+
`));try{let n=await(await P(`/templates/${e}`)).json();return s.info(`Install: ${g.yellow("nebutra ecosystem templates install multi-tenant-saas")}`),c.SUCCESS}catch(t){return s.error(`Failed to fetch template info: ${t}`),c.ERROR}}async function gi(e,t){s.info(g.cyan(`\u2B07\uFE0F Installing template "${e}"
|
|
409
412
|
`));try{let n=await P(`/templates/${e}/install`,{method:"POST",body:{projectName:"my-saas"},dryRun:t.dryRun});return t.dryRun?(d("[DRY RUN] Would install template","success"),c.SUCCESS):(s.success(`\u2713 Template installed!
|
|
410
|
-
`),s.info("Project: ./my-saas"),s.info(`Next: ${g.yellow("cd my-saas && pnpm install && pnpm dev")}`),c.SUCCESS)}catch(n){return s.error(`Installation failed: ${n}`),c.ERROR}}async function
|
|
411
|
-
`));try{let n=await(await P(`/ideas?status=${e.status||""}&sort=${e.sort||"recent"}`)).json();return e.format==="json"||(s.info(`Vote: ${g.yellow("nebutra ecosystem ideas vote <id>")}`),s.info(`Claim: ${g.yellow("nebutra ecosystem ideas claim <id>")}`)),c.SUCCESS}catch(t){return s.error(`Failed to list ideas: ${t}`),c.ERROR}}async function
|
|
413
|
+
`),s.info("Project: ./my-saas"),s.info(`Next: ${g.yellow("cd my-saas && pnpm install && pnpm dev")}`),c.SUCCESS)}catch(n){return s.error(`Installation failed: ${n}`),c.ERROR}}async function yi(e){s.info(g.cyan(`\u{1F4A1} Ideas Marketplace
|
|
414
|
+
`));try{let n=await(await P(`/ideas?status=${e.status||""}&sort=${e.sort||"recent"}`)).json();return e.format==="json"||(s.info(`Vote: ${g.yellow("nebutra ecosystem ideas vote <id>")}`),s.info(`Claim: ${g.yellow("nebutra ecosystem ideas claim <id>")}`)),c.SUCCESS}catch(t){return s.error(`Failed to list ideas: ${t}`),c.ERROR}}async function hi(e){if(s.info(g.cyan(`\u2728 Submit New Idea
|
|
412
415
|
`)),!e.title||!e.description)return s.error("Missing required fields: --title and --description"),c.INVALID_ARGS;try{let n=await(await P("/ideas",{method:"POST",body:{title:e.title,description:e.description,tags:e.tags?.split(",")||[],authorId:"user_current"},dryRun:e.dryRun})).json();return e.dryRun?(d("[DRY RUN] Would submit idea","success"),c.SUCCESS):(s.success(`\u2713 Idea submitted!
|
|
413
416
|
`),s.info(`Idea URL: ${g.blue(`https://nebutra.com/ideas/${n.ideaId}`)}`),s.info(`Start voting and discussing! Community will help shape it.
|
|
414
|
-
`),c.SUCCESS)}catch(t){return s.error(`Submission failed: ${t}`),c.ERROR}}async function
|
|
417
|
+
`),c.SUCCESS)}catch(t){return s.error(`Submission failed: ${t}`),c.ERROR}}async function bi(e,t){s.info(g.cyan(`\u{1F44D} Voting on idea "${e}"
|
|
415
418
|
`));try{let n=await P(`/ideas/${e}/vote`,{method:"POST",body:{action:"upvote"},dryRun:t.dryRun});return t.dryRun?(d("[DRY RUN] Would upvote idea","success"),c.SUCCESS):(s.success(`\u2713 Vote recorded! This idea now has more momentum.
|
|
416
|
-
`),c.SUCCESS)}catch(n){return s.error(`Vote failed: ${n}`),c.ERROR}}async function
|
|
419
|
+
`),c.SUCCESS)}catch(n){return s.error(`Vote failed: ${n}`),c.ERROR}}async function vi(e,t){s.info(g.cyan(`\u{1F3AF} Claiming idea "${e}"
|
|
417
420
|
`));try{let n=await P(`/ideas/${e}/claim`,{method:"POST",body:{claimerId:"user_current",status:"in-progress"},dryRun:t.dryRun});return t.dryRun?(d("[DRY RUN] Would claim idea","success"),c.SUCCESS):(s.success(`\u2713 Idea claimed! You're now working on this.
|
|
418
|
-
`),s.info("Post updates in the comments to keep the community informed."),c.SUCCESS)}catch(n){return s.error(`Claim failed: ${n}`),c.ERROR}}async function
|
|
421
|
+
`),s.info("Post updates in the comments to keep the community informed."),c.SUCCESS)}catch(n){return s.error(`Claim failed: ${n}`),c.ERROR}}async function wi(e,t){if(s.info(g.cyan(`\u{1F4AC} Adding comment to idea "${e}"
|
|
419
422
|
`)),!t.message)return s.error("Missing --message parameter"),c.INVALID_ARGS;try{let n=await P(`/ideas/${e}/comments`,{method:"POST",body:{authorId:"user_current",message:t.message},dryRun:t.dryRun});return t.dryRun?(d("[DRY RUN] Would post comment","success"),c.SUCCESS):(s.success(`\u2713 Comment posted!
|
|
420
|
-
`),c.SUCCESS)}catch(n){return s.error(`Comment failed: ${n}`),c.ERROR}}async function
|
|
423
|
+
`),c.SUCCESS)}catch(n){return s.error(`Comment failed: ${n}`),c.ERROR}}async function Si(e){s.info(g.cyan(`\u{1F465} Legacy Member Directory
|
|
421
424
|
`));try{let n=await(await P(`/opc?skill=${e.skill||""}&industry=${e.industry||""}&sort=${e.sort||"active"}`)).json();return e.format==="json"||(s.info(`View profile: ${g.yellow("nebutra ecosystem opc profile <handle>")}`),s.info(`Register: ${g.yellow("nebutra ecosystem opc register")}`)),c.SUCCESS}catch(t){return s.error(`Failed to list members: ${t}`),c.ERROR}}async function Ri(){s.info(g.cyan(`\u{1F464} Legacy Member Profile
|
|
422
|
-
`));try{let t=await(await P("/opc/me")).json();return s.info(`Edit profile: ${g.yellow("nebutra ecosystem opc register")}`),c.SUCCESS}catch(e){return s.error(`Failed to load profile: ${e}`),c.ERROR}}async function
|
|
425
|
+
`));try{let t=await(await P("/opc/me")).json();return s.info(`Edit profile: ${g.yellow("nebutra ecosystem opc register")}`),c.SUCCESS}catch(e){return s.error(`Failed to load profile: ${e}`),c.ERROR}}async function Ci(e){s.info(g.cyan(`\u{1F4DD} Register Legacy Member Profile
|
|
423
426
|
`));let t={name:"Your Name",handle:"your-handle",bio:"Building amazing products",skills:["nextjs","ai","devtools"],industry:"startup"};if(e.dryRun)return s.info(`[DRY RUN] Would register profile:
|
|
424
427
|
`),c.SUCCESS;if(!e.yes)return s.info("This will create your public legacy member profile."),s.info(`Run with ${g.yellow("--yes")} to confirm`),c.CANCELLED;try{let n=await P("/opc/register",{method:"POST",body:t});return s.success(`\u2713 Legacy member profile created!
|
|
425
|
-
`),s.info(`View at: ${g.blue("https://nebutra.com/members/your-handle")}`),s.info(`Compatibility command: ${g.yellow("nebutra ecosystem opc profile --share")}`),c.SUCCESS}catch(n){return s.error(`Registration failed: ${n}`),c.ERROR}}async function
|
|
426
|
-
`));try{let n=await(await P(`/showcase?category=${e.category||""}&featured=${e.featured?"true":""}`)).json();return e.format==="json"||(s.info(`Vote: ${g.yellow("nebutra ecosystem showcase vote <id>")}`),s.info(`Submit yours: ${g.yellow("nebutra ecosystem showcase submit")}`)),c.SUCCESS}catch(t){return s.error(`Failed to list showcase: ${t}`),c.ERROR}}async function
|
|
428
|
+
`),s.info(`View at: ${g.blue("https://nebutra.com/members/your-handle")}`),s.info(`Compatibility command: ${g.yellow("nebutra ecosystem opc profile --share")}`),c.SUCCESS}catch(n){return s.error(`Registration failed: ${n}`),c.ERROR}}async function Ei(e){s.info(g.cyan(`\u2B50 Project Showcase
|
|
429
|
+
`));try{let n=await(await P(`/showcase?category=${e.category||""}&featured=${e.featured?"true":""}`)).json();return e.format==="json"||(s.info(`Vote: ${g.yellow("nebutra ecosystem showcase vote <id>")}`),s.info(`Submit yours: ${g.yellow("nebutra ecosystem showcase submit")}`)),c.SUCCESS}catch(t){return s.error(`Failed to list showcase: ${t}`),c.ERROR}}async function ki(e){s.info(g.cyan(`\u{1F389} Submit Project to Showcase
|
|
427
430
|
`));let t={projectName:"My Awesome Project",url:"https://example.com",description:"A production product built with Nebutra",monthlyVisitors:1e4,builtWith:["nextjs","tailwind","prisma"]};if(!e.yes)return s.info("This will add your project to the public showcase."),s.info(`Run with ${g.yellow("--yes")} to confirm`),c.CANCELLED;try{let n=await P("/showcase/submit",{method:"POST",body:t,dryRun:e.dryRun});return e.dryRun?(d("[DRY RUN] Would submit to showcase","success"),c.SUCCESS):(s.success(`\u2713 Project added to showcase!
|
|
428
|
-
`),s.info(`View at: ${g.blue("https://nebutra.com/showcase/my-project")}`),s.info("Community can now discover your work!"),c.SUCCESS)}catch(n){return s.error(`Submission failed: ${n}`),c.ERROR}}async function
|
|
431
|
+
`),s.info(`View at: ${g.blue("https://nebutra.com/showcase/my-project")}`),s.info("Community can now discover your work!"),c.SUCCESS)}catch(n){return s.error(`Submission failed: ${n}`),c.ERROR}}async function xi(e,t){s.info(g.cyan(`\u{1F44D} Voting on showcase project "${e}"
|
|
429
432
|
`));try{let n=await P(`/showcase/${e}/vote`,{method:"POST",body:{action:"upvote"},dryRun:t.dryRun});return t.dryRun?(d("[DRY RUN] Would upvote project","success"),c.SUCCESS):(s.success(`\u2713 Vote recorded! You're supporting this project.
|
|
430
|
-
`),c.SUCCESS)}catch(n){return s.error(`Vote failed: ${n}`),c.ERROR}}async function
|
|
433
|
+
`),c.SUCCESS)}catch(n){return s.error(`Vote failed: ${n}`),c.ERROR}}async function Oi(e){s.info(g.cyan(`\u{1F504} Sync with Ecosystem
|
|
431
434
|
`));let t=!e.push,n=e.push?"push":"pull";try{let r=await P("/sync",{method:"POST",body:{direction:n,timestamp:new Date().toISOString()},dryRun:e.dryRun});return e.dryRun?(s.info(g.green(`\u2713 [DRY RUN] Would sync (${n})
|
|
432
435
|
`)),c.SUCCESS):(s.success(`\u2713 Synced!
|
|
433
|
-
`),t?s.info("Downloaded: ecosystem config, stats, badges"):s.info("Uploaded: project updates, metrics"),c.SUCCESS)}catch(r){return s.error(`Sync failed: ${r}`),c.ERROR}}function
|
|
434
|
-
`)){if(o.trim().startsWith("#")||!o.trim())continue;let a=o.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/);if(a){let[,i,l]=a;r[i]=l.replace(/^["'](.*)["']$/,"$1")}}return r}function
|
|
435
|
-
`)){if(i.trim().startsWith("#")||!i.trim())continue;let l=i.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/);if(l){let[,u,m]=l;a[u]=m.replace(/^["'](.*)["']$/,"$1")}}return a}function
|
|
436
|
-
`);e.dryRun?(d("Dry-run: would write .env.local","info"),
|
|
437
|
-
`),d(`Environment template written to ${r}`,"success"))}async function
|
|
436
|
+
`),t?s.info("Downloaded: ecosystem config, stats, badges"):s.info("Uploaded: project updates, metrics"),c.SUCCESS)}catch(r){return s.error(`Sync failed: ${r}`),c.ERROR}}function yr(e){let t=e.command("ecosystem").description("Nebutra ecosystem marketplace, ideas, showcase, and sync workflows");t.command("status").description("Ecosystem overview dashboard").option("--format <format>","Output format: json","text").action(async i=>{await li(i)}),t.command("connect").description("Connect local project to Nebutra ecosystem").option("--token <token>","Ecosystem API token").option("--org <orgId>","Organization ID").option("--dry-run","Preview without making changes").option("--yes","Skip confirmations").action(async i=>{await di(i)}),t.command("publish").description("Publish project/template to ecosystem marketplace").option("--tag <tag>","Release tag: latest|beta|canary","latest").option("--visibility <visibility>","Project visibility: public|private|unlisted","public").option("--dry-run","Preview without making changes").option("--yes","Skip confirmations").action(async i=>{await ui(i)});let n=t.command("templates").description("Template marketplace");n.command("list").description("Browse available templates").option("--category <category>","Filter by category").option("--sort <sort>","Sort by: stars|downloads|recent","downloads").option("--format <format>","Output format","text").action(async i=>{await mi(i)}),n.command("search <query>").description("Search templates").option("--format <format>","Output format","text").action(async(i,l)=>{await pi(i,l)}),n.command("info <id>").description("Template details").action(async i=>{await fi(i)}),n.command("install <id>").description("Install/fork a template").option("--dry-run","Preview without making changes").action(async(i,l)=>{await gi(i,l)});let r=t.command("ideas").description("Ideas marketplace");r.command("list").description("Browse ideas").option("--status <status>","Filter by status").option("--sort <sort>","Sort by: votes|recent|trending","recent").option("--format <format>","Output format","text").action(async i=>{await yi(i)}),r.command("submit").description("Submit new idea").option("--title <title>","Idea title").option("--description <description>","Idea description").option("--tags <tags>","Comma-separated tags").option("--dry-run","Preview without making changes").action(async i=>{await hi(i)}),r.command("vote <id>").description("Upvote an idea").option("--dry-run","Preview without making changes").action(async(i,l)=>{await bi(i,l)}),r.command("claim <id>").description("Claim an idea to work on").option("--dry-run","Preview without making changes").action(async(i,l)=>{await vi(i,l)}),r.command("comment <id>").description("Comment on an idea").option("--message <message>","Comment text").option("--dry-run","Preview without making changes").action(async(i,l)=>{await wi(i,l)});let o=t.command("opc",{hidden:!0}).description("Legacy member directory");o.command("list").description("Browse legacy member profiles").option("--skill <skill>","Filter by skill tag").option("--industry <industry>","Filter by industry").option("--sort <sort>","Sort by: active|joined","active").option("--format <format>","Output format","text").action(async i=>{await Si(i)}),o.command("profile").description("View/edit your legacy member profile").action(async()=>{await Ri()}),o.command("register").description("Register a legacy member profile").option("--yes","Skip confirmations").option("--dry-run","Preview without making changes").action(async i=>{await Ci(i)});let a=t.command("showcase").description("Project showcase");a.command("list").description("Browse showcased projects").option("--category <category>","Filter by category").option("--featured","Show featured only").option("--format <format>","Output format","text").action(async i=>{await Ei(i)}),a.command("submit").description("Submit your project to showcase").option("--yes","Skip confirmations").option("--dry-run","Preview without making changes").action(async i=>{await ki(i)}),a.command("vote <id>").description("Upvote a project (Product Hunt style)").option("--dry-run","Preview without making changes").action(async(i,l)=>{await xi(i,l)}),t.command("sync").description("Sync local project with ecosystem").option("--pull","Pull remote changes").option("--push","Push local changes").option("--dry-run","Preview without making changes").action(async i=>{await Oi(i)})}import{existsSync as wt,readFileSync as hr,writeFileSync as Ai}from"fs";import{resolve as St}from"path";import*as Ie from"@clack/prompts";import _i from"picocolors";function Rt(e){let t=St(e,".env.example");if(!wt(t))throw new Error(`.env.example not found at ${t}`);let n=hr(t,"utf-8"),r={};for(let o of n.split(`
|
|
437
|
+
`)){if(o.trim().startsWith("#")||!o.trim())continue;let a=o.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/);if(a){let[,i,l]=a;r[i]=l.replace(/^["'](.*)["']$/,"$1")}}return r}function Wt(e){let t=St(e,".env.local"),n=St(e,".env"),r=wt(t)?t:n;if(!wt(r))return{};let o=hr(r,"utf-8"),a={};for(let i of o.split(`
|
|
438
|
+
`)){if(i.trim().startsWith("#")||!i.trim())continue;let l=i.match(/^([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/);if(l){let[,u,m]=l;a[u]=m.replace(/^["'](.*)["']$/,"$1")}}return a}function Pi(e,t){return["SECRET","KEY","TOKEN","PASSWORD"].some(o=>e.toUpperCase().includes(o))&&t.length>0}function Ii(e){return e.length<=8?"*".repeat(Math.max(e.length,4)):e.substring(0,4)+"*".repeat(e.length-8)+e.substring(e.length-4)}async function Ni(e){d("Validating environment variables...","info");let t=h(),n=Rt(t),r=Wt(t),o=process.env,a={},i=!0;for(let l of Object.keys(n)){let u=l in r||l in o;a[l]=u,u||(i=!1)}if(e.format==="json")R({valid:i,checked:Object.keys(n).length,missing:Object.entries(a).filter(([,l])=>!l).map(([l])=>l)},{format:"json"});else{mt("Environment Validation");let l=Object.entries(a).filter(([,u])=>!u).map(([u])=>u);if(l.length===0)d("All required environment variables are set","success");else{d(`${l.length} missing environment variable(s):`,"warn");for(let u of l)d(` - ${u}`,"warn")}}i||process.exit(c.CONFIG_ERROR)}async function $i(e){let t=h(),n=Rt(t),r=St(t,".env.local");if(wt(r)&&!e.yes&&!e.dryRun){let u=await Ie.confirm({message:".env.local already exists. Overwrite?",initialValue:!1});(Ie.isCancel(u)||!u)&&(d("Template generation cancelled","warn"),process.exit(c.CANCELLED))}d("Generating .env.local from template...","info");let o={},a=0,i=Object.keys(n).length;for(let[u,m]of Object.entries(n))if(a++,e.yes)o[u]=m;else if(process.stdin.isTTY===!0){let f=`[${a}/${i}] ${u}`,y=await Ie.text({message:f,defaultValue:m});Ie.isCancel(y)&&(d("Template generation cancelled","warn"),process.exit(c.CANCELLED)),o[u]=y}else o[u]=m;let l=Object.entries(o).map(([u,m])=>{let y=/[\s=]/.test(m)?`"${m}"`:m;return`${u}=${y}`}).join(`
|
|
439
|
+
`);e.dryRun?(d("Dry-run: would write .env.local","info"),R(l,{format:"plain"})):(Ai(r,l+`
|
|
440
|
+
`),d(`Environment template written to ${r}`,"success"))}async function Ti(e){d("Comparing environment variables...","info");let t=h(),n=Rt(t),r=Wt(t),o=[],a=[],i=[];for(let l of Object.keys(n))l in r?i.push(l):o.push(l);for(let l of Object.keys(r))l in n||a.push(l);if(e.format==="json")R({matching:i.length,missing:o.length,extra:a.length,missing_vars:o,extra_vars:a},{format:"json"});else{if(mt("Environment Diff"),i.length>0&&d(`Matching (${i.length}): ${i.join(", ")}`,"success"),o.length>0){d(`Missing (${o.length}):`,"warn");for(let l of o)d(` - ${l}`,"warn")}if(a.length>0){d(`Extra (${a.length}):`,"info");for(let l of a)d(` - ${l}`,"info")}}}async function Ui(e){d("Reading environment variables...","info");let t=h(),n=Wt(t),r=Rt(t),o={};for(let a of Object.keys(r))if(a in n){let i=n[a];o[a]=Pi(a,i)?Ii(i):i||"(empty)"}else o[a]="(not set)";if(e.format==="json"){let a={};for(let[i,l]of Object.entries(o))a[i]=l;R(a,{format:"json"})}else{mt("Current Environment Variables");let a=Object.entries(o).map(([i,l])=>({Variable:_i.cyan(i),Value:l}));R(a,{format:"table"}),d("Note: Sensitive values (KEY, TOKEN, SECRET, PASSWORD) are masked","info")}}function br(e){e.command("env <verb>").description("Manage environment variables and configuration").option("--dry-run","Show what would be done without making changes").option("--yes","Skip confirmations and use defaults").option("--format <type>","Output format: json, plain","plain").action(async(n,r)=>{let o=r.optsWithGlobals?.(),a={dryRun:r.dryRun||o?.dryRun,yes:r.yes||o?.yes,format:r.format||o?.format};try{switch(n){case"validate":await Ni(a);break;case"template":await $i(a);break;case"diff":await Ti(a);break;case"show":await Ui(a);break;default:d(`Unknown env subcommand: ${n}. Valid commands: validate, template, diff, show`,"error"),process.exit(c.INVALID_ARGS)}}catch(i){let l=i instanceof Error?i.message:String(i);d(`Environment command failed: ${l}`,"error"),k("Full error",{error:i}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
438
441
|
Examples:
|
|
439
442
|
nebutra env validate Check all required vars are set
|
|
440
443
|
nebutra env template Generate .env.local from .env.example with prompts
|
|
@@ -451,7 +454,7 @@ Flags:
|
|
|
451
454
|
Sensitive Variables:
|
|
452
455
|
Variables with KEY, TOKEN, SECRET, PASSWORD in their names are masked in output.
|
|
453
456
|
This prevents accidental exposure of credentials.
|
|
454
|
-
`)}import{promises as
|
|
457
|
+
`)}import{promises as vr}from"fs";import{join as Ne}from"path";import*as Xe from"@clack/prompts";import L from"picocolors";var Je=["design","iam","commerce","integrations","platform","ops","ai"];function ji(e){return Je.includes(e)}function Jt(e,t){if(!t)throw new Error(`--category is required. Valid categories: ${Je.join(", ")}. Example: nebutra generate package ${e} --category iam`);if(!ji(t))throw new Error(`Unknown category "${t}". Valid categories: ${Je.join(", ")}.`);return`packages/${t}/${e}`}function wr(e){let t=e.split("-").map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return{"package.json":`{
|
|
455
458
|
"name": "@nebutra/${e}",
|
|
456
459
|
"version": "0.0.0",
|
|
457
460
|
"private": true,
|
|
@@ -536,7 +539,7 @@ export default function RootLayout({
|
|
|
536
539
|
|
|
537
540
|
@theme {
|
|
538
541
|
--color-*: var(--neutral-*);
|
|
539
|
-
}`}}function
|
|
542
|
+
}`}}function Sr(e){return{"package.json":`{
|
|
540
543
|
"name": "@nebutra/${e}",
|
|
541
544
|
"version": "0.0.0",
|
|
542
545
|
"type": "module",
|
|
@@ -624,7 +627,7 @@ app.post("/", async (c) => {
|
|
|
624
627
|
);
|
|
625
628
|
});
|
|
626
629
|
|
|
627
|
-
export default app;`}}function
|
|
630
|
+
export default app;`}}function Cr(e){let t=e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),n=e.split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("");return{[`src/components/${t}.tsx`]:`import { cva, type VariantProps } from "class-variance-authority";
|
|
628
631
|
import { cn } from "@nebutra/ui/utils";
|
|
629
632
|
|
|
630
633
|
const ${t}Variants = cva(
|
|
@@ -698,13 +701,13 @@ export const AllSizes: Story = {
|
|
|
698
701
|
<${n} size="lg">Large</\${pascalCase}>
|
|
699
702
|
</div>
|
|
700
703
|
),
|
|
701
|
-
};`}}async function
|
|
702
|
-
`),process.exit(c.DRY_RUN_OK)}
|
|
703
|
-
`),process.exit(c.DRY_RUN_OK)}
|
|
704
|
-
`),process.exit(c.DRY_RUN_OK)}
|
|
705
|
-
`),process.exit(c.DRY_RUN_OK)}Ze.intro(L.bgCyan(L.black(" nebutra generate component ")));let n=s.spinner();try{n.start(`Generating component ${L.cyan(e)}...`);let r=await xt("component",e);n.stop(`Created component ${L.cyan(e)}`,0),s.success(`Component created with ${r.length} files`),s.info("Files created in packages/design/ui/src/components/"),s.info("Next steps:"),s.info(" 1. Add export to packages/design/ui/src/components/index.ts"),s.info(" 2. pnpm --filter @nebutra/ui typecheck"),s.info(" 3. pnpm --filter @nebutra/storybook dev"),process.exit(c.SUCCESS)}catch(r){n.stop(`Failed to generate component: ${r instanceof Error?r.message:"Unknown error"}`,1),process.exit(c.ERROR)}}var Cr=e=>{let t=e.command("generate").description("Scaffold a new app, package, route, or component").alias("gen");t.command("app <name>").description("Scaffold a new Next.js app (Next.js 16 + Tailwind v4)").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").option("--template <type>","App template (default: nextjs)","nextjs").option("--port <number>","Dev server port","3000").action(async(n,r,o)=>{let a=x(r,o);await ji(n,{dryRun:!!r.dryRun,yes:!!a.yes,interactive:!!process.stdin.isTTY,template:(r.template==="nextjs","nextjs"),port:typeof r.port=="string"?Number(r.port):void 0})}),t.command("package <name>").description(`Scaffold a new categorized package (@nebutra/<name>). Categories: ${Qe.join(", ")}`).requiredOption("--category <category>",`Package category: ${Qe.join(" | ")}`).option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").action(async(n,r,o)=>{let a=x(r,o);await Li(n,{category:String(r.category??""),dryRun:!!r.dryRun,yes:!!a.yes})}),t.command("route <path>").description("Scaffold a Hono API route in backends/gateway").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").action(async(n,r,o)=>{let a=x(r,o);await Di(n,{dryRun:!!r.dryRun,yes:!!a.yes})}),t.command("component <name>").description("Scaffold a UI component with Storybook story").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").option("--variants <list>","Comma-separated variant names (e.g., 'primary,secondary')").option("--sizes <list>","Comma-separated size names (e.g., 'sm,md,lg')").action(async(n,r,o)=>{let a=x(r,o);await Fi(n,{dryRun:!!r.dryRun,yes:!!a.yes,variants:typeof r.variants=="string"?r.variants:void 0,sizes:typeof r.sizes=="string"?r.sizes:void 0})})};import Ve from"picocolors";async function J(e,t){let n=await h(),r=new URL(e,"http://localhost:3000/api/growth");t?.query&&Object.entries(t.query).forEach(([a,i])=>{r.searchParams.set(a,i)});let o=await fetch(r,{method:t?.method||"GET",headers:{"Content-Type":"application/json"},body:t?.body?JSON.stringify(t.body):void 0});if(!o.ok)throw new Error(`Growth API error (${o.status}): ${await o.text()}`);return o.json()}async function Bi(e){try{let t=e.period||"7d",n=e.compare;s.info(`Fetching growth metrics for ${t}...`);let r=await J("/summary",{query:{period:t,compare:n?"true":"false"}});return c.SUCCESS}catch(t){return s.error(`Dashboard error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Mi(e){try{let t=e.period||"7d",n=e.segment||"all";s.info(`Fetching funnel data for ${t} (${n})...`);let r=await J("/funnel",{query:{period:t,segment:n}});return r.forEach((a,i)=>{let l="\u2588".repeat(Math.ceil(a.rate*20)),u="\u2591".repeat(20-Math.ceil(a.rate*20)),m=i<r.length-1?Ve.red(`\u2193 ${(a.dropoff_rate*100).toFixed(1)}% drop`):""}),r.reduce((a,i)=>i.dropoff_rate>a.dropoff_rate?i:a).dropoff_rate>.2,c.SUCCESS}catch(t){return s.error(`Funnel error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Gi(e){try{let t=e.period||"weekly",n=parseInt(e.cohorts,10)||8;s.info(`Fetching ${t} cohort data (${n} cohorts)...`);let r=await J("/cohort",{query:{period:t,cohorts:String(n)}});if(r.length===0)return c.SUCCESS;let o=Object.keys(r[0]).slice(1);return r.forEach(a=>{let l=String(a.cohort).padEnd(15);o.forEach(u=>{let m=a[u];if(typeof m=="number"){let f=m/100,y=String(Math.round(m)).padEnd(8);f>=.7?y=Ve.green(y):f>=.4?y=Ve.yellow(y):y=Ve.red(y),l+=y+" "}})}),c.SUCCESS}catch(t){return s.error(`Cohort error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Vi(e,t){try{if(e==="stats"){s.info("Fetching newsletter stats...");let n=await J("/newsletter/stats");return c.SUCCESS}if(e==="subscribers"){let n=parseInt(t.limit,10)||10,r=parseInt(t.offset,10)||0;return s.info(`Fetching ${n} newsletter subscribers (offset ${r})...`),(await J("/newsletter/subscribers",{query:{limit:String(n),offset:String(r)}})).forEach(a=>{}),c.SUCCESS}if(e==="send"){let n=t.template;return n?t.yes?(s.info(`Sending newsletter with template: ${n}`),await J("/newsletter/send",{method:"POST",body:{template_id:n}}),c.SUCCESS):(s.warn("Use --yes to confirm newsletter send"),c.ERROR):(s.error("--template is required"),c.ERROR)}return s.error(`Unknown newsletter subcommand: ${e}`),c.ERROR}catch(n){return s.error(`Newsletter error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function Ki(e,t){try{if(e==="status"){s.info("Fetching referral program status...");let n=await J("/referral/status");return c.SUCCESS}if(e==="config"){s.info("Fetching referral config...");let n=await J("/referral/config");return Object.entries(n).forEach(([r,o])=>{}),c.SUCCESS}return e==="leaderboard"?(s.info("Fetching referral leaderboard..."),(await J("/referral/leaderboard")).forEach(r=>{let o=r.rank===1?"\u{1F947}":r.rank===2?"\u{1F948}":"\u{1F949}"}),c.SUCCESS):(s.error(`Unknown referral subcommand: ${e}`),c.ERROR)}catch(n){return s.error(`Referral error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function qi(e,t){try{if(e==="list"){s.info("Fetching active experiments...");let n=await J("/experiment");return n.length===0?c.SUCCESS:(n.forEach(r=>{let o=r.status==="running"?Ve.yellow("\u25CF"):Ve.green("\u2713")}),c.SUCCESS)}if(e==="create"){let n=t.name,r=t.variants?.split(","),o=t.metric;if(!n||!r||!o)return s.error("Required: --name <name> --variants <A,B> --metric <metric>"),c.ERROR;s.info(`Creating experiment: ${n}`);let a=await J("/experiment",{method:"POST",body:{name:n,variants:r,metric:o}});return c.SUCCESS}if(e==="results"){let n=t.id;if(!n)return s.error("--id is required"),c.ERROR;s.info(`Fetching results for experiment ${n}...`);let r=await J(`/experiment/${n}`);return r.winner,r.significance,c.SUCCESS}if(e==="conclude"){let n=t.id,r=t.winner;return!n||!r?(s.error("Required: --id <id> --winner <variant>"),c.ERROR):t.yes?(s.info(`Concluding experiment ${n} with winner: ${r}`),await J(`/experiment/${n}`,{method:"POST",body:{action:"conclude",winner:r}}),c.SUCCESS):(s.warn("Use --yes to confirm experiment conclusion"),c.ERROR)}return s.error(`Unknown experiment subcommand: ${e}`),c.ERROR}catch(n){return s.error(`Experiment error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function zi(e){try{let t=e.focus||"activation",n=e.depth||"quick";s.info(`Generating growth insights (focus: ${t}, depth: ${n})...`);let r=await J("/pulse",{query:{focus:t,depth:n}});return r.insights.forEach(o=>{}),r.recommendations.forEach(o=>{}),c.SUCCESS}catch(t){return s.error(`Pulse error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}function Er(e){let t=e.command("growth").description("Growth engine operations \u2014 metrics, funnel, cohorts, AI insights");t.command("dashboard").description("Growth metrics overview").option("--period <7d|30d|90d>","Time period","7d").option("--compare","Show period-over-period deltas").action(async a=>{process.exit(await Bi(a))}),t.command("funnel").description("Conversion funnel analysis").option("--period <7d|30d|90d>","Time period","7d").option("--segment <organic|paid|referral>","Traffic segment","all").action(async a=>{process.exit(await Mi(a))}),t.command("cohort").description("Cohort retention analysis").option("--period <weekly|monthly>","Cohort period","weekly").option("--cohorts <n>","Number of cohorts","8").action(async a=>{process.exit(await Gi(a))}),t.command("newsletter <subcommand>").description("Newsletter management").action(async(a,i)=>{process.exit(await Vi(a,i))}),t.command("referral <subcommand>").description("Referral program management").action(async(a,i)=>{process.exit(await Ki(a,i))}),t.command("experiment <subcommand>").description("A/B testing and experiment management").option("--id <id>","Experiment ID").option("--name <name>","Experiment name").option("--variants <A,B>","Comma-separated variants").option("--metric <metric>","Success metric").option("--winner <variant>","Winning variant").action(async(a,i)=>{process.exit(await qi(a,i))}),t.command("pulse").description("AI-generated growth insights (AARRR: Acquisition, Activation, Retention, Revenue, Referral)").option("--focus <aarrr>","Focus area (acquisition|activation|retention|revenue|referral)","activation").option("--depth <quick|deep>","Analysis depth","quick").action(async a=>{process.exit(await zi(a))}),t.option("--dry-run","Preview changes without applying them").option("--format <json|text>","Output format","text").option("--yes","Skip confirmation prompts")}import Qt,{lstatSync as Yi,readdirSync as Zt,readFileSync as Hi,writeFileSync as Wi}from"fs";import ge from"path";import{fileURLToPath as Ji}from"url";import te from"picocolors";var Xi=ge.dirname(Ji(import.meta.url));function en(){let e=new Map,t=ge.join(Xi,"../../../apps");if(!Qt.existsSync(t))return e;try{let n=Zt(t);for(let r of n){let o=ge.join(t,r),a=ge.join(o,"messages");Qt.existsSync(a)&&Yi(a).isDirectory()&&e.set(r,a)}}catch(n){s.debug(`Error scanning apps directory: ${n instanceof Error?n.message:String(n)}`)}return e}function et(e,t=""){let n=new Set;for(let[r,o]of Object.entries(e)){let a=t?`${t}.${r}`:r;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=et(o,a);for(let l of i)n.add(l)}else n.add(a)}return n}function tt(e){try{let t=Hi(e,"utf-8");return JSON.parse(t)}catch(t){return s.debug(`Failed to parse ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async function Qi(e){if(s.info("Syncing language files across the project..."),(await z("translate",{filter:"landing",dryRun:e.dryRun,interactive:e.interactive??!0})).exitCode!==0){s.warn("Landing page translate script not found or failed. Trying sync-lang.mjs...");let n=await O({command:"node",args:["scripts/sync-lang.mjs"],dryRun:e.dryRun,interactive:e.interactive??!0,label:"Sync language files"});n.exitCode!==0&&(s.error("Failed to sync language files"),process.exit(n.exitCode)),e.format==="json"?console.log(JSON.stringify({command:"i18n:sync",exitCode:0,success:!0},null,2)):e.dryRun||s.success("Language files synced successfully")}else e.format==="json"?console.log(JSON.stringify({command:"i18n:sync",exitCode:0,success:!0},null,2)):e.dryRun||s.success("Language files synced successfully")}async function Zi(e){s.info("Validating translation files...");let t=en();t.size===0&&(s.warn("No message directories found in the project"),process.exit(c.NOT_FOUND));let n=new Map,r=!1;for(let[o,a]of t){let i=[];try{let l=Zt(a).filter(y=>y.endsWith(".json"));if(l.length===0)continue;let u=ge.join(a,"en.json"),m=tt(u);if(!m){s.warn(`Could not load reference locale en.json from ${o}`);continue}let f=et(m);for(let y of l){if(y==="en.json")continue;let E=y.replace(".json",""),D=ge.join(a,y),F=tt(D);if(!F){s.debug(`Could not parse ${y}`);continue}let q=et(F),ye=Array.from(f).filter(p=>!q.has(p)),ue=Array.from(q).filter(p=>!f.has(p)),_e=f.size>0?(f.size-ye.length)/f.size*100:100;(ye.length>0||ue.length>0)&&(r=!0),i.push({locale:E,totalKeys:f.size,missingKeys:ye,extraKeys:ue,coverage:Math.round(_e*100)/100})}i.length>0&&n.set(o,i)}catch(l){s.debug(`Error validating ${o}: ${l instanceof Error?l.message:String(l)}`)}}if(e.format==="json"){let o={command:"i18n:validate",success:!r,results:Array.from(n.entries()).reduce((a,[i,l])=>(a[i]=l,a),{})};console.log(JSON.stringify(o,null,2))}else for(let[o,a]of n){s.info(`${te.bold(o)}:`);for(let i of a){let u=(i.coverage>=100?te.green:i.coverage>=80?te.yellow:te.red)(`${i.coverage}%`);s.info(` ${te.cyan(i.locale.padEnd(5))} ${u.padEnd(20)} [${i.totalKeys} keys]`),i.missingKeys.length>0&&s.warn(` Missing: ${i.missingKeys.slice(0,5).join(", ")}${i.missingKeys.length>5?` (+ ${i.missingKeys.length-5} more)`:""}`),i.extraKeys.length>0&&s.warn(` Extra: ${i.extraKeys.slice(0,5).join(", ")}${i.extraKeys.length>5?` (+ ${i.extraKeys.length-5} more)`:""}`)}}r&&process.exit(c.CONFLICT)}async function ec(e,t){/^[a-z]{2}(-[A-Z]{2})?$/.test(e)||(s.error(`Invalid locale format: ${e}. Use 'en', 'es', 'zh-CN', etc.`),process.exit(c.INVALID_ARGS));let n=en();n.size===0&&(s.error("No message directories found in the project"),process.exit(c.NOT_FOUND));let r=[],o=!1;for(let[i,l]of n){let u=ge.join(l,`${e}.json`);if(Qt.existsSync(u)){s.warn(`Locale ${e} already exists in ${i}`);continue}try{let E=function(D){for(let F in D)typeof D[F]=="string"?D[F]="":typeof D[F]=="object"&&D[F]!==null&&E(D[F])};var a=E;let m=ge.join(l,"en.json"),f=tt(m);if(!f){s.warn(`Could not load reference en.json from ${i}, skipping...`);continue}let y=JSON.parse(JSON.stringify(f));E(y),t.dryRun?s.info(`Would create ${e} locale in ${i}`):(Wi(u,JSON.stringify(y,null,2)+`
|
|
706
|
-
`),r.push({app:i,path:u}),s.success(`Created ${e} locale in ${i}`))}catch(m){s.error(`Failed to create locale in ${i}: ${m instanceof Error?m.message:String(m)}`),o=!0}}t.format==="json"?console.log(JSON.stringify({command:"i18n:add",locale:e,dryRun:t.dryRun||!1,created:r,success:!o},null,2)):t.dryRun||s.success(`Locale '${e}' added to ${r.length} app(s)`),o&&process.exit(c.ERROR)}async function
|
|
707
|
-
Average coverage: ${i(a.toFixed(1)+"%")}`)}}}function
|
|
704
|
+
};`}}async function Ct(e,t,n){let r=h(),o=[],a={};switch(e){case"app":a=wr(t);break;case"package":a=Sr(t);break;case"route":a=Rr(t);break;case"component":a=Cr(t);break;default:throw new Error(`Unknown generate type: ${e}`)}let i=e==="package"?Jt(t,n.category):void 0;for(let[l,u]of Object.entries(a)){let m=e==="app"?Ne(r,"apps",t,l):e==="package"?Ne(r,i??`packages/${t}`,l):Ne(r,"backends/gateway",l);o.push({path:m,size:Buffer.byteLength(u)})}return o}async function Et(e,t,n={}){let r=h(),o=[],a={};switch(e){case"app":a=wr(t);break;case"package":a=Sr(t);break;case"route":a=Rr(t);break;case"component":a=Cr(t);break;default:throw new Error(`Unknown generate type: ${e}`)}let i=e==="package"?Jt(t,n.category):void 0;for(let[l,u]of Object.entries(a)){let m;e==="app"?m=Ne(r,"apps",t,l):e==="package"?m=Ne(r,i??`packages/${t}`,l):e==="component"?m=Ne(r,"packages/design/ui",l):m=Ne(r,"backends/gateway",l);let f=m.substring(0,m.lastIndexOf("/"));await vr.mkdir(f,{recursive:!0}),await vr.writeFile(m,u,"utf-8"),o.push(m)}return o}async function Li(e,t){if(t.dryRun){let r=await Ct("app",e,t),o={mode:"dry-run",timestamp:new Date().toISOString(),type:"app",name:e,location:`apps/${e}`,files:r.map(a=>({path:a.path,sizeBytes:a.size})),instructions:[`cd apps/${e}`,"pnpm install","pnpm run dev"]};process.stdout.write(JSON.stringify(o,null,2)+`
|
|
705
|
+
`),process.exit(c.DRY_RUN_OK)}Xe.intro(L.bgCyan(L.black(" nebutra generate app ")));let n=s.spinner();try{n.start(`Generating app ${L.cyan(e)}...`);let r=await Et("app",e);n.stop(`Created app ${L.cyan(e)}`,0),s.success(`App created with ${r.length} files`),s.info("Next steps:"),s.info(` cd apps/${e}`),s.info(" pnpm install"),s.info(" pnpm run dev"),process.exit(c.SUCCESS)}catch(r){n.stop(`Failed to generate app: ${r instanceof Error?r.message:"Unknown error"}`,1),process.exit(c.ERROR)}}async function Di(e,t){let n;try{n=Jt(e,t.category)}catch(o){s.error(o instanceof Error?o.message:String(o)),process.exit(c.INVALID_ARGS)}if(t.dryRun){let o=await Ct("package",e,t),a={mode:"dry-run",timestamp:new Date().toISOString(),type:"package",name:e,category:t.category,location:n,files:o.map(i=>({path:i.path,sizeBytes:i.size}))};process.stdout.write(JSON.stringify(a,null,2)+`
|
|
706
|
+
`),process.exit(c.DRY_RUN_OK)}Xe.intro(L.bgCyan(L.black(" nebutra generate package ")));let r=s.spinner();try{r.start(`Generating package ${L.cyan(e)} in ${L.dim(n)}...`);let o=await Et("package",e,{category:t.category});r.stop(`Created package ${L.cyan(e)}`,0),s.success(`Package created with ${o.length} files`),s.info("Next steps:"),s.info(` Edit ${n}/src/index.ts`),s.info(` Run: pnpm --filter @nebutra/${e} build`),process.exit(c.SUCCESS)}catch(o){r.stop(`Failed to generate package: ${o instanceof Error?o.message:"Unknown error"}`,1),process.exit(c.ERROR)}}async function Fi(e,t){if(t.dryRun){let r=await Ct("route",e,t),o={mode:"dry-run",timestamp:new Date().toISOString(),type:"route",path:e,location:`backends/gateway/src/routes/${e}.ts`,files:r.map(a=>({path:a.path,sizeBytes:a.size}))};process.stdout.write(JSON.stringify(o,null,2)+`
|
|
707
|
+
`),process.exit(c.DRY_RUN_OK)}Xe.intro(L.bgCyan(L.black(" nebutra generate route ")));let n=s.spinner();try{n.start(`Generating route ${L.cyan(e)}...`);let r=await Et("route",e);n.stop(`Created route ${L.cyan(e)}`,0),s.success(`Route created with ${r.length} files`),s.info(`File: backends/gateway/src/routes/${e}.ts`),s.info(`Add to your main app.ts: app.route("/${e}", routes)`),process.exit(c.SUCCESS)}catch(r){n.stop(`Failed to generate route: ${r instanceof Error?r.message:"Unknown error"}`,1),process.exit(c.ERROR)}}async function Bi(e,t){if(t.dryRun){let r=await Ct("component",e,t),o={mode:"dry-run",timestamp:new Date().toISOString(),type:"component",name:e,location:"packages/design/ui/src/components/",files:r.map(a=>({path:a.path,sizeBytes:a.size})),nextSteps:["Add export to packages/design/ui/src/components/index.ts","Run: pnpm --filter @nebutra/ui typecheck","View in Storybook: pnpm --filter @nebutra/storybook dev"]};process.stdout.write(JSON.stringify(o,null,2)+`
|
|
708
|
+
`),process.exit(c.DRY_RUN_OK)}Xe.intro(L.bgCyan(L.black(" nebutra generate component ")));let n=s.spinner();try{n.start(`Generating component ${L.cyan(e)}...`);let r=await Et("component",e);n.stop(`Created component ${L.cyan(e)}`,0),s.success(`Component created with ${r.length} files`),s.info("Files created in packages/design/ui/src/components/"),s.info("Next steps:"),s.info(" 1. Add export to packages/design/ui/src/components/index.ts"),s.info(" 2. pnpm --filter @nebutra/ui typecheck"),s.info(" 3. pnpm --filter @nebutra/storybook dev"),process.exit(c.SUCCESS)}catch(r){n.stop(`Failed to generate component: ${r instanceof Error?r.message:"Unknown error"}`,1),process.exit(c.ERROR)}}var Er=e=>{let t=e.command("generate").description("Scaffold a new app, package, route, or component").alias("gen");t.command("app <name>").description("Scaffold a new Next.js app (Next.js 16 + Tailwind v4)").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").option("--template <type>","App template (default: nextjs)","nextjs").option("--port <number>","Dev server port","3000").action(async(n,r,o)=>{let a=x(r,o);await Li(n,{dryRun:!!r.dryRun,yes:!!a.yes,interactive:!!process.stdin.isTTY,template:(r.template==="nextjs","nextjs"),port:typeof r.port=="string"?Number(r.port):void 0})}),t.command("package <name>").description(`Scaffold a new categorized package (@nebutra/<name>). Categories: ${Je.join(", ")}`).requiredOption("--category <category>",`Package category: ${Je.join(" | ")}`).option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").action(async(n,r,o)=>{let a=x(r,o);await Di(n,{category:String(r.category??""),dryRun:!!r.dryRun,yes:!!a.yes})}),t.command("route <path>").description("Scaffold a Hono API route in backends/gateway").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").action(async(n,r,o)=>{let a=x(r,o);await Fi(n,{dryRun:!!r.dryRun,yes:!!a.yes})}),t.command("component <name>").description("Scaffold a UI component with Storybook story").option("--dry-run","Preview changes without writing files").option("--yes","Skip all prompts").option("--variants <list>","Comma-separated variant names (e.g., 'primary,secondary')").option("--sizes <list>","Comma-separated size names (e.g., 'sm,md,lg')").action(async(n,r,o)=>{let a=x(r,o);await Bi(n,{dryRun:!!r.dryRun,yes:!!a.yes,variants:typeof r.variants=="string"?r.variants:void 0,sizes:typeof r.sizes=="string"?r.sizes:void 0})})};import Ge from"picocolors";async function J(e,t){let n=await h(),r=new URL(e,"http://localhost:3000/api/growth");t?.query&&Object.entries(t.query).forEach(([a,i])=>{r.searchParams.set(a,i)});let o=await fetch(r,{method:t?.method||"GET",headers:{"Content-Type":"application/json"},body:t?.body?JSON.stringify(t.body):void 0});if(!o.ok)throw new Error(`Growth API error (${o.status}): ${await o.text()}`);return o.json()}async function Mi(e){try{let t=e.period||"7d",n=e.compare;s.info(`Fetching growth metrics for ${t}...`);let r=await J("/summary",{query:{period:t,compare:n?"true":"false"}});return c.SUCCESS}catch(t){return s.error(`Dashboard error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Gi(e){try{let t=e.period||"7d",n=e.segment||"all";s.info(`Fetching funnel data for ${t} (${n})...`);let r=await J("/funnel",{query:{period:t,segment:n}});return r.forEach((a,i)=>{let l="\u2588".repeat(Math.ceil(a.rate*20)),u="\u2591".repeat(20-Math.ceil(a.rate*20)),m=i<r.length-1?Ge.red(`\u2193 ${(a.dropoff_rate*100).toFixed(1)}% drop`):""}),r.reduce((a,i)=>i.dropoff_rate>a.dropoff_rate?i:a).dropoff_rate>.2,c.SUCCESS}catch(t){return s.error(`Funnel error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Vi(e){try{let t=e.period||"weekly",n=parseInt(e.cohorts,10)||8;s.info(`Fetching ${t} cohort data (${n} cohorts)...`);let r=await J("/cohort",{query:{period:t,cohorts:String(n)}});if(r.length===0)return c.SUCCESS;let o=Object.keys(r[0]).slice(1);return r.forEach(a=>{let l=String(a.cohort).padEnd(15);o.forEach(u=>{let m=a[u];if(typeof m=="number"){let f=m/100,y=String(Math.round(m)).padEnd(8);f>=.7?y=Ge.green(y):f>=.4?y=Ge.yellow(y):y=Ge.red(y),l+=y+" "}})}),c.SUCCESS}catch(t){return s.error(`Cohort error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}async function Ki(e,t){try{if(e==="stats"){s.info("Fetching newsletter stats...");let n=await J("/newsletter/stats");return c.SUCCESS}if(e==="subscribers"){let n=parseInt(t.limit,10)||10,r=parseInt(t.offset,10)||0;return s.info(`Fetching ${n} newsletter subscribers (offset ${r})...`),(await J("/newsletter/subscribers",{query:{limit:String(n),offset:String(r)}})).forEach(a=>{}),c.SUCCESS}if(e==="send"){let n=t.template;return n?t.yes?(s.info(`Sending newsletter with template: ${n}`),await J("/newsletter/send",{method:"POST",body:{template_id:n}}),c.SUCCESS):(s.warn("Use --yes to confirm newsletter send"),c.ERROR):(s.error("--template is required"),c.ERROR)}return s.error(`Unknown newsletter subcommand: ${e}`),c.ERROR}catch(n){return s.error(`Newsletter error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function qi(e,t){try{if(e==="status"){s.info("Fetching referral program status...");let n=await J("/referral/status");return c.SUCCESS}if(e==="config"){s.info("Fetching referral config...");let n=await J("/referral/config");return Object.entries(n).forEach(([r,o])=>{}),c.SUCCESS}return e==="leaderboard"?(s.info("Fetching referral leaderboard..."),(await J("/referral/leaderboard")).forEach(r=>{let o=r.rank===1?"\u{1F947}":r.rank===2?"\u{1F948}":"\u{1F949}"}),c.SUCCESS):(s.error(`Unknown referral subcommand: ${e}`),c.ERROR)}catch(n){return s.error(`Referral error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function zi(e,t){try{if(e==="list"){s.info("Fetching active experiments...");let n=await J("/experiment");return n.length===0?c.SUCCESS:(n.forEach(r=>{let o=r.status==="running"?Ge.yellow("\u25CF"):Ge.green("\u2713")}),c.SUCCESS)}if(e==="create"){let n=t.name,r=t.variants?.split(","),o=t.metric;if(!n||!r||!o)return s.error("Required: --name <name> --variants <A,B> --metric <metric>"),c.ERROR;s.info(`Creating experiment: ${n}`);let a=await J("/experiment",{method:"POST",body:{name:n,variants:r,metric:o}});return c.SUCCESS}if(e==="results"){let n=t.id;if(!n)return s.error("--id is required"),c.ERROR;s.info(`Fetching results for experiment ${n}...`);let r=await J(`/experiment/${n}`);return r.winner,r.significance,c.SUCCESS}if(e==="conclude"){let n=t.id,r=t.winner;return!n||!r?(s.error("Required: --id <id> --winner <variant>"),c.ERROR):t.yes?(s.info(`Concluding experiment ${n} with winner: ${r}`),await J(`/experiment/${n}`,{method:"POST",body:{action:"conclude",winner:r}}),c.SUCCESS):(s.warn("Use --yes to confirm experiment conclusion"),c.ERROR)}return s.error(`Unknown experiment subcommand: ${e}`),c.ERROR}catch(n){return s.error(`Experiment error: ${n instanceof Error?n.message:String(n)}`),c.ERROR}}async function Yi(e){try{let t=e.focus||"activation",n=e.depth||"quick";s.info(`Generating growth insights (focus: ${t}, depth: ${n})...`);let r=await J("/pulse",{query:{focus:t,depth:n}});return r.insights.forEach(o=>{}),r.recommendations.forEach(o=>{}),c.SUCCESS}catch(t){return s.error(`Pulse error: ${t instanceof Error?t.message:String(t)}`),c.ERROR}}function kr(e){let t=e.command("growth").description("Growth engine operations \u2014 metrics, funnel, cohorts, AI insights");t.command("dashboard").description("Growth metrics overview").option("--period <7d|30d|90d>","Time period","7d").option("--compare","Show period-over-period deltas").action(async a=>{process.exit(await Mi(a))}),t.command("funnel").description("Conversion funnel analysis").option("--period <7d|30d|90d>","Time period","7d").option("--segment <organic|paid|referral>","Traffic segment","all").action(async a=>{process.exit(await Gi(a))}),t.command("cohort").description("Cohort retention analysis").option("--period <weekly|monthly>","Cohort period","weekly").option("--cohorts <n>","Number of cohorts","8").action(async a=>{process.exit(await Vi(a))}),t.command("newsletter <subcommand>").description("Newsletter management").action(async(a,i)=>{process.exit(await Ki(a,i))}),t.command("referral <subcommand>").description("Referral program management").action(async(a,i)=>{process.exit(await qi(a,i))}),t.command("experiment <subcommand>").description("A/B testing and experiment management").option("--id <id>","Experiment ID").option("--name <name>","Experiment name").option("--variants <A,B>","Comma-separated variants").option("--metric <metric>","Success metric").option("--winner <variant>","Winning variant").action(async(a,i)=>{process.exit(await zi(a,i))}),t.command("pulse").description("AI-generated growth insights (AARRR: Acquisition, Activation, Retention, Revenue, Referral)").option("--focus <aarrr>","Focus area (acquisition|activation|retention|revenue|referral)","activation").option("--depth <quick|deep>","Analysis depth","quick").action(async a=>{process.exit(await Yi(a))}),t.option("--dry-run","Preview changes without applying them").option("--format <json|text>","Output format","text").option("--yes","Skip confirmation prompts")}import Xt,{lstatSync as Hi,readdirSync as Qt,readFileSync as Wi,writeFileSync as Ji}from"fs";import ye from"path";import{fileURLToPath as Xi}from"url";import te from"picocolors";var Qi=ye.dirname(Xi(import.meta.url));function Zt(){let e=new Map,t=ye.join(Qi,"../../../apps");if(!Xt.existsSync(t))return e;try{let n=Qt(t);for(let r of n){let o=ye.join(t,r),a=ye.join(o,"messages");Xt.existsSync(a)&&Hi(a).isDirectory()&&e.set(r,a)}}catch(n){s.debug(`Error scanning apps directory: ${n instanceof Error?n.message:String(n)}`)}return e}function Qe(e,t=""){let n=new Set;for(let[r,o]of Object.entries(e)){let a=t?`${t}.${r}`:r;if(typeof o=="object"&&o!==null&&!Array.isArray(o)){let i=Qe(o,a);for(let l of i)n.add(l)}else n.add(a)}return n}function Ze(e){try{let t=Wi(e,"utf-8");return JSON.parse(t)}catch(t){return s.debug(`Failed to parse ${e}: ${t instanceof Error?t.message:String(t)}`),null}}async function Zi(e){if(s.info("Syncing language files across the project..."),(await z("translate",{filter:"landing",dryRun:e.dryRun,interactive:e.interactive??!0})).exitCode!==0){s.warn("Landing page translate script not found or failed. Trying sync-lang.mjs...");let n=await O({command:"node",args:["scripts/sync-lang.mjs"],dryRun:e.dryRun,interactive:e.interactive??!0,label:"Sync language files"});n.exitCode!==0&&(s.error("Failed to sync language files"),process.exit(n.exitCode)),e.format==="json"?console.log(JSON.stringify({command:"i18n:sync",exitCode:0,success:!0},null,2)):e.dryRun||s.success("Language files synced successfully")}else e.format==="json"?console.log(JSON.stringify({command:"i18n:sync",exitCode:0,success:!0},null,2)):e.dryRun||s.success("Language files synced successfully")}async function ec(e){s.info("Validating translation files...");let t=Zt();t.size===0&&(s.warn("No message directories found in the project"),process.exit(c.NOT_FOUND));let n=new Map,r=!1;for(let[o,a]of t){let i=[];try{let l=Qt(a).filter(y=>y.endsWith(".json"));if(l.length===0)continue;let u=ye.join(a,"en.json"),m=Ze(u);if(!m){s.warn(`Could not load reference locale en.json from ${o}`);continue}let f=Qe(m);for(let y of l){if(y==="en.json")continue;let E=y.replace(".json",""),D=ye.join(a,y),F=Ze(D);if(!F){s.debug(`Could not parse ${y}`);continue}let q=Qe(F),ue=Array.from(f).filter(p=>!q.has(p)),me=Array.from(q).filter(p=>!f.has(p)),Ae=f.size>0?(f.size-ue.length)/f.size*100:100;(ue.length>0||me.length>0)&&(r=!0),i.push({locale:E,totalKeys:f.size,missingKeys:ue,extraKeys:me,coverage:Math.round(Ae*100)/100})}i.length>0&&n.set(o,i)}catch(l){s.debug(`Error validating ${o}: ${l instanceof Error?l.message:String(l)}`)}}if(e.format==="json"){let o={command:"i18n:validate",success:!r,results:Array.from(n.entries()).reduce((a,[i,l])=>(a[i]=l,a),{})};console.log(JSON.stringify(o,null,2))}else for(let[o,a]of n){s.info(`${te.bold(o)}:`);for(let i of a){let u=(i.coverage>=100?te.green:i.coverage>=80?te.yellow:te.red)(`${i.coverage}%`);s.info(` ${te.cyan(i.locale.padEnd(5))} ${u.padEnd(20)} [${i.totalKeys} keys]`),i.missingKeys.length>0&&s.warn(` Missing: ${i.missingKeys.slice(0,5).join(", ")}${i.missingKeys.length>5?` (+ ${i.missingKeys.length-5} more)`:""}`),i.extraKeys.length>0&&s.warn(` Extra: ${i.extraKeys.slice(0,5).join(", ")}${i.extraKeys.length>5?` (+ ${i.extraKeys.length-5} more)`:""}`)}}r&&process.exit(c.CONFLICT)}async function tc(e,t){/^[a-z]{2}(-[A-Z]{2})?$/.test(e)||(s.error(`Invalid locale format: ${e}. Use 'en', 'es', 'zh-CN', etc.`),process.exit(c.INVALID_ARGS));let n=Zt();n.size===0&&(s.error("No message directories found in the project"),process.exit(c.NOT_FOUND));let r=[],o=!1;for(let[i,l]of n){let u=ye.join(l,`${e}.json`);if(Xt.existsSync(u)){s.warn(`Locale ${e} already exists in ${i}`);continue}try{let E=function(D){for(let F in D)typeof D[F]=="string"?D[F]="":typeof D[F]=="object"&&D[F]!==null&&E(D[F])};var a=E;let m=ye.join(l,"en.json"),f=Ze(m);if(!f){s.warn(`Could not load reference en.json from ${i}, skipping...`);continue}let y=JSON.parse(JSON.stringify(f));E(y),t.dryRun?s.info(`Would create ${e} locale in ${i}`):(Ji(u,JSON.stringify(y,null,2)+`
|
|
709
|
+
`),r.push({app:i,path:u}),s.success(`Created ${e} locale in ${i}`))}catch(m){s.error(`Failed to create locale in ${i}: ${m instanceof Error?m.message:String(m)}`),o=!0}}t.format==="json"?console.log(JSON.stringify({command:"i18n:add",locale:e,dryRun:t.dryRun||!1,created:r,success:!o},null,2)):t.dryRun||s.success(`Locale '${e}' added to ${r.length} app(s)`),o&&process.exit(c.ERROR)}async function nc(e){s.info("Checking translation coverage...");let t=Zt();t.size===0&&(s.warn("No message directories found in the project"),process.exit(c.NOT_FOUND));let n=new Map,r=0,o=0;for(let[a,i]of t){let l=[];try{let u=Qt(i).filter(E=>E.endsWith(".json"));if(u.length===0)continue;let m=ye.join(i,"en.json"),f=Ze(m);if(!f){s.debug(`Could not load reference locale from ${a}`);continue}let y=Qe(f);for(let E of u){let D=E.replace(".json",""),F=ye.join(i,E),q=Ze(F);if(!q)continue;let ue=Qe(q),me=Array.from(ue).filter(B=>{let je=q[B.split(".")[0]];return je!==void 0&&je!==""}).length,Ae=y.size-me,p=y.size>0?me/y.size*100:0;l.push({locale:D,coverage:Math.round(p*100)/100,totalKeys:y.size,translatedKeys:me,missingKeys:Ae})}l.length>0&&(n.set(a,l),o++,r+=l.reduce((E,D)=>E+D.coverage,0)/l.length)}catch(u){s.debug(`Error checking status for ${a}: ${u instanceof Error?u.message:String(u)}`)}}if(e.format==="json"){let a={command:"i18n:status",averageCoverage:o>0?Math.round(r/o*100)/100:0,results:Array.from(n.entries()).reduce((i,[l,u])=>(i[l]=u,i),{})};console.log(JSON.stringify(a,null,2))}else{for(let[a,i]of n){s.info(`${te.bold(a)}:`);for(let l of i){let u="",f=Math.round(l.coverage/100*20);u="\u2588".repeat(f)+"\u2591".repeat(20-f);let E=(l.coverage>=100?te.green:l.coverage>=80?te.yellow:te.red)(`${l.coverage.toFixed(1)}%`);s.info(` ${te.cyan(l.locale.padEnd(5))} [${u}] ${E}`),s.info(` ${l.translatedKeys}/${l.totalKeys} keys (${l.missingKeys} missing)`)}}if(o>0){let a=r/o,i=a>=100?te.green:a>=80?te.yellow:te.red;s.info(`
|
|
710
|
+
Average coverage: ${i(a.toFixed(1)+"%")}`)}}}function xr(e){let t=e.command("i18n").description("Manage internationalization and translations");t.command("sync").description("Synchronize language translations across the project").option("--dry-run","Preview changes without executing").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await Zi({dryRun:n.dryRun||!1,format:n.format||r.format,interactive:r.yes!==!0})}),t.command("validate").description("Validate all locale files for missing or extra keys").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await ec({format:n.format||r.format,interactive:r.yes!==!0})}),t.command("add <locale>").description("Add a new locale with template files (e.g. 'en', 'es', 'zh-CN')").option("--dry-run","Preview what would be created without writing files").option("--format <type>","Output format: json or plain").action(async(n,r)=>{let o=r.optsWithGlobals?.()||r;await tc(n,{dryRun:r.dryRun||!1,format:r.format||o.format,interactive:o.yes!==!0})}),t.command("status").description("Show translation coverage per locale and app").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await nc({format:n.format||r.format,interactive:r.yes!==!0})})}import*as kt from"@clack/prompts";async function rc(e){let t=e.lite?"docker-compose.lite.yml":void 0,n=e.lite?"Starting lite stack (PostgreSQL + Redis)":"Starting full stack";d(n+"...","info");let r=await Le("up -d",{file:t,profile:e.profile,dryRun:e.dryRun});r.exitCode===0?d("Infrastructure stack started successfully","success"):(d("Failed to start infrastructure stack","error"),k("Docker compose output",{stderr:r.stderr}),process.exit(r.exitCode||1))}async function oc(e){d("Stopping infrastructure stack...","info");let t=await Le("down",{dryRun:e.dryRun});t.exitCode===0?d("Infrastructure stack stopped","success"):(d("Failed to stop infrastructure stack","error"),k("Docker compose output",{stderr:t.stderr}),process.exit(t.exitCode||1))}async function sc(e){d("Checking infrastructure status...","info");let t=await Le("ps --format json",{dryRun:e.dryRun});if(t.exitCode===0)try{let n=JSON.parse(t.stdout);if(e.format==="json")R(n,{format:"json"});else{let r=n.map(o=>({name:o.Name,status:o.Status,ports:o.Ports||"-"}));R(r,{format:"table"})}}catch{R(t.stdout,{format:"plain"})}else d("Failed to check infrastructure status","error"),k("Docker compose output",{stderr:t.stderr}),process.exit(t.exitCode||1)}async function ac(e,t){let n=t||{},r=e?`Fetching logs for ${e}...`:"Fetching infrastructure logs...";d(r,"info");let o=["logs","--tail","50"];e&&o.push(e);let a=await Le(o.join(" "),{dryRun:n.dryRun});a.exitCode===0?R(a.stdout,{format:"plain"}):(d("Failed to fetch logs","error"),k("Docker compose output",{stderr:a.stderr}),process.exit(a.exitCode||1))}async function ic(e){let t=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(!e.yes&&!e.dryRun)if(t){let r=await kt.confirm({message:"Reset infrastructure? This will remove all containers and volumes.",initialValue:!1});(kt.isCancel(r)||!r)&&(d("Reset cancelled","warn"),process.exit(c.CANCELLED))}else d("Infrastructure reset requires explicit --yes confirmation (use: nebutra infra reset --yes)","error"),process.exit(c.INVALID_ARGS);d("Resetting infrastructure stack...","warn");let n=await Le("down -v",{dryRun:e.dryRun});n.exitCode===0?d("Infrastructure reset successfully","success"):(d("Failed to reset infrastructure","error"),k("Docker compose output",{stderr:n.stderr}),process.exit(n.exitCode||1))}function Or(e){e.command("infra <verb> [service]").description("Manage Docker Compose infrastructure (PostgreSQL, Redis, Meilisearch, etc.)").option("--dry-run","Show what would be run without executing").option("--yes","Skip confirmations (especially for reset)").option("--lite","Use lite stack (PostgreSQL + Redis only)").option("--profile <name>","Docker Compose profile to use (e.g., search)").option("--format <type>","Output format: json, plain","plain").action(async(n,r,o)=>{let a=o.optsWithGlobals?.(),i={dryRun:o.dryRun||a?.dryRun,yes:o.yes||a?.yes,format:o.format||a?.format,lite:o.lite||!1,profile:o.profile};try{switch(n){case"up":await rc(i);break;case"down":await oc(i);break;case"status":await sc(i);break;case"logs":await ac(r,i);break;case"reset":await ic(i);break;default:d(`Unknown infra subcommand: ${n}. Valid commands: up, down, status, logs, reset`,"error"),process.exit(c.INVALID_ARGS)}}catch(l){let u=l instanceof Error?l.message:String(l);d(`Infrastructure command failed: ${u}`,"error"),k("Full error",{error:l}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
708
711
|
Examples:
|
|
709
712
|
nebutra infra up Start full stack
|
|
710
713
|
nebutra infra up --lite Start lite stack (PostgreSQL + Redis)
|
|
@@ -721,14 +724,14 @@ Flags:
|
|
|
721
724
|
--lite Use docker-compose.lite.yml (PostgreSQL + Redis only)
|
|
722
725
|
--profile <name> Enable Docker Compose profile (search, notifications, etc.)
|
|
723
726
|
--format <type> Output format: json, plain (default: plain, auto-json in non-TTY)
|
|
724
|
-
`)}import
|
|
725
|
-
`),o?(s.success("Configuration saved to nebutra.config.json"),s.info('Initialization complete! You can now use "nebutra add" to start injecting components.')):(await new Promise(i=>setTimeout(i,800)),re.spinner().stop(
|
|
726
|
-
`)}async function
|
|
727
|
-
`));let r=
|
|
727
|
+
`)}import en from"fs";import cc from"path";import*as re from"@clack/prompts";import xt from"picocolors";var lc={$schema:"https://nebutra.com/schema.json",componentsDirectory:"packages/design/ui/src/components",tailwind:{config:"tailwind.config.ts",css:"packages/design/tokens/styles.css",baseColor:"slate",cssVariables:!0},aliases:{components:"@nebutra/ui",utils:"@nebutra/ui/utils"}};function dc(){return process.stdout.isTTY===!0}function uc(e){return e.yes===!0||e.dryRun===!0||!dc()}function mc(e,t,n){return{operation:n?"update":"create",path:e,...n&&{before:n},after:t}}async function Ar(e={}){let t=process.cwd(),n=cc.join(t,"nebutra.config.json"),r=en.existsSync(n);e.ifNotExists&&r&&(s.info("nebutra.config.json already exists, skipping initialization."),process.exit(c.SUCCESS));let o=uc(e);o||re.intro(xt.bgCyan(xt.black(" nebutra init "))),r&&!o&&(re.log.warn("nebutra.config.json already exists in this directory."),await re.confirm({message:"Do you want to overwrite it?",initialValue:!1})||(re.outro("Operation aborted."),process.exit(c.CANCELLED)));let a={...lc};if(e.dryRun){let i=r?JSON.parse(en.readFileSync(n,"utf-8")):void 0,l=mc(n,a,i);A(l),d("Dry-run completed. No changes made."),process.exit(c.DRY_RUN_OK)}o?s.info("Initializing Nebutra CLI configuration..."):re.spinner().start("Initializing Nebutra CLI configuration..."),en.writeFileSync(n,JSON.stringify(a,null,2)+`
|
|
728
|
+
`),o?(s.success("Configuration saved to nebutra.config.json"),s.info('Initialization complete! You can now use "nebutra add" to start injecting components.')):(await new Promise(i=>setTimeout(i,800)),re.spinner().stop(xt.green("Configuration saved to nebutra.config.json")),re.outro(xt.cyan('Initialization complete! You can now use "nebutra add" to start injecting components.'))),process.exit(c.SUCCESS)}import tn from"fs/promises";import yc from"os";import nn from"path";import*as I from"@clack/prompts";import oe from"picocolors";var pc="https://analytics.nebutra.com";function fc(e={}){if(e.noTelemetry===!0)return!0;let t=process.env.NEBUTRA_TELEMETRY;return t==="0"||t==="false"}function gc(){return process.env.npm_package_version??"0.0.0-dev"}function Ot(e,t={}){fc(t)||(async()=>{try{let n=await import("./dist-WSEDRKMF.js");if(typeof n.createProductAnalyticsClient!="function")return;let r=n.createProductAnalyticsClient({posthog:{apiKey:process.env.POSTHOG_KEY??process.env.NEXT_PUBLIC_POSTHOG_KEY??process.env.NEBUTRA_POSTHOG_KEY??"",host:process.env.POSTHOG_HOST??process.env.NEXT_PUBLIC_POSTHOG_HOST??process.env.NEBUTRA_POSTHOG_HOST??pc},onError:()=>{}});if(typeof r?.track!="function")return;let o=r.track("license.cli",{action:e.action,cli_version:gc(),...e.tier?{license_tier:e.tier}:{},...e.type?{license_type:e.type}:{},...e.error_code?{error_code:e.error_code}:{}});o&&typeof o.then=="function"&&await o.catch(()=>{})}catch{}})()}var _r=process.env.NEBUTRA_LICENSE_API_URL??"https://nebutra.com";async function Pr(){let e=yc.homedir(),t=nn.join(e,".config","nebutra");try{await tn.mkdir(t,{recursive:!0})}catch{}return t}async function hc(e){let t=`${_r}/api/license/validate?key=${encodeURIComponent(e)}`,n;try{n=await fetch(t,{signal:AbortSignal.timeout(1e4)})}catch{throw new Error(`Could not reach the Nebutra license server (${_r}). Check your internet connection or set NEBUTRA_LICENSE_API_URL.`)}if(n.status===404)throw new Error("License key not found. Please check the key and try again.");if(n.status===410)throw new Error("License key has expired. Please renew your license at nebutra.com.");if(!n.ok)throw new Error(`License validation failed (HTTP ${n.status}). Please try again later.`);let r=await n.json();if(!r.valid)throw new Error("License key is not valid. Please check the key and try again.");return{tier:r.tier??"UNKNOWN",type:r.type??"UNKNOWN"}}function bc(e){let t=e instanceof Error?e.message:String(e);return/Invalid license key format/i.test(t)?"invalid_format":/license server/i.test(t)?"network_error":/not found/i.test(t)?"not_found":/expired/i.test(t)?"expired":/not valid/i.test(t)?"invalid_key":/HTTP \d+/i.test(t)?"http_error":"unknown"}async function vc(e,t){let n=t.quiet===!0;n||I.intro(oe.bgCyan(oe.black(" Nebutra License Activation "))),Ot({action:"activate_attempted"});try{if(e.length<10)throw new Error("Invalid license key format.");n||I.log.step("Validating license key with Nebutra...");let{tier:r,type:o}=await hc(e),a=await Pr(),i=nn.join(a,"license.json");await tn.writeFile(i,JSON.stringify({licenseKey:e,tier:r,type:o,activatedAt:new Date().toISOString()},null,2),"utf-8"),n||(I.log.success(oe.green(`${r} license activated and saved to ${i}`)),I.outro(oe.cyan("Premium CLI capabilities are now unlocked!"))),Ot({action:"activated",tier:r,type:o})}catch(r){Ot({action:"failed",error_code:bc(r)}),n||(I.log.error(oe.red("Activation failed")),s.error(r instanceof Error?r.message:String(r)),I.outro("Please check your key and try again.")),process.exit(c.ERROR)}}async function wc(e){let t=e.quiet===!0;t||I.intro(oe.bgCyan(oe.black(" Nebutra License Status ")));try{let n=await Pr(),r=nn.join(n,"license.json"),o=await tn.readFile(r,"utf-8"),a=JSON.parse(o);if(a.licenseKey)t||(I.log.success(oe.green("License is active!")),I.log.info(`Key: ${a.licenseKey.substring(0,8)}...`),a.tier&&I.log.info(`Tier: ${oe.bold(a.tier)}`),a.type&&I.log.info(`Type: ${a.type}`),I.log.info(`Activated: ${new Date(a.activatedAt).toLocaleString()}`),I.outro(oe.cyan("You are ready to use premium features.")));else throw new Error("License key not found in config.")}catch{t||(I.log.warn(oe.yellow("No active license found locally.")),I.log.message(oe.dim("Run `nebutra license activate <key>` to unlock premium features.")),I.outro("")),process.exit(c.NOT_FOUND)}}function Ir(e){let t=e.command("license").description("Manage your Nebutra-Sailor commercial license");t.command("activate <key>").description("Activate a commercial license key for local development").option("--quiet","Suppress output").action(async(n,r)=>{await vc(n,r)}),t.command("status").description("Check the locally configured license status").option("--quiet","Suppress output").action(async n=>{await wc(n)})}import{existsSync as Nr,readFileSync as Sc,writeFileSync as Rc}from"fs";import{dirname as Cc,join as $r,parse as Ec}from"path";import*as At from"@clack/prompts";function kc(e){let t=e,{root:n}=Ec(t);for(;;){if(Nr($r(t,"package.json")))return t;if(t===n)return null;let r=Cc(t);if(r===t)return null;t=r}}function xc(e){if(!Nr(e))return{};try{let t=JSON.parse(Sc(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function Oc(e,t){Rc(e,JSON.stringify(t,null,2)+`
|
|
729
|
+
`)}async function Ac(e,t){let n=t.format==="json",r=kc(process.cwd());r||(n?console.log(JSON.stringify({command:"link",success:!1,error:"No package.json found upstream"},null,2)):s.error("No package.json found in current or parent directories."),process.exit(c.NOT_FOUND));let o=e;if(!o){t.yes&&(n?console.log(JSON.stringify({command:"link",success:!1,error:"project-id required in --yes mode"},null,2)):s.error("project-id is required when running with --yes / non-interactive."),process.exit(c.INVALID_ARGS));let u=await At.text({message:"Project ID to link to:",placeholder:"proj_abc123",validate:m=>m&&m.trim().length>0?void 0:"Project ID cannot be empty"});At.isCancel(u)&&(s.warn("Cancelled"),process.exit(c.CANCELLED)),o=String(u).trim()}let a=$r(r,"nebutra.config.json"),l={...xc(a),projectId:o};Oc(a,l),n?console.log(JSON.stringify({command:"link",success:!0,projectId:o,configPath:a},null,2)):s.success(`Linked to project: ${o}`)}function Tr(e){e.command("link [project-id]").description("Link the current project to a Nebutra project id").option("--format <type>","Output format: json or plain").action(async(t,n,r)=>{let o=r?.optsWithGlobals?.()||n;await Ac(t,{yes:o.yes||!1,format:n.format||o.format})})}import{existsSync as Ur,rmSync as _c,unlinkSync as Pc}from"fs";import{homedir as jr,platform as Ic}from"os";import{join as et}from"path";function Nc(){if(Ic()==="win32"){let t=process.env.LOCALAPPDATA||et(jr(),"AppData","Local");return et(t,"nebutra")}let e=process.env.XDG_CONFIG_HOME;return e?et(e,"nebutra"):et(jr(),".config","nebutra")}var $c=["auth.json","session.json","token","credentials.json"];async function Tc(e){let t=Nc(),n=e.format==="json",r=0,o=[];if(e.all){if(Ur(t))try{_c(t,{recursive:!0,force:!0}),r=1,o.push(t)}catch(a){let i=a instanceof Error?a.message:String(a);n?console.log(JSON.stringify({command:"logout",success:!1,error:i},null,2)):s.error(`Failed to clear config directory: ${i}`),process.exit(c.PERMISSION_DENIED)}}else for(let a of $c){let i=et(t,a);if(Ur(i))try{Pc(i),r++,o.push(i)}catch{}}r===0&&(n?console.log(JSON.stringify({command:"logout",success:!0,alreadyLoggedOut:!0,removed:[]},null,2)):s.info("Already logged out"),process.exit(c.SUCCESS)),n?console.log(JSON.stringify({command:"logout",success:!0,removed:o,clearedAll:!!e.all},null,2)):s.success(e.all?"Cleared all nebutra config":"Logged out of nebutra.com")}function Lr(e){e.command("logout").description("Clear stored authentication credentials").option("--all","Clear ALL local config, not just auth tokens").option("--format <type>","Output format: json or plain").action(async(t,n)=>{let r=n?.optsWithGlobals?.()||t;await Tc({all:t.all||!1,format:t.format||r.format})})}import{spawn as Uc}from"child_process";import{dirname as jc,resolve as Lc}from"path";import{fileURLToPath as Dc}from"url";import*as de from"@clack/prompts";import ve from"picocolors";var Fc=jc(Dc(import.meta.url));function Bc(){let e=[()=>Lc(Fc,"../../../mcp/dist/server/contextServer.js")];for(let t of e)try{return t()}catch(n){s.debug("MCP server binary resolution strategy failed",{error:n})}return"nebutra-mcp"}function Dr(e){e.command("mcp").description("Start the Nebutra MCP server for Cursor/Windsurf").option("--stdio","Use stdio transport (default)",!0).action(async t=>{de.intro(ve.bgCyan(ve.black(" nebutra mcp ")));try{let n=Bc();de.log.info(ve.cyan("Starting Nebutra MCP server for Cursor/Windsurf integration...")),de.log.info(ve.dim(`Press Ctrl+C to stop the server.
|
|
730
|
+
`));let r=Uc(process.execPath,[n],{stdio:"inherit",env:{...process.env}});r.on("close",o=>{o===0?de.outro(ve.green("MCP server stopped gracefully.")):o===null&&de.outro(ve.yellow("MCP server terminated.")),process.exit(o??0)}),r.on("error",o=>{s.error(`
|
|
728
731
|
Failed to start MCP server: ${o.message}`),o.code==="ENOENT"&&(s.warn(`
|
|
729
732
|
Tip: Ensure @nebutra/mcp is installed or available in your PATH.`),s.info(" Install globally: npm install -g @nebutra/mcp"),process.exit(c.NOT_FOUND)),process.exit(c.ERROR)}),process.on("SIGINT",()=>{de.log.info(ve.yellow(`
|
|
730
|
-
Shutting down MCP server...`)),r.kill("SIGINT")}),process.on("SIGTERM",()=>{de.log.info(ve.yellow("Terminating MCP server...")),r.kill("SIGTERM")})}catch(n){de.log.error(ve.red("Error: Unable to start MCP server. Ensure @nebutra/mcp is properly installed.")),n instanceof Error&&s.error(n.message),process.exit(c.ERROR)}})}import*as M from"@clack/prompts";import se from"picocolors";var
|
|
731
|
-
`)}function
|
|
733
|
+
Shutting down MCP server...`)),r.kill("SIGINT")}),process.on("SIGTERM",()=>{de.log.info(ve.yellow("Terminating MCP server...")),r.kill("SIGTERM")})}catch(n){de.log.error(ve.red("Error: Unable to start MCP server. Ensure @nebutra/mcp is properly installed.")),n instanceof Error&&s.error(n.message),process.exit(c.ERROR)}})}import*as M from"@clack/prompts";import se from"picocolors";var Br=Object.fromEntries(Object.entries(En).map(([e,t])=>[e,t]));function Mr(e){return typeof e=="boolean"?"boolean":"string"}function Mc(){let e=_n().map(n=>({name:n.name,description:n.description,envFile:n.envFile??".env.local",providers:(n.providers??[]).map(r=>({id:r.id,description:r.description,dependencies:r.dependencies??[],devDependencies:r.devDependencies??[],env:r.env??[]})),files:(n.files??[]).map(r=>r.path)})),t=Array.from(new Set(e.flatMap(n=>n.providers.map(r=>r.id))));return{localFeatures:e,valueDomains:{components:e.map(n=>n.name),provider:t}}}function Gc(e){let t=e.arguments.map(a=>a.name==="components"?{...a,description:"Local feature names to install from the Nebutra registry"}:a),r=e.options.some(a=>a.flags.includes("--provider"))?e.options:[...e.options,{flags:"--provider <id>",description:"Specify a provider for a local feature install",required:!1,type:"string"}],o=[{command:"nebutra add queue --provider upstash",description:"Install the local queue feature starter with the Upstash provider"},{command:"nebutra add search --provider meilisearch --dry-run",description:"Preview the local search feature install plan as JSON"},...e.examples.filter(a=>a.command.includes("--21st")||a.command.includes("--v0"))];return{...e,arguments:t,options:r,examples:o,extensions:Mc()}}function Vc(e){return{...e,extensions:{valueDomains:b,aliases:{storage:{supabase:"supabase-storage"},payment:{lemonsqueezy:"lemon"}}}}}function Gr(e){let t={name:e.name,description:e.description,usage:e.usage,arguments:e.arguments||[],options:(e.options||[]).map(n=>({flags:n.flags,description:n.description,default:n.default,required:!1,type:Mr(n.default)})),examples:e.examples||[]};return e.name==="add"?Gc(t):e.name==="create"?Vc(t):t}function Kc(e){let n=(fe.subcommands||[]).find(r=>r.name===e);return n?Gr(n):null}function qc(){return(fe.options??[]).map(e=>({flags:e.flags,description:e.description,required:!1,type:Mr(e.default)}))}function zc(e){let t=fe.subcommands||[];return{name:fe.name,version:e,description:fe.description,usage:fe.usage||"nebutra [command] [options]",globalOptions:qc(),commands:t.map(Gr),exitCodes:Br,timestamp:new Date().toISOString()}}function Fr(){return(fe.subcommands||[]).map(t=>t.name)}function _t(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
734
|
+
`)}function Yc(e){return e instanceof Error&&e.message.startsWith("EXIT:")}async function Hc(e,t){let n=t.quiet===!0,r="0.1.0";try{if(t.all===!0&&(_t(zc(r)),process.exit(0)),t.list===!0&&(_t(Fr()),process.exit(0)),(t.exitCodes===!0||t["exit-codes"]===!0)&&(_t(Br),process.exit(0)),e){let o=Kc(e);o||(n||(s.error(`Unknown command '${e}'`),s.info(`Available commands: ${Fr().join(", ")}`)),process.exit(c.NOT_FOUND)),_t(o),process.exit(0)}n||(M.intro(se.bgCyan(se.black(" nebutra schema "))),M.log.info(se.cyan("Agent-friendly introspection of CLI commands, arguments, and value domains.")),M.log.message(""),M.log.info(se.bold("Usage:")),M.log.message(se.dim(" nebutra schema --all Show full command tree as JSON")),M.log.message(se.dim(" nebutra schema <command> Show schema for a specific command")),M.log.message(se.dim(" nebutra schema --list List available command names")),M.log.message(se.dim(" nebutra schema --exit-codes Show exit codes reference")),M.log.message(""),M.log.info(se.bold("Example:")),M.log.message(se.dim(" nebutra schema add")),M.log.message(se.dim(" nebutra schema --all | jq '.commands[0]'")),M.outro(se.cyan("All output is JSON for easy parsing by agents and automation tools."))),process.exit(0)}catch(o){if(Yc(o))throw o;n||s.error(o instanceof Error?o.message:String(o)),process.exit(c.ERROR)}}function Vr(e){e.command("schema [command]").description("Show command schema and argument documentation (Agent-friendly JSON output)").option("--all","Show full schema for all commands").option("--list","List all available command names").option("--exit-codes","Show exit codes reference").action(async(t,n)=>{await Hc(t,n)})}import*as Pt from"@clack/prompts";import ae from"picocolors";function tt(){let e=process.env.MEILISEARCH_URL,t=process.env.TYPESENSE_URL,n=process.env.ALGOLIA_APP_ID;return e?{type:"meilisearch",url:e,health:!0,message:"Meilisearch configured"}:t?{type:"typesense",url:t,health:!0,message:"Typesense configured"}:n?{type:"algolia",health:!0,message:"Algolia configured"}:{type:"none",health:!1,message:"No search provider configured"}}async function Wc(e){d("Detecting search provider...","info");let t=tt();t.type==="none"&&(d("No search provider is configured","warn"),d("Set one of: MEILISEARCH_URL, TYPESENSE_URL, or ALGOLIA_APP_ID","info"),process.exit(0));let n={provider:t.type,configured:!0,url:t.url||"managed",health:t.health,message:t.message};e.format==="json"?R(n,{format:"json"}):(d(`Search Provider: ${ae.cyan(t.type.toUpperCase())}`,"success"),d(`Status: ${t.health?ae.green("Healthy"):ae.red("Unhealthy")}`,t.health?"success":"error"),t.url&&d(`URL: ${t.url}`,"info"))}async function Jc(e){d("Fetching search indexes...","info"),tt().type==="none"&&(d("No search provider configured","error"),process.exit(c.CONFIG_ERROR));let n=[{name:"products",documentCount:15420,size:"2.4 MB",lastUpdated:"2 hours ago"},{name:"articles",documentCount:3240,size:"1.1 MB",lastUpdated:"1 day ago"},{name:"users",documentCount:8900,size:"0.8 MB",lastUpdated:"30 minutes ago"}];if(e.format==="json")R(n,{format:"json"});else{d("Search Indexes","info");for(let r of n)d(`${ae.cyan(r.name)}: ${r.documentCount} documents (${r.size})`,"info")}}async function Kr(e,t){let n=t||{},r=tt();r.type==="none"&&(d("No search provider configured","error"),process.exit(c.CONFIG_ERROR));let o=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(!e&&!n.force&&!n.dryRun&&o){let i=await Pt.confirm({message:"Reindex ALL indexes? This will recreate all indexes from scratch.",initialValue:!1});(Pt.isCancel(i)||!i)&&(d("Reindex cancelled","warn"),process.exit(c.CANCELLED))}!n.yes&&!n.dryRun&&!e&&(d("Full reindex requires --yes confirmation","error"),process.exit(c.INVALID_ARGS));let a=e||"all";if(d(`Reindexing ${ae.cyan(a)}...`,"info"),n.dryRun){d(`Would reindex ${a} with provider ${r.type}`,"info");return}d(`Reindexing ${a} on ${r.type}...`,"info"),d(`Index ${ae.cyan(a)} reindexed successfully`,"success")}async function Xc(e,t,n){d(`Querying ${ae.cyan(e)} for "${ae.yellow(t)}"...`,"info");let r=tt();r.type==="none"&&(d("No search provider configured","error"),process.exit(c.CONFIG_ERROR));let o=[{id:"1",title:"Sample Result 1",score:.95,_formatted:{title:"Sample <mark>Result</mark> 1",content:"Contains search term..."}},{id:"2",title:"Another Result",score:.87,_formatted:{title:"Another <mark>Result</mark>",content:"Also matches search..."}}],a={index:e,query:t,provider:r.type,hits:o.length,limit:n.limit||10,results:o};if(n.format==="json")R(a,{format:"json"});else{d(`Found ${ae.cyan(String(o.length))} results for "${t}"`,"success");for(let i of o)d(`${ae.dim(String(i.score))}: ${i.title}`,"info")}}async function Qc(e){d("Fetching search statistics...","info");let t=tt();t.type==="none"&&(d("No search provider configured","error"),process.exit(c.CONFIG_ERROR));let n={provider:t.type,indexes:[{name:"products",documents:15420,size:24e5,lastUpdated:"2024-03-30T14:22:00Z"},{name:"articles",documents:3240,size:11e5,lastUpdated:"2024-03-29T08:15:00Z"},{name:"users",documents:8900,size:8e5,lastUpdated:"2024-03-30T14:52:00Z"}],totalDocuments:27560,totalSize:43e5};if(e.format==="json")R(n,{format:"json"});else{d("Search Statistics","info"),d(`Provider: ${ae.cyan(n.provider)}`,"info"),d(`Total Indexes: ${n.indexes.length}`,"info"),d(`Total Documents: ${n.totalDocuments.toLocaleString()}`,"info"),d(`Total Size: ${(n.totalSize/1024/1024).toFixed(2)} MB`,"info"),d("Index Breakdown:","info");for(let r of n.indexes)d(` ${ae.cyan(r.name)}: ${r.documents.toLocaleString()} docs (${(r.size/1024/1024).toFixed(2)} MB)`,"info")}}function qr(e){e.command("search <verb> [args...]").description("Manage search engine (Meilisearch, Typesense, or Algolia)").option("--dry-run","Show what would be run without executing").option("--yes","Skip confirmations").option("--format <type>","Output format: json, plain, table","plain").option("--force","Force operation (e.g., recreate index)").option("--limit <n>","Result limit for queries").option("--filters <json>","Filters for search query (JSON)").option("--tenant <id>","Tenant ID for multi-tenant queries").action(async(n,r,o)=>{let a=o.optsWithGlobals?.(),i={dryRun:o.dryRun||a?.dryRun,yes:o.yes||a?.yes,format:o.format||a?.format,force:o.force||!1,limit:o.limit??10,filters:o.filters,tenant:o.tenant};try{switch(n){case"status":await Wc(i);break;case"indexes":await Jc(i);break;case"reindex":r.length>0?await Kr(r[0],i):await Kr(void 0,i);break;case"query":r.length<2&&(d("query requires an index and search term: nebutra search query <index> <query>","error"),process.exit(c.INVALID_ARGS)),await Xc(r[0],r.slice(1).join(" "),i);break;case"stats":await Qc(i);break;default:d(`Unknown search subcommand: ${n}. Valid commands: status, indexes, reindex, query, stats`,"error"),process.exit(c.ERROR)}}catch(l){let u=l instanceof Error?l.message:String(l);d(`Search command failed: ${u}`,"error"),k("Full error",{error:l}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
732
735
|
Examples:
|
|
733
736
|
nebutra search status Show search provider status
|
|
734
737
|
nebutra search indexes List all indexes
|
|
@@ -751,7 +754,7 @@ Flags:
|
|
|
751
754
|
--limit <n> Result limit for queries (default: 10)
|
|
752
755
|
--filters <json> Filters for search query
|
|
753
756
|
--tenant <id> Tenant ID for multi-tenant searches
|
|
754
|
-
`)}import{stdin as
|
|
757
|
+
`)}import{stdin as nt}from"process";import*as It from"@clack/prompts";import N from"picocolors";async function Zc(){return new Promise((e,t)=>{let n="";nt.setEncoding("utf8"),nt.on("readable",()=>{let r;for(;(r=nt.read())!==null;)n+=r}),nt.on("end",()=>{e(n.trim())}),nt.on("error",t)})}async function el(e){d("Fetching secret metadata...","info");let t=[{key:"openai_key",tenant:e.tenant||"org_123",createdAt:"2024-03-15T10:30:00Z",updatedAt:"2024-03-30T14:22:00Z",description:"OpenAI API key for embeddings",masked:!0},{key:"stripe_sk",tenant:e.tenant||"org_123",createdAt:"2024-03-10T08:15:00Z",updatedAt:"2024-03-25T09:45:00Z",description:"Stripe secret key",masked:!0},{key:"github_token",tenant:e.tenant||"org_123",createdAt:"2024-03-20T16:30:00Z",updatedAt:"2024-03-29T11:20:00Z",description:"GitHub API token",masked:!0}];if(e.format==="json")R(t,{format:"json"});else{d("Secrets for tenant: "+(e.tenant||"org_123"),"info");for(let n of t){let r=n.description?` \u2014 ${n.description}`:"";d(`${N.cyan(n.key)}${N.gray(r)}`,"info"),d(` Updated: ${n.updatedAt}`,"info")}}}async function tl(e,t){e||(d("Secret key is required: nebutra secrets set <key>","error"),process.exit(c.INVALID_ARGS));let n;if(t.value)d("WARNING: Using --value flag exposes secret in shell history. Prefer stdin.","warn"),n=t.value;else{d("Enter secret value (will not echo). Press Ctrl+D when done:","info");try{n=await Zc()}catch{d("Failed to read secret from stdin","error"),process.exit(c.ERROR)}}if(n||(d("Secret value cannot be empty","error"),process.exit(c.INVALID_ARGS)),d(`Setting secret ${N.cyan(e)}...`,"info"),t.dryRun){d(`Would encrypt and store secret ${e} for tenant ${t.tenant||"org_123"}`,"info");return}d(`Secret ${N.cyan(e)} encrypted and stored successfully`,"success"),t.description&&d(`Description: ${t.description}`,"info")}async function nl(e,t){e||(d("Secret key is required: nebutra secrets get <key>","error"),process.exit(c.INVALID_ARGS)),d(`Retrieving secret ${N.cyan(e)}...`,"info");let r=t.unmask?"sk_live_abc123xyz789...":"***masked***";t.unmask||d(`Secret value is ${N.yellow("masked")}. Use --unmask to display.`,"warn");let o={key:e,tenant:t.tenant||"org_123",value:r,encrypted:!0};t.format==="json"?R(o,{format:"json"}):d(`${N.cyan(e)}: ${r}`,"info")}async function rl(e,t){e||(d("Secret key is required: nebutra secrets rotate <key>","error"),process.exit(c.INVALID_ARGS));let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(!t.yes&&!t.dryRun&&n){let r=await It.confirm({message:`Rotate encryption key for ${N.cyan(e)}? This will re-encrypt with new key material.`,initialValue:!1});(It.isCancel(r)||!r)&&(d("Rotation cancelled","warn"),process.exit(c.CANCELLED))}if(!t.yes&&!t.dryRun&&!n&&(d("Key rotation requires --yes confirmation","error"),process.exit(c.INVALID_ARGS)),d(`Rotating encryption key for ${N.cyan(e)}...`,"info"),t.dryRun){d(`Would rotate encryption key for ${e}`,"info");return}d(`Encryption key for ${N.cyan(e)} rotated successfully`,"success"),d(`New key version: ${N.dim("v2")}`,"info")}async function ol(e){d("Fetching audit log...","info");let n=[{timestamp:"2024-03-30T14:52:00Z",action:"read",key:"openai_key",actor:"api_service",success:!0},{timestamp:"2024-03-30T14:22:00Z",action:"write",key:"openai_key",actor:"claude_user",success:!0},{timestamp:"2024-03-30T13:45:00Z",action:"read",key:"stripe_sk",actor:"billing_worker",success:!0},{timestamp:"2024-03-30T11:30:00Z",action:"rotate",key:"github_token",actor:"admin_user",success:!0},{timestamp:"2024-03-30T10:15:00Z",action:"read",key:"unknown_key",actor:"unauthorized_service",success:!1,message:"Key not found"}];if(e.limit&&(n=n.slice(0,e.limit)),e.format==="json")R(n,{format:"json"});else{d("Secret Access Audit Log","info");for(let r of n){let o=r.success?N.green("\u2713"):N.red("\u2716");d(`${o} ${r.timestamp} ${N.cyan(r.action)} ${r.key}`,r.success?"success":"error"),d(` Actor: ${r.actor}${r.message?` \u2014 ${r.message}`:""}`,"info")}}}async function sl(e){d("Verifying vault configuration...","info");let t=[];if(t.push({name:"KMS Connectivity",healthy:!0,message:"Connected to AWS KMS"}),t.push({name:"Master Key",healthy:!0,message:"Master encryption key available"}),t.push({name:"Envelope Encryption",healthy:!0,message:"HKDF envelope encryption configured"}),t.push({name:"Storage Backend",healthy:!0,message:"PostgreSQL backend healthy"}),e.format==="json")R(t,{format:"json"});else{d("Vault Configuration Check","info");for(let r of t){let o=r.healthy?N.green("\u2713"):N.red("\u2716");d(`${o} ${r.name}: ${r.message}`,r.healthy?"success":"error")}let n=t.every(r=>r.healthy);d(`Overall: ${n?N.green("HEALTHY"):N.red("UNHEALTHY")}`,n?"success":"error")}}function zr(e){e.command("secrets <verb> [args...]").description("Manage encrypted secrets via @nebutra/vault (AWS KMS + HKDF envelope encryption)").option("--dry-run","Show what would be run without executing").option("--yes","Skip confirmations").option("--format <type>","Output format: json, plain, table","plain").option("--tenant <id>","Tenant ID for multi-tenant access").option("--unmask","Unmask secret values (required to view)").option("--description <text>","Description for secret").option("--value <text>","Secret value (prefer stdin for security)").option("--since <date>","Audit log start date (ISO 8601)").option("--limit <n>","Maximum audit log entries (default: 50)").action(async(n,r,o)=>{let a=o.optsWithGlobals?.(),i={dryRun:o.dryRun||a?.dryRun,yes:o.yes||a?.yes,format:o.format||a?.format,tenant:o.tenant||a?.tenant,unmask:o.unmask||!1,description:o.description,value:o.value,since:o.since,limit:o.limit??50};try{switch(n){case"list":await el(i);break;case"set":r.length===0&&(d("set requires a secret key: nebutra secrets set <key>","error"),process.exit(c.INVALID_ARGS)),await tl(r[0],i);break;case"get":r.length===0&&(d("get requires a secret key: nebutra secrets get <key>","error"),process.exit(c.INVALID_ARGS)),await nl(r[0],i);break;case"rotate":r.length===0&&(d("rotate requires a secret key: nebutra secrets rotate <key>","error"),process.exit(c.INVALID_ARGS)),await rl(r[0],i);break;case"audit":await ol(i);break;case"verify":await sl(i);break;default:d(`Unknown secrets subcommand: ${n}. Valid commands: list, set, get, rotate, audit, verify`,"error"),process.exit(c.ERROR)}}catch(l){let u=l instanceof Error?l.message:String(l);d(`Secrets command failed: ${u}`,"error"),k("Full error",{error:l}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
755
758
|
Examples:
|
|
756
759
|
nebutra secrets list List all secrets (metadata only)
|
|
757
760
|
nebutra secrets list --tenant org_456 List secrets for specific tenant
|
|
@@ -786,7 +789,7 @@ Security Notes:
|
|
|
786
789
|
- Never use --value in production (visible in shell history)
|
|
787
790
|
- Always use --unmask when viewing secrets in scripts
|
|
788
791
|
- Audit log tracks all access and modifications
|
|
789
|
-
`)}import*as
|
|
792
|
+
`)}import*as Nt from"@clack/prompts";import G from"picocolors";function Yr(e){switch(e.toLowerCase()){case"running":return"running";case"exited":return"exited";case"restarting":return"restarting";case"paused":return"paused";default:return"exited"}}function al(e){switch(e){case"running":return G.green("\u25CF");case"exited":return G.red("\u25CF");case"restarting":return G.yellow("\u25CF");case"paused":return G.gray("\u25CF");default:return G.gray("\u25CF")}}async function il(e){d("Checking service status...","info");let t=await O({command:"docker",args:["compose","ps","--format","json"],cwd:h(),interactive:!1,label:"Docker Compose PS",dryRun:e.dryRun});t.exitCode!==0&&(d("Failed to fetch service status","error"),k("Docker error",{stderr:t.stderr}),process.exit(c.ERROR));try{let n=JSON.parse(t.stdout);if(e.format==="json"){let r=n.map(o=>({name:o.Name,status:Yr(o.State),exitCode:o.ExitCode}));R(r,{format:"json"})}else{d("Service Status","info");let r=n.map(o=>({Service:al(Yr(o.State))+" "+o.Name,Status:o.State,"Exit Code":o.ExitCode||"\u2014"}));for(let o of r)d(`${o.Service} (${o.Status})`,"info")}}catch(n){d("Failed to parse service status","error"),k("Parse error",{error:String(n)}),process.exit(c.ERROR)}}async function cl(e,t){d(`Streaming logs for ${G.cyan(e)}...`,"info");let n=["compose","logs"];t.tail?n.push("--tail",String(t.tail)):n.push("--tail","100"),t.since&&n.push("--since",t.since),n.push("-f",e),(await O({command:"docker",args:n,cwd:h(),interactive:!0,label:`Docker Compose Logs (${e})`,dryRun:t.dryRun})).exitCode!==0&&(d(`Failed to stream logs for ${e}`,"error"),process.exit(c.ERROR))}async function ll(e,t){let n=process.stdin.isTTY===!0&&process.stdout.isTTY===!0;if(!t.yes&&!t.dryRun&&n){let a=await Nt.confirm({message:`Restart service ${G.cyan(e)}?`,initialValue:!1});(Nt.isCancel(a)||!a)&&(d("Restart cancelled","warn"),process.exit(c.CANCELLED))}d(`Restarting service ${G.cyan(e)}...`,"info");let r=["compose","restart"];t.timeout&&r.push("--timeout",String(t.timeout)),r.push(e);let o=await O({command:"docker",args:r,cwd:h(),interactive:!1,label:`Docker Compose Restart (${e})`,dryRun:t.dryRun});o.exitCode===0?d(`Service ${G.cyan(e)} restarted successfully`,"success"):(d(`Failed to restart service ${e}`,"error"),k("Docker error",{stderr:o.stderr}),process.exit(c.ERROR))}async function dl(e){d("Running deep health check...","info");let t=[],n=await O({command:"docker",args:["compose","exec","-T","postgres","pg_isready"],cwd:h(),interactive:!1,label:"PostgreSQL Health",dryRun:e.dryRun});t.push({service:"PostgreSQL",healthy:n.exitCode===0,message:n.exitCode===0?"Ready":"Not responding"});let r=await O({command:"docker",args:["compose","exec","-T","redis","redis-cli","ping"],cwd:h(),interactive:!1,label:"Redis Health",dryRun:e.dryRun});t.push({service:"Redis",healthy:r.exitCode===0,message:r.exitCode===0?"Ready":"Not responding"});let o=await O({command:"docker",args:["compose","exec","-T","clickhouse","curl","-s","http://localhost:8123/ping"],cwd:h(),interactive:!1,label:"ClickHouse Health",dryRun:e.dryRun});t.push({service:"ClickHouse",healthy:o.exitCode===0,message:o.exitCode===0?"Ready":"Not responding"});let a=await O({command:"docker",args:["compose","exec","-T","meilisearch","curl","-s","http://localhost:7700/health"],cwd:h(),interactive:!1,label:"Meilisearch Health",dryRun:e.dryRun});if(t.push({service:"Meilisearch",healthy:a.exitCode===0,message:a.exitCode===0?"Healthy":"Not responding"}),e.format==="json")R(t,{format:"json"});else{for(let l of t){let u=l.healthy?G.green("\u2713"):G.red("\u2716");d(`${u} ${l.service}: ${l.message}`,l.healthy?"success":"error")}let i=t.every(l=>l.healthy);d(`Overall health: ${i?G.green("HEALTHY"):G.red("UNHEALTHY")}`,i?"success":"error")}}async function ul(e,t,n){let r=parseInt(t,10);(Number.isNaN(r)||r<0)&&(d("Invalid replica count (must be a non-negative number)","error"),process.exit(c.INVALID_ARGS)),d(`Scaling ${G.cyan(e)} to ${G.cyan(String(r))} replicas...`,"info");let o=await O({command:"docker",args:["compose","up","-d","--scale",`${e}=${r}`],cwd:h(),interactive:!1,label:`Docker Compose Scale (${e})`,dryRun:n.dryRun});o.exitCode===0?d(`Service ${G.cyan(e)} scaled to ${r} replicas`,"success"):(d(`Failed to scale service ${e}`,"error"),k("Docker error",{stderr:o.stderr}),process.exit(c.ERROR))}function Hr(e){e.command("services <verb> [args...]").description("Manage Docker Compose microservices (postgres, redis, clickhouse, meilisearch, novu, openfga, etc.)").option("--dry-run","Show what would be run without executing").option("--yes","Skip confirmations").option("--format <type>","Output format: json, plain, table","plain").option("--tail <n>","Number of log lines to show (default: 100)").option("--since <duration>","Show logs since duration (e.g., 10m, 1h)").option("--timeout <seconds>","Timeout for service restart").action(async(n,r,o)=>{let a=o.optsWithGlobals?.(),i={dryRun:o.dryRun||a?.dryRun,yes:o.yes||a?.yes,format:o.format||a?.format,tail:o.tail??100,since:o.since,timeout:o.timeout};try{switch(n){case"status":await il(i);break;case"logs":r.length===0&&(d("logs requires a service name: nebutra services logs <service>","error"),process.exit(c.INVALID_ARGS)),await cl(r[0],i);break;case"restart":r.length===0&&(d("restart requires a service name: nebutra services restart <service>","error"),process.exit(c.INVALID_ARGS)),await ll(r[0],i);break;case"health":await dl(i);break;case"scale":r.length<2&&(d("scale requires a service name and replica count: nebutra services scale <service> <count>","error"),process.exit(c.INVALID_ARGS)),await ul(r[0],r[1],i);break;default:d(`Unknown services subcommand: ${n}. Valid commands: status, logs, restart, health, scale`,"error"),process.exit(c.ERROR)}}catch(l){let u=l instanceof Error?l.message:String(l);d(`Services command failed: ${u}`,"error"),k("Full error",{error:l}),process.exit(c.ERROR)}}).addHelpText("after",`
|
|
790
793
|
Examples:
|
|
791
794
|
nebutra services status Show all service status
|
|
792
795
|
nebutra services logs postgres Stream postgres logs
|
|
@@ -807,22 +810,22 @@ Flags:
|
|
|
807
810
|
--tail <n> Log lines to show (default: 100)
|
|
808
811
|
--since <duration> Show logs since (e.g., 10m, 1h)
|
|
809
812
|
--timeout <seconds> Timeout for restart
|
|
810
|
-
`)}import{existsSync as ne,readdirSync as
|
|
811
|
-
${
|
|
812
|
-
`),r.forEach(a=>{console.log(` ${
|
|
813
|
-
${
|
|
814
|
-
`),r.forEach(a=>{let i=a.status==="ready"?
|
|
815
|
-
${n}`)}return t}async function
|
|
816
|
-
`)}function Rl(e,t="table"){let n=
|
|
817
|
-
`)}function
|
|
818
|
-
`)}function
|
|
819
|
-
`)}function
|
|
820
|
-
`)}return JSON.stringify(e,null,2)}function
|
|
821
|
-
`):JSON.stringify(e,null,2)}function
|
|
813
|
+
`)}import{existsSync as ne,readdirSync as rt,readFileSync as Wr}from"fs";import{resolve as V}from"path";import Ve from"picocolors";function $e(e,t,n){if(t==="json"){let r={command:n||"stats",...e};console.log(JSON.stringify(r,null,2))}else e.stdout&&(console.log(e.stdout),delete e.stdout),Object.keys(e).length>0&&console.log(JSON.stringify(e,null,2))}function Jr(e){try{let t=Wr(V(e,"package.json"),"utf-8");return JSON.parse(t)}catch{return{}}}function Xr(e){try{return rt(e,{recursive:!0}).length}catch{return 0}}async function ml(e){s.info("Gathering monorepo statistics...");let t=h(),n=V(t,"packages"),r=V(t,"apps"),o=[],a=[],i=0,l="unknown";try{ne(n)&&(o=rt(n).filter(f=>!f.startsWith(".")&&ne(V(n,f,"package.json")))),ne(r)&&(a=rt(r).filter(f=>!f.startsWith(".")&&ne(V(r,f,"package.json"))));let m=V(t,"nebutra.config.ts");if(ne(m)){let y=Wr(m,"utf-8").match(/preset:\s*["']([^"']+)["']/);y&&(l=y[1])}}catch(m){s.warn(`Failed to read monorepo structure: ${m instanceof Error?m.message:String(m)}`)}let u={monorepo:{root:t,packages:o.length,apps:a.length,preset:l},statistics:{totalWorkspaces:o.length+a.length,packageCount:o.length,appCount:a.length}};e.dryRun||(s.success(`Found ${u.statistics.totalWorkspaces} workspaces`),s.info(`Packages: ${u.statistics.packageCount}, Apps: ${u.statistics.appCount}`),s.info(`Preset: ${l}`)),$e(u,e.format,"stats")}async function pl(e){s.info("Analyzing bundle and dependency sizes...");let t=await O({command:"pnpm",args:["size"],interactive:!1,label:"Analyze package sizes",dryRun:e.dryRun}),n={analysis:"pnpm size",exitCode:t.exitCode,...t.stdout&&{stdout:t.stdout},...t.stderr&&{stderr:t.stderr}};t.exitCode!==0&&s.warn("Size analysis failed. Ensure your project is built."),$e(n,e.format,"stats:size")}async function fl(e){s.info("Analyzing dependencies...");let t=await O({command:"npx",args:["knip","--no-progress"],interactive:!1,label:"Analyze dependencies",dryRun:e.dryRun}),n={analysis:"knip (unused dependencies)",exitCode:t.exitCode,command:"npx knip",...t.stdout&&{stdout:t.stdout.substring(0,500)}};e.dryRun||(t.exitCode===0?s.success("No unused dependencies detected"):s.info("Run 'npx knip' to see detailed dependency analysis")),$e(n,e.format,"stats:deps")}async function gl(e){s.info("Listing packages...");let t=h(),n=V(t,"packages"),r=[];try{ne(n)&&(r=rt(n).filter(i=>!i.startsWith(".")&&ne(V(n,i,"package.json"))).map(i=>{let l=V(n,i),u=Jr(l);return{name:u.name||i,version:u.version,description:u.description,files:Xr(l)}}))}catch(a){s.error(`Failed to list packages: ${a instanceof Error?a.message:String(a)}`),process.exit(c.ERROR)}let o={packages:r,total:r.length};e.dryRun||e.format==="json"?$e(o,e.format,"stats:packages"):(console.log(`
|
|
814
|
+
${Ve.cyan("Packages")} (${r.length} total)
|
|
815
|
+
`),r.forEach(a=>{console.log(` ${Ve.blue(a.name)}`),a.version&&console.log(` version: ${a.version}`),a.description&&console.log(` ${a.description}`),console.log(` files: ${a.files}`)}),console.log(""))}async function yl(e){s.info("Listing apps...");let t=h(),n=V(t,"apps"),r=[];try{ne(n)&&(r=rt(n).filter(i=>!i.startsWith(".")&&ne(V(n,i,"package.json"))).map(i=>{let l=V(n,i),u=Jr(l),m=ne(V(l,"next.config.ts"))||ne(V(l,"next.config.js")),f=ne(V(l,"server.ts"))||ne(V(l,"server.js"));return{name:u.name||i,version:u.version,description:u.description,files:Xr(l),status:m||f?"ready":"unknown"}}))}catch(a){s.error(`Failed to list apps: ${a instanceof Error?a.message:String(a)}`),process.exit(c.ERROR)}let o={apps:r,total:r.length,ready:r.filter(a=>a.status==="ready").length};e.dryRun||e.format==="json"?$e(o,e.format,"stats:apps"):(console.log(`
|
|
816
|
+
${Ve.cyan("Apps")} (${r.length} total, ${o.ready} ready)
|
|
817
|
+
`),r.forEach(a=>{let i=a.status==="ready"?Ve.green("\u2713"):Ve.gray("\u25CB");console.log(` ${i} ${Ve.blue(a.name)}`),a.version&&console.log(` version: ${a.version}`),a.description&&console.log(` ${a.description}`),console.log(` files: ${a.files}`)}),console.log(""))}function Qr(e){let t=e.command("stats").description("Project statistics and health checks");t.command("*",{isDefault:!0}).description("Show monorepo overview").option("--format <type>","Output format: json or plain").action(async n=>{let r=typeof n.optsWithGlobals=="function"?n.optsWithGlobals():n;await ml({format:typeof n.format=="string"?n.format:typeof r.format=="string"?r.format:void 0})}),t.command("size").description("Analyze bundle and package sizes").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await pl({format:n.format||r.format})}),t.command("deps").description("Analyze dependencies (unused, missing, duplicate)").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await fl({format:n.format||r.format})}),t.command("packages").description("List all packages with metadata").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await gl({format:n.format||r.format})}),t.command("apps").description("List all apps with status").option("--format <type>","Output format: json or plain").action(async n=>{let r=n.optsWithGlobals?.()||n;await yl({format:n.format||r.format})})}import*as K from"@clack/prompts";import $ from"picocolors";function ke(e){if(e==="json"||e==="plain"||e==="table")return e}var rn=["landing","web","storybook","backends/gateway","design-docs","studio","docs","ui","tokens","brand","theme","icons","preset","queue","search","notifications","permissions","webhooks","metering","uploads","vault","tenant"];function hl(e){let t=`@nebutra/${e}`;if(!rn.includes(e)){let n=$.yellow(`Valid apps: ${rn.join(", ")}`);throw new Error(`Invalid app: ${$.red(e)}
|
|
818
|
+
${n}`)}return t}async function bl(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"test",options:{app:e.app,watch:e.watch,coverage:e.coverage},task:e.coverage?"pnpm test:coverage":e.watch?"pnpm test:watch":"pnpm test"},{format:ke(e.format)}),process.exit(c.DRY_RUN_OK));try{if(e.app&&(e.watch||e.coverage)&&(K.log.error($.red("Cannot use --watch or --coverage with --app filter (app-level tests use turbo)")),process.exit(c.INVALID_ARGS)),e.app){hl(e.app);let r=`@nebutra/${e.app}`;e.quiet||K.log.info($.cyan(`Running tests for ${$.bold(r)}...`));let o=await we("test",{filter:r});process.exit(o.exitCode)}let t="test";if(e.coverage?t="test:coverage":e.watch&&(t="test:watch"),!e.quiet){let r=t==="test:coverage"?"Running tests with coverage...":t==="test:watch"?"Running tests in watch mode...":"Running tests...";K.log.info($.cyan(r))}let n=await z(t,{interactive:!0});process.exit(n.exitCode)}catch(t){t instanceof Error?K.log.error($.red(t.message)):K.log.error($.red("Unknown error occurred")),process.exit(c.ERROR)}}async function Zr(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"test e2e",options:{ui:e.ui,ci:e.ci},task:e.ci?"pnpm e2e:ci":e.ui?"pnpm e2e:ui":"pnpm e2e"},{format:ke(e.format)}),process.exit(c.DRY_RUN_OK));try{e.ui&&e.ci&&(K.log.error($.red("Cannot use --ui and --ci together")),process.exit(c.INVALID_ARGS));let t="e2e";if(e.ci?t="e2e:ci":e.ui&&(t="e2e:ui"),!e.quiet){let r=t==="e2e:ci"?"Running E2E tests (CI mode)...":t==="e2e:ui"?"Opening E2E tests in UI mode...":"Running E2E tests...";K.log.info($.cyan(r))}let n=await z(t,{interactive:!0});process.exit(n.exitCode)}catch(t){t instanceof Error?K.log.error($.red(t.message)):K.log.error($.red("Unknown error occurred")),process.exit(c.ERROR)}}async function eo(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"test size",options:{why:e.why},task:e.why?"pnpm size:why":"pnpm size"},{format:ke(e.format)}),process.exit(c.DRY_RUN_OK));try{let t=e.why?"size:why":"size";if(!e.quiet){let r=e.why?"Analyzing bundle size (showing largest assets)...":"Checking bundle size...";K.log.info($.cyan(r))}let n=await z(t,{interactive:!0});process.exit(n.exitCode)}catch(t){t instanceof Error?K.log.error($.red(t.message)):K.log.error($.red("Unknown error occurred")),process.exit(c.ERROR)}}async function to(e){e.dryRun&&(A({mode:"dry-run",timestamp:new Date().toISOString(),command:"test arch",task:"pnpm test:arch"},{format:ke(e.format)}),process.exit(c.DRY_RUN_OK));try{e.quiet||K.log.info($.cyan("Running architecture tests..."));let t=await z("test:arch",{interactive:!0});process.exit(t.exitCode)}catch(t){t instanceof Error?K.log.error($.red(t.message)):K.log.error($.red("Unknown error occurred")),process.exit(c.ERROR)}}var no=e=>{let t=e.command("test [subcommand]").description("Run tests (Vitest, Playwright, bundle size, architecture)").option("--watch","Run tests in watch mode (unit tests only)").option("--coverage","Generate coverage report (unit tests only)").option("--app <name>",`Run tests for specific app: ${rn.join(", ")}`).option("--dry-run","Preview what would run (exit code 10)").action(async(n,r,o)=>{let a=x(r,o),i={dryRun:!!r.dryRun,quiet:!!a.quiet,verbose:!!a.verbose,format:ke(a.format)};n==="e2e"?await Zr({...i,ui:!!r.ui,ci:!!r.ci}):n==="size"?await eo({...i,why:!!r.why}):n==="arch"?await to(i):await bl({...i,watch:!!r.watch,coverage:!!r.coverage,app:typeof r.app=="string"?r.app:void 0})});t.command("e2e").description("Run end-to-end tests (Playwright)").option("--ui","Open interactive UI mode").option("--ci","Run in CI mode with strict options").option("--dry-run","Preview what would run (exit code 10)").action(async(n,r)=>{let o=x(n,r);await Zr({ui:!!n.ui,ci:!!n.ci,dryRun:!!n.dryRun,quiet:!!o.quiet,verbose:!!o.verbose,format:ke(o.format)})}),t.command("size").description("Check bundle size (analyze largest assets)").option("--why","Show breakdown of largest bundle assets").option("--dry-run","Preview what would run (exit code 10)").action(async(n,r)=>{let o=x(n,r);await eo({why:!!n.why,dryRun:!!n.dryRun,quiet:!!o.quiet,verbose:!!o.verbose,format:ke(o.format)})}),t.command("arch").description("Run architecture tests (verify design layer isolation)").option("--dry-run","Preview what would run (exit code 10)").action(async(n,r)=>{let o=x(n,r);await to({dryRun:!!n.dryRun,quiet:!!o.quiet,verbose:!!o.verbose,format:ke(o.format)})})};var ro={$schema:"https://nebutra.com/schemas/design-language-registry.json",version:"2026.07",defaultLanguage:"factory",description:"Design-language catalog for global product chrome swap (Create Center / SaaS theme). Not color moods \u2014 full Brand Packages (roles + recipe + elev + zones).",languages:[{id:"factory",name:"Nebutra Factory",kind:"design-language",description:"Default product chrome from @nebutra/tokens (no skin). Clear data-brand to restore.",proves:["factory HSL SSOT","recipe defaults","action\u2261brand-mark until skin"],darkDefault:!0,brandPath:null,skinPath:null,install:{command:"nebutra theme use factory",cssImport:null},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"gsap",name:"GSAP",kind:"design-language",description:"Dark cream-on-void; shockingly-green is accent \u2014 CTA is gradient-stroke/outline, not solid green fill.",proves:["outline / gradient-stroke recipe","category extensions","marketing display zone"],darkDefault:!0,brandPath:"brands/gsap/brand.json",skinPath:"skins/gsap.css",install:{command:"nebutra theme use gsap",cssImport:"@nebutra/tokens/skins/gsap.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"linear",name:"Linear",kind:"design-language",description:"Dual-mode: dark void default + light paper; solid acid-lime CTA, compact density.",proves:["chromatic solid action","dark product chrome","dual-mode light/dark palettes"],darkDefault:!0,brandPath:"brands/linear/brand.json",skinPath:"skins/linear.css",install:{command:"nebutra theme use linear",cssImport:"@nebutra/tokens/skins/linear.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"notion",name:"Notion",kind:"design-language",description:"Warm paper notebook; Notion Blue sole filled CTA \u2260 Ink brand-mark; 8px buttons / 12px cards; elev=none + hairline; accent hues decorative only.",proves:["action \u2260 brand-mark (blue vs ink)","canvas\u2260card (paper-warmth vs pure-white)","elevation=none content cards + raised nav shadow slot","table radius priority (8/12 over tertiary 4px)","decorative accents never product CTA"],darkDefault:!1,brandPath:"brands/notion/brand.json",skinPath:"skins/notion.css",install:{command:"nebutra theme use notion",cssImport:"@nebutra/tokens/skins/notion.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"raycast",name:"Raycast",kind:"design-language",description:"Neutral Mist/Iron filled CTA; Coral is brand-mark only. Key elevation stack.",proves:["action \u2260 brand-mark","elevation=key free CSS"],darkDefault:!0,brandPath:"brands/raycast/brand.json",skinPath:"skins/raycast.css",install:{command:"nebutra theme use raycast",cssImport:"@nebutra/tokens/skins/raycast.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"stripe",name:"Stripe",kind:"design-language",description:"Indigo-ink ledger on frost glass; Indigo action \u2260 Midnight brand-mark; 4px controls; elevation=none (tint + frost rules).",proves:["action \u2260 brand-mark (chromatic indigo vs midnight)","elevation=none tint-ladder depth","4px squared controls (not pill)","whisper heading weight 300"],darkDefault:!1,brandPath:"brands/stripe/brand.json",skinPath:"skins/stripe.css",install:{command:"nebutra theme use stripe",cssImport:"@nebutra/tokens/skins/stripe.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"vanta",name:"Vanta",kind:"design-language",description:"Editorial violet on parchment; Vivid Violet action \u2260 Indigo Ink brand-mark; full pills; elevation=none (carbon hairlines).",proves:["action \u2260 brand-mark (chromatic)","elevation=none border-only","999px pill controls","serif display + sans UI zones"],darkDefault:!1,brandPath:"brands/vanta/brand.json",skinPath:"skins/vanta.css",install:{command:"nebutra theme use vanta",cssImport:"@nebutra/tokens/skins/vanta.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}},{id:"vercel",name:"Vercel",kind:"design-language",description:"Monochrome dual-mode: light paper + Obsidian CTA; dark carbon + white CTA; hairline elevation (no chromatic CTA).",proves:["light monochrome action","elevation=hairline","dual-mode light/dark palettes"],darkDefault:!1,brandPath:"brands/vercel/brand.json",skinPath:"skins/vercel.css",install:{command:"nebutra theme use vercel",cssImport:"@nebutra/tokens/skins/vercel.css"},compatibility:{tailwind:"4",cssVariables:!0,brandPackage:!0,dataBrand:!0}}]};var Te=ro,bf=Te.languages.map(e=>e.id),oo=Te.defaultLanguage;function so(e){return Te.languages.find(t=>t.id===e)}function ao(e){let t=e.opts?e.opts():e,n=e.optsWithGlobals?e.optsWithGlobals():e;return t.format??n.format??wl()}function wl(){let e=process.argv.find(n=>n.startsWith("--format="));if(e)return e.slice(9);let t=process.argv.indexOf("--format");if(t>=0)return process.argv[t+1]}function Sl(e="table"){let t=Te.languages;return e==="json"?JSON.stringify({version:Te.version,defaultLanguage:Te.defaultLanguage,count:t.length,languages:t},null,2):[`Nebutra design languages (${t.length}) \u2014 global product chrome swap`,`Default: ${oo} (factory tokens; no skin)`,"Contract: roles.action \u2192 CTA; roles.brand \u2192 brand-mark; free elev/radii/zones","",...t.map(r=>`${r.id.padEnd(10)} ${r.darkDefault?"dark ":"light"} ${(r.proves[0]??"").slice(0,48)} ${r.description.slice(0,56)}`)].join(`
|
|
819
|
+
`)}function Rl(e,t="table"){let n=so(e);if(n)return t==="json"?JSON.stringify(n,null,2):[`${n.name} (${n.id}) \u2014 design language`,`Description: ${n.description}`,`Dark default: ${n.darkDefault}`,`Brand JSON: ${n.brandPath??"(factory \u2014 none)"}`,`Skin CSS: ${n.skinPath??"(factory \u2014 none)"}`,`Install: ${n.install.command}`,`CSS import: ${n.install.cssImport??"(clear data-brand)"}`,`Proves: ${n.proves.join("; ")}`].join(`
|
|
820
|
+
`)}function io(e){let t=e.command("theme").description("Design languages (Brand Package global product chrome swap)");t.command("list").description("List design languages").option("--format <type>","Output format: json or table").action(n=>{console.log(Sl(ao(n)))}),t.command("inspect <id>").description("Show a design language by id").option("--format <type>","Output format: json or table").action((n,r)=>{let o=Rl(n,ao(r));o||(s.error(`Design language '${n}' not found. Run: nebutra theme list`),process.exit(c.NOT_FOUND)),console.log(o)})}import{existsSync as uo,readFileSync as mo}from"fs";import{resolve as co,join as on}from"path";function po(e={}){let t=e.manifestPath?co(e.manifestPath):on(co(e.root??process.cwd()),"apps","design-docs","public","agent-manifest.json");return{manifestPath:t,componentDir:on(t,"..","agent","components")}}function Cl(e){return e.trim().toLowerCase()}function El(e){let t=Cl(e);if(!/^[a-z0-9-]+$/.test(t))throw new Error(`Invalid UI component name "${e}". Use a registry kebab-case id such as "button".`);return t}function fo(e={}){let{manifestPath:t}=po(e);if(!uo(t))throw new Error(`Missing Nebutra UI agent manifest at ${t}. Run pnpm --filter @nebutra/design-docs build:registry.`);return JSON.parse(mo(t,"utf8"))}function sn(e,t={}){let n=El(e),{componentDir:r}=po(t),o=on(r,`${n}.json`);if(!uo(o))throw new Error(`UI component contract not found: ${n}`);return JSON.parse(mo(o,"utf8"))}function go(e,t="",n={}){let r=t.trim().toLowerCase(),o=lo(n.limit??20,1,100),a=lo(n.offset??0,0,Number.MAX_SAFE_INTEGER),i=n.tag?.trim().toLowerCase(),l=e.components.filter(f=>n.status&&f.status!==n.status||n.maturity&&f.maturity!==n.maturity||i&&!f.tags.includes(i)?!1:r?kl(f).includes(r):!0).map(f=>({component:f,score:xl(f,r)})).sort((f,y)=>y.score-f.score||f.component.name.localeCompare(y.component.name)).map(({component:f})=>f),u=l.slice(a,a+o),m=a+u.length;return{query:t,total:l.length,count:u.length,offset:a,limit:o,hasMore:m<l.length,...m<l.length&&{nextOffset:m},items:u}}function an(e){let t=[],n=[];return e.evidence.source||t.push("Missing source evidence."),e.evidence.docs||t.push("Missing docs evidence."),e.evidence.registry||t.push("Missing registry evidence."),(e.status==="stable"||e.maturity==="canonical")&&!e.evidence.storybook&&t.push("Stable/canonical components must have Storybook evidence."),!e.evidence.tokens&&e.package==="@nebutra/ui"&&n.push("No token evidence was detected; confirm this primitive intentionally has no CSS variables."),e.migration.requiredForBreakingChanges&&e.migration.hints.length===0&&n.push("Breaking-change migration policy is enabled but no migration hints are present."),{name:e.name,valid:t.length===0,errors:t,warnings:n,evidence:e.evidence,migration:e.migration}}function kl(e){return[e.name,e.title,e.description,e.status,e.maturity,e.layer,e.source,...e.tags].join(" ").toLowerCase()}function xl(e,t){return t?e.name===t?100:e.name.startsWith(t)?80:e.title.toLowerCase().startsWith(t)?70:e.tags.includes(t)?60:e.name.includes(t)?50:e.title.toLowerCase().includes(t)?40:e.description.toLowerCase().includes(t)?20:1:e.maturity==="canonical"?20:10}function lo(e,t,n){return Number.isFinite(e)?Math.min(Math.max(Math.trunc(e),t),n):t}import{stderr as Ol}from"process";import xe from"picocolors";function Al(){return process.stderr.isTTY===!0&&!process.env.CI&&!process.env.NEBUTRA_NON_TTY}function _l(e){let t=[];return t.push(xe.red(`\u2716 ${e.error}`)),t.push(xe.white(e.message)),e.suggestion&&(t.push(""),t.push(xe.cyan("\u{1F4A1} Suggestion:")),t.push(xe.gray(` ${e.suggestion}`))),process.env.NEBUTRA_DEBUG&&e.context&&Object.keys(e.context).length>0&&(t.push(""),t.push(xe.dim("Debug context:")),t.push(xe.dim(JSON.stringify(e.context,null,2)))),process.env.NEBUTRA_DEBUG&&e.stack&&(t.push(""),t.push(xe.dim("Stack trace:")),t.push(xe.dim(e.stack))),t.join(`
|
|
821
|
+
`)}function Pl(e){let t={error:e.error,message:e.message,...e.suggestion&&{suggestion:e.suggestion},retryable:e.retryable,exitCode:e.exitCode,...e.context&&Object.keys(e.context).length>0&&{context:e.context},...process.env.NEBUTRA_DEBUG&&e.stack&&{stack:e.stack}};return JSON.stringify(t)}function ot(e){return{error:e.error,message:e.message,suggestion:e.suggestion,retryable:e.retryable??!1,exitCode:e.exitCode??c.ERROR,context:e.context,stack:e.cause?.stack}}function cn(e){let t=Al()?_l(e):Pl(e);Ol.write(t+`
|
|
822
|
+
`)}function Il(e){cn(e),process.exit(e.exitCode)}function ln(e,t){Il(ot({error:"not_found",message:e,suggestion:t??"Check the resource path and try again",exitCode:c.NOT_FOUND}))}function $t(e){let t=e.opts?e.opts():e,n=e.optsWithGlobals?e.optsWithGlobals():e;return t.format??n.format??Nl()}function Nl(){let e=process.argv.find(n=>n.startsWith("--format="));if(e)return e.slice(9);let t=process.argv.indexOf("--format");if(t>=0)return process.argv[t+1]}function un(e){let t=e.opts?e.opts():e;return{root:h(),manifestPath:t.manifest}}function yo(e,t){if(!e)return t;let n=Number(e);return Number.isFinite(n)?n:t}function $l(e,t="json"){if(t==="plain"||t==="table"){let n=[`Nebutra UI components (${e.total})`,""];for(let r of e.items)n.push(`${r.name.padEnd(22)} ${r.status.padEnd(12)} ${r.maturity.padEnd(10)} ${r.title}`);return e.hasMore&&n.push("",`Next offset: ${e.nextOffset}`),n.join(`
|
|
823
|
+
`)}return JSON.stringify(e,null,2)}function Tl(e,t="json"){return t==="plain"||t==="table"?[`${e.title} (${e.name})`,`Status: ${e.status}`,`Maturity: ${e.maturity}`,`Source: ${e.source}`,`Package import: ${e.imports.package}`,`Registry: ${e.imports.registry}`,`Docs: ${e.docs.routes.join(", ")||"missing"}`,`Storybook: ${e.docs.storybook??"missing"}`,`Tokens: ${e.tokens.join(", ")||"none detected"}`].join(`
|
|
824
|
+
`):JSON.stringify(e,null,2)}function Ul(e,t="json"){if(t==="plain"||t==="table"){if("results"in e){let n=[`Nebutra UI validation: ${e.valid?"valid":"invalid"}`,`Total: ${e.total}`,`Invalid: ${e.invalid}`];for(let r of e.results.filter(o=>!o.valid))n.push(`- ${r.name}: ${r.errors.join("; ")}`);return n.join(`
|
|
822
825
|
`)}return[`${e.name}: ${e.valid?"valid":"invalid"}`,...e.errors.map(n=>`error: ${n}`),...e.warnings.map(n=>`warning: ${n}`)].join(`
|
|
823
|
-
`)}return JSON.stringify(e,null,2)}function
|
|
824
|
-
`):JSON.stringify(n,null,2)}function
|
|
825
|
-
`),t?console.log(JSON.stringify({command:"unlink",success:!0,configPath:r},null,2)):s.success("Unlinked from project")}function
|
|
826
|
+
`)}return JSON.stringify(e,null,2)}function jl(e,t="json"){let n={component:e.name,dryRun:!0,codemods:e.migration.codemods,hints:e.migration.hints,requiredForBreakingChanges:e.migration.requiredForBreakingChanges};return t==="plain"||t==="table"?[`Migration hints for ${e.name}`,`Codemods: ${n.codemods.length===0?"none registered":n.codemods.join(", ")}`,...n.hints.map(r=>`- ${r}`)].join(`
|
|
827
|
+
`):JSON.stringify(n,null,2)}function dn(e,t){try{return sn(e,un(t))}catch{ln(`UI component contract not found: ${e}`,"Run `nebutra ui search <query> --format json` to discover available component ids.")}}function ho(e){try{return fo(un(e))}catch(t){ln(t instanceof Error?t.message:"UI agent manifest not found","Run `pnpm --filter @nebutra/design-docs build:registry` from the Nebutra monorepo.")}}function Ll(e,t){let n=e.components.map(o=>an(sn(o.name,un(t)))),r=n.filter(o=>!o.valid).length;return{valid:r===0,total:n.length,invalid:r,results:n}}function bo(e){let t=e.command("ui").description("Inspect Nebutra UI agent contracts, production evidence, and migration hints");t.command("search [query]").description("Search the agent-readable @nebutra/ui component contract").option("--limit <number>","Maximum number of results","20").option("--offset <number>","Pagination offset","0").option("--tag <tag>","Filter by generated tag").option("--status <status>","Filter by status").option("--maturity <maturity>","Filter by maturity").option("--manifest <path>","Read a specific agent-manifest.json").option("--format <type>","Output format: json, table, plain").action((n,r)=>{let o=ho(r),a=go(o,n??"",{limit:yo(r.limit,20),offset:yo(r.offset,0),tag:r.tag,status:r.status,maturity:r.maturity});console.log($l(a,$t(r)))}),t.command("component <name>").description("Print one component contract with imports, evidence, and migration policy").option("--manifest <path>","Read a specific agent-manifest.json").option("--format <type>","Output format: json, table, plain").action((n,r)=>{let o=dn(n,r);console.log(Tl(o,$t(r)))}),t.command("validate [name]").description("Validate production evidence for one component or the full UI contract").option("--manifest <path>","Read a specific agent-manifest.json").option("--warn-only","Report validation failures without a non-zero exit").option("--format <type>","Output format: json, table, plain").action((n,r)=>{let o=n?an(dn(n,r)):Ll(ho(r),r);console.log(Ul(o,$t(r))),!o.valid&&!r.warnOnly&&process.exit(c.INCOMPATIBLE)}),t.command("migrate <name>").description("Print dry-run codemod and migration hints for a component").option("--manifest <path>","Read a specific agent-manifest.json").option("--apply","Reserved for future codemod execution").option("--format <type>","Output format: json, table, plain").action((n,r)=>{r.apply&&(console.error("Codemod execution is not implemented yet. Use `nebutra ui migrate <name>` for the dry-run plan."),process.exit(c.INCOMPATIBLE));let o=dn(n,r);console.log(jl(o,$t(r)))})}import{existsSync as vo,readFileSync as Dl,unlinkSync as Fl,writeFileSync as Bl}from"fs";import{dirname as Ml,join as wo,parse as Gl}from"path";function Vl(e){let t=e,{root:n}=Gl(t);for(;;){if(vo(wo(t,"package.json")))return t;if(t===n)return null;let r=Ml(t);if(r===t)return null;t=r}}async function Kl(e){let t=e.format==="json",n=Vl(process.cwd())??process.cwd(),r=wo(n,"nebutra.config.json");if(vo(r)||(t?console.log(JSON.stringify({command:"unlink",success:!0,alreadyUnlinked:!0},null,2)):s.info("Already unlinked"),process.exit(c.SUCCESS)),e.force){try{Fl(r)}catch(l){let u=l instanceof Error?l.message:String(l);t?console.log(JSON.stringify({command:"unlink",success:!1,error:u},null,2)):s.error(`Failed to delete config: ${u}`),process.exit(c.PERMISSION_DENIED)}t?console.log(JSON.stringify({command:"unlink",success:!0,deletedConfig:!0,configPath:r},null,2)):s.success("Removed nebutra.config.json");return}let o={};try{o=JSON.parse(Dl(r,"utf-8"))}catch{o={}}"projectId"in o||(t?console.log(JSON.stringify({command:"unlink",success:!0,alreadyUnlinked:!0},null,2)):s.info("Already unlinked"),process.exit(c.SUCCESS));let{projectId:a,...i}=o;Bl(r,JSON.stringify(i,null,2)+`
|
|
828
|
+
`),t?console.log(JSON.stringify({command:"unlink",success:!0,configPath:r},null,2)):s.success("Unlinked from project")}function So(e){e.command("unlink").description("Remove the project link from nebutra.config.json").option("--force","Delete the entire nebutra.config.json").option("--format <type>","Output format: json or plain").action(async(t,n)=>{let r=n?.optsWithGlobals?.()||t;await Kl({force:t.force||!1,format:t.format||r.format})})}import{spawnSync as nd}from"child_process";import{readFileSync as rd}from"fs";import{dirname as od,join as sd}from"path";import{fileURLToPath as ad}from"url";import{promises as Tt}from"fs";import{homedir as ql}from"os";import{join as Co}from"path";import zl from"p-timeout";import Oe from"picocolors";var Yl=1440*60*1e3,Eo=Co(ql(),".nebutra"),mn=Co(Eo,"update-check.json"),Hl="https://registry.npmjs.org/nebutra",Wl=5e3;async function Jl(){try{await Tt.mkdir(Eo,{recursive:!0})}catch{}}async function Xl(){try{let e=await Tt.readFile(mn,"utf-8"),t=JSON.parse(e);return Date.now()-t.timestamp<Yl?t:(await Tt.unlink(mn).catch(r=>{s.debug("Failed to remove expired update cache file",{error:r})}),null)}catch{return null}}async function Ql(e){try{await Jl();let t={timestamp:Date.now(),latestVersion:e};await Tt.writeFile(mn,JSON.stringify(t,null,2),"utf-8")}catch{}}async function Zl(){try{let e=new AbortController,t=await zl(fetch(Hl,{signal:e.signal,headers:{Accept:"application/json"}}),{milliseconds:Wl,fallback:()=>(e.abort(),null)});if(!t?.ok)return null;let r=(await t.json())["dist-tags"];return!r||typeof r.latest!="string"?null:r.latest}catch{return null}}function Ro(e){return e.split(".").map(t=>parseInt(t.replace(/[^0-9]/g,""),10)||0).slice(0,3)}function ed(e,t){let n=Ro(e),r=Ro(t);for(let o=0;o<3;o++){let a=n[o]??0,i=r[o]??0;if(i>a)return!0;if(i<a)return!1}return!1}async function pn(e){let t=await Xl(),n=null;return t?n=t.latestVersion:(n=await Zl(),n&&await Ql(n)),!n||!ed(e,n)?null:{currentVersion:e,latestVersion:n,isUpdate:!0}}function td(e){let n=`Update available: ${e.currentVersion} \u2192 ${e.latestVersion}`,r="Run `npm i -g nebutra` to update",o=" ".repeat((43-n.length)/2),a=" ".repeat((43-r.length)/2),i=[Oe.cyan("\u256D"+"\u2500".repeat(41)+"\u256E"),Oe.cyan("\u2502")+Oe.yellow(o+n+o)+Oe.cyan("\u2502"),Oe.cyan("\u2502")+Oe.gray(a+r+a)+Oe.cyan("\u2502"),Oe.cyan("\u2570"+"\u2500".repeat(41)+"\u256F")]}async function ko(e){let t=null;return pn(e).then(n=>{t=n}),async()=>{!process.stdout.isTTY||process.env.CI||(t||await new Promise(n=>setTimeout(n,100)),t&&td(t))}}var id=sd(od(ad(import.meta.url)),"..","..","package.json"),Ue=JSON.parse(rd(id,"utf8")).version;function cd(){let t=(process.argv[1]||"").toLowerCase();if(t.includes("/homebrew/")||t.includes("/cellar/"))return"brew";if(t.includes("/.bun/")||t.includes("/bun/"))return"bun";if(t.includes("/pnpm/")||t.includes("/.pnpm/"))return"pnpm";if(t.includes("/yarn/")||t.includes("/.yarn/"))return"yarn";if(t.includes("/npm/")||t.includes("/node_modules/"))return"npm";let n=process.env.npm_config_user_agent||"";return n.startsWith("pnpm")?"pnpm":n.startsWith("yarn")?"yarn":n.startsWith("bun")?"bun":n.startsWith("npm")?"npm":"unknown"}function ld(e){switch(e){case"pnpm":return"pnpm add -g nebutra@latest";case"yarn":return"yarn global add nebutra@latest";case"bun":return"bun add -g nebutra@latest";case"brew":return"brew upgrade nebutra";case"npm":return"npm i -g nebutra@latest";default:return"npm i -g nebutra@latest"}}async function dd(e){let t=cd(),n=ld(t),r=e.format==="json",o=await pn(Ue),a=o?.latestVersion??null,i=!!o?.isUpdate;e.dryRun&&(r?console.log(JSON.stringify({command:"upgrade",dryRun:!0,installer:t,command_to_run:n,currentVersion:Ue,latestVersion:a,hasUpdate:i},null,2)):(s.info(`Detected installer: ${t}`),s.info(`Current: ${Ue}${a?` \u2192 Latest: ${a}`:""}`),s.info(`Upgrade command: ${n}`)),process.exit(c.DRY_RUN_OK)),!i&&a&&(r?console.log(JSON.stringify({command:"upgrade",success:!0,alreadyLatest:!0,version:Ue},null,2)):s.success(`Already on the latest version (${Ue})`),process.exit(c.SUCCESS)),e.yes||(r?console.log(JSON.stringify({command:"upgrade",success:!0,installer:t,command_to_run:n,currentVersion:Ue,latestVersion:a,requiresConfirmation:!0},null,2)):(s.info(`Current: ${Ue}${a?` \u2192 Latest: ${a}`:""}`),s.info("To upgrade, run:"),s.info(` ${n}`),s.info("Or re-run this command with --yes to execute it now.")),process.exit(c.SUCCESS));let[l,...u]=n.split(" ");r||s.info(`Running: ${n}`);let m=nd(l,u,{stdio:r?"pipe":"inherit"});m.status===0&&(r?console.log(JSON.stringify({command:"upgrade",success:!0,installer:t,ran:n},null,2)):s.success("Upgrade complete"),process.exit(c.SUCCESS));let f=m.stderr?.toString()||`Upgrade failed (exit ${m.status})`;r?console.log(JSON.stringify({command:"upgrade",success:!1,installer:t,ran:n,error:f},null,2)):s.error(f),process.exit(c.ERROR)}function xo(e){let t=(n,r)=>{let o=r?.optsWithGlobals?.()||n;return dd({yes:n.yes||o.yes||!1,dryRun:n.dryRun||!1,format:n.format||o.format})};e.command("upgrade").alias("self-update").description("Upgrade the nebutra CLI to the latest version").option("--yes","Execute the upgrade command without confirmation").option("--dry-run","Show the upgrade command without executing (exit 10)").option("--format <type>","Output format: json or plain").action(t)}import fn from"fs";import gn from"path";import ud from"picocolors";var yn=["inngest","n8n","pusher"],md=`import { Inngest } from "inngest";
|
|
826
829
|
|
|
827
830
|
export const inngest = new Inngest({ id: "nebutra-sailor" });
|
|
828
831
|
|
|
@@ -836,7 +839,7 @@ export const exampleFn = inngest.createFunction(
|
|
|
836
839
|
return { status: "completed" };
|
|
837
840
|
},
|
|
838
841
|
);
|
|
839
|
-
`,
|
|
842
|
+
`,pd=`# n8n Workflows (Self-hosted Convention)
|
|
840
843
|
|
|
841
844
|
Nebutra Sailor uses n8n in self-hosted mode for visual workflow orchestration.
|
|
842
845
|
|
|
@@ -860,7 +863,7 @@ docker run -it --rm \\
|
|
|
860
863
|
## Webhook endpoints
|
|
861
864
|
|
|
862
865
|
Production webhooks route through \`backends/gateway\` (see \`packages/integrations/webhooks\`).
|
|
863
|
-
`,
|
|
866
|
+
`,fd=`{
|
|
864
867
|
"name": "example-workflow",
|
|
865
868
|
"nodes": [
|
|
866
869
|
{
|
|
@@ -876,7 +879,7 @@ Production webhooks route through \`backends/gateway\` (see \`packages/integrati
|
|
|
876
879
|
"settings": {},
|
|
877
880
|
"tags": []
|
|
878
881
|
}
|
|
879
|
-
`,
|
|
882
|
+
`,gd=`import Pusher from "pusher";
|
|
880
883
|
|
|
881
884
|
export const pusher = new Pusher({
|
|
882
885
|
appId: process.env.PUSHER_APP_ID ?? "",
|
|
@@ -892,8 +895,8 @@ export async function publishExample(channel: string, event: string, data: unkno
|
|
|
892
895
|
}
|
|
893
896
|
return pusher.trigger(channel, event, data);
|
|
894
897
|
}
|
|
895
|
-
`;function
|
|
896
|
-
`))}catch{}
|
|
898
|
+
`;function yd(e){switch(e){case"inngest":return[{relPath:"workflows/inngest/example.ts",content:md}];case"n8n":return[{relPath:"workflows/n8n/README.md",content:pd},{relPath:"workflows/n8n/example.json",content:fd}];case"pusher":return[{relPath:"workflows/pusher/example.ts",content:gd}]}}async function hd(e,t={}){yn.includes(e)||(s.error(`Invalid provider: ${ud.red(e)}. Valid: ${yn.join(", ")}`),process.exit(c.INVALID_ARGS));let n=h(),r=yd(e);t.dryRun&&(A({mode:"dry-run",command:`workflow init ${e}`,files:r.map(i=>({path:gn.join(n,i.relPath)}))}),process.exit(c.DRY_RUN_OK));let o=0,a=0;for(let i of r){let l=gn.join(n,i.relPath);if(fn.existsSync(l)){s.warn(`Skipping ${i.relPath} \u2014 already exists.`),a++;continue}fn.mkdirSync(gn.dirname(l),{recursive:!0}),fn.writeFileSync(l,i.content),t.quiet||s.success(`Created ${i.relPath}`),o++}o===0&&a>0&&(s.info(`No files created \u2014 ${e} scaffold already present.`),process.exit(c.CONFLICT)),process.exit(c.SUCCESS)}var Oo=e=>{e.command("workflow").description("Manage workflow provider scaffolding (inngest | n8n | pusher)").command("init <provider>").description(`Scaffold a starter workflow file for a provider (${yn.join(" | ")})`).option("--dry-run","Preview files that would be created (exit code 10)").action(async(n,r,o)=>{let a=x(r,o);await hd(n,{dryRun:!!r.dryRun,quiet:!!a.quiet})})};var st=class extends Error{code;exitCode;suggestion;retryable;context;cause;constructor(t){super(t.message),this.name="CommandError",this.code=t.code,this.exitCode=t.exitCode??c.ERROR,this.suggestion=t.suggestion,this.retryable=t.retryable??!1,this.context=t.context,this.cause=t.cause}};function bd(e){return e instanceof st}function vd(e){return bd(e)?ot({error:e.code,message:e.message,suggestion:e.suggestion,retryable:e.retryable,exitCode:e.exitCode,context:e.context,cause:e.cause instanceof Error?e.cause:e}):e instanceof Error?ot({error:"unexpected_error",message:e.message,suggestion:"Re-run with NEBUTRA_DEBUG=1 for a stack trace.",exitCode:c.ERROR,cause:e}):ot({error:"unexpected_error",message:String(e),suggestion:"Re-run with NEBUTRA_DEBUG=1 for a stack trace.",exitCode:c.ERROR})}function hn(e){let t=vd(e);return cn(t),t.exitCode}async function bn(e){try{await e()}catch(t){process.exitCode=hn(t)}}import{existsSync as wd,mkdirSync as Sd,writeFileSync as Rd}from"fs";import{homedir as _o,platform as Cd}from"os";import{join as at}from"path";var Ao={name:"Nebutra",nameCn:"\u4E91\u6BD3\u667A\u80FD",nameFull:"\u65E0\u9521\u4E91\u6BD3\u667A\u80FD\u79D1\u6280\u6709\u9650\u516C\u53F8",nameFullEn:"Wuxi Nebutra Intelligence Technology Co., Ltd.",tagline:"Ship AI products, not boilerplate.",taglineCn:"AI\u539F\u751F\xB7\u5FEB\u901F\u51FA\u6D77\xB7\u5373\u523B\u4EA4\u4ED8",description:"Production-ready Next.js monorepo template for AI SaaS products. Auth, billing, multi-tenancy, AI services, design system, and enterprise infrastructure \u2014 pre-configured.",descriptionCn:"\u9762\u5411AI\u521B\u4E1A\u8005\u7684\u4E00\u4F53\u5316SaaS\u57FA\u7840\u8BBE\u65BD\u6A21\u677F\uFF0C\u8986\u76D6\u8BA4\u8BC1\u3001\u8BA1\u8D39\u3001\u591A\u79DF\u6237\u3001AI\u670D\u52A1\u4E0E\u8BBE\u8BA1\u7CFB\u7EDF\uFF0C\u5F00\u7BB1\u5373\u4EA7\u54C1",story:{concept:"Logo\u4EE5\u9996\u5B57\u6BCDN\u7684\u57FA\u7840\u9020\u578B\u6982\u5FF5\u4E3A\u4E3B\u8981\u8BBE\u8BA1\u6846\u67B6\uFF0C\u901A\u8FC7\u51E0\u4F55\u6B63\u8D1F\u7A7A\u95F4\u6784\u5EFA\u9690\u5F62'N'\uFF0C\u5F62\u6210\u8FD1\u4F3C\u516D\u8FB9\u5F62\u7684\u7A33\u5B9A\u7ED3\u6784",colorMeaning:"\u84DD\u7EFF\u6E10\u53D8\u4F53\u73B0\u672A\u6765\u611F\u4E0E\u79D1\u6280\u950B\u8292\uFF0C'\u4E91'\u4EE3\u8868\u4E91\u7AEF\u5E73\u53F0\uFF0C'\u6BD3'\u5BD3\u610F\u5B55\u80B2\u4E0E\u8F6C\u5316",values:["AI Native","Ship Fast","Open by Default","Global-Ready","Enterprise-Grade"],missionStatement:"Help AI founders and SaaS teams go from idea to production 10x faster by providing the infrastructure layer they shouldn't have to build."},domains:{landing:"nebutra.com",app:"app.nebutra.com",api:"api.nebutra.com",auth:"auth.nebutra.com",sso:"sso.nebutra.com",docs:"docs.nebutra.com",studio:"studio.nebutra.com",cdn:"cdn.nebutra.com",router:"router.nebutra.com",forge:"forge.nebutra.com",design:"design.nebutra.com",status:"status.nebutra.com",admin:"admin.nebutra.com",analytics:"analytics.nebutra.com",pebble:"pebble.nebutra.com",carina:"carina.nebutra.com"},social:{twitter:"https://twitter.com/nebutra",github:"https://github.com/nebutra",discord:"https://discord.gg/nebutra",linkedin:"https://linkedin.com/company/nebutra"}};import vn from"picocolors";function Ed(){if(Cd()==="win32"){let t=process.env.LOCALAPPDATA||at(_o(),"AppData","Local");return at(t,"nebutra")}let e=process.env.XDG_CONFIG_HOME;return e?at(e,"nebutra"):at(_o(),".config","nebutra")}function kd(){let e=process.env.NEBUTRA_TELEMETRY;return e==="0"||e==="false"||e==="no"}function Po(e,t){try{Sd(e,{recursive:!0}),Rd(t,"")}catch{}}function Io(){if(!process.stderr.isTTY||!process.stdin.isTTY||process.env.CI)return;let e=Ed(),t=at(e,"first-run-acked");try{if(wd(t))return}catch{return}if(kd()){Po(e,t);return}let r=[`${vn.cyan("\u2139")} ${Ao.name} collects anonymous usage analytics to improve the CLI.`,` Opt out at any time: ${vn.dim("export NEBUTRA_TELEMETRY=0")}`,` Privacy policy: ${vn.dim(`${Cn("landing")}/legal/cli-analytics`)}`,""];try{process.stderr.write(r.join(`
|
|
899
|
+
`))}catch{}Po(e,t)}var Pd=Ad(Od(wn(import.meta.url)),"..","package.json"),To=JSON.parse(xd(Pd,"utf8")).version;function Id(e){let t=new _d,n=e.isInteractive??(process.stdin.isTTY!==!1&&process.stdout.isTTY!==!1);return t.name("nebutra").description("Nebutra \u2014 governance-first CLI for topology scaffolding, registry features, and platform operations").version(e.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-essential output").option("--format <type>","Output format: json, table, plain").option("--yes","Skip all interactive prompts (Agent mode)").option("--no-interactive","Alias for --yes").option("--no-color","Disable colored output"),t.command("init").description("Initialize a Nebutra project and create nebutra.config.json").option("--dry-run","Preview changes without writing files (exits with code 10)").option("--if-not-exists","Skip initialization if nebutra.config.json already exists").action(r=>bn(async()=>{let o=r.optsWithGlobals?r.optsWithGlobals():r;await Ar({dryRun:r.dryRun||!1,yes:o.yes||!1,ifNotExists:r.ifNotExists||!1})})),t.command("add [components...]").description("Add a registry-backed platform feature or external UI component").option("--21st <id>","Fetch and install a component from 21st.dev").option("--v0 <url>","Fetch and install a component from v0.dev").option("--provider <id>","Specify a backend provider for a system feature (e.g. upstash)").option("--dry-run","Preview what would be installed without making changes (exit code 10)").option("--yes","Skip all interactive prompts and use defaults (Agent mode)").option("--if-not-exists","Skip installation if component already exists").action(async(r,o)=>{let a=o.optsWithGlobals?o.optsWithGlobals():o;await Ln(r,{...o,yes:a.yes||!n})}),lr(t),Dr(t),Vr(t),er(t),xr(t),Or(t),br(t),Ir(t),zn(t),Yn(t),Qn(t),Qr(t),dr(t),Er(t),ur(t),no(t),Oo(t),Xn(t),fr(t),io(t),bo(t),Mn(t),tr(t),kr(t),yr(t),Hr(t),qr(t),zr(t),ir(t),Lr(t),xo(t),Tr(t),So(t),t.command("doctor").description("Check your Nebutra project setup for common issues").action(()=>bn(async()=>{let{logger:r}=await import("./logger-WOLJCPZK.js"),{findMonorepoRoot:o}=await import("./delegate-7HQKV277.js"),a=await import("fs"),i=await import("path");r.info("Running project health check...");let l=!1,u=o(),m=process.version;parseInt(m.replace("v","").split(".")[0]??"0",10)<22?(r.error(`Node.js >= 22 required, found ${m}`),l=!0):r.success(`Node.js version OK (${m})`),a.existsSync(i.join(u,"nebutra.config.json"))?r.success("nebutra.config.json found"):r.warn("nebutra.config.json missing. Try running 'nebutra init'"),a.existsSync(i.join(u,"package.json"))?r.success("package.json found"):(r.error("No package.json found in root directory"),l=!0),a.existsSync(i.join(u,".env"))||a.existsSync(i.join(u,".env.local"))?r.success("Environment variables configured"):r.warn("No .env or .env.local found. Some features may not work properly.");let E=i.join(u,"apps/api-gateway");a.existsSync(E)&&r.warn("Legacy `apps/api-gateway/` present. Expected `backends/gateway/` \u2014 see CLAUDE.md for the W2.x restructure.");let D=i.join(u,"backends/gateway");a.existsSync(D)?r.success("backends/gateway/ present"):a.existsSync(i.join(u,"backends"));let F=i.join(u,"packages");if(a.existsSync(F)){let me=new Set(["design","iam","commerce","integrations","platform","ops","ai"]);try{let Ae=a.readdirSync(F,{withFileTypes:!0}),p=[];for(let B of Ae){if(!B.isDirectory()||me.has(B.name))continue;let je=i.join(F,B.name,"package.json");a.existsSync(je)&&p.push(B.name)}p.length>0?r.warn(`Found ${p.length} uncategorized package(s) under packages/: ${p.join(", ")}. Expected packages/<category>/<name>/ \u2014 see CLAUDE.md.`):r.success("Packages follow categorized layout")}catch{}}let q=i.join(u,".nebutra"),ue=i.join(q,"scaffold-meta.json");if(a.existsSync(ue)?r.success(".nebutra/scaffold-meta.json present (CLI-scaffolded project)"):a.existsSync(q)&&r.warn(".nebutra/ directory exists but scaffold-meta.json is missing. Harmless \u2014 the marker is provenance only and grants nothing."),(a.existsSync(ue)||a.existsSync(i.join(u,"nebutra.config.json")))&&(r.info(""),r.info("Golden path to a running app:"),r.info(" 1. Fill .env.local (copy keys from .env.example)"),r.info(" 2. pnpm infra:up # local Postgres/Redis if needed"),r.info(" 3. pnpm db:migrate && pnpm db:seed"),r.info(" 4. pnpm dev # http://localhost:3000")),l)throw new st({code:"doctor_failed",message:"Doctor found critical issues that require your attention.",suggestion:"Fix the errors above, then re-run `nebutra doctor`.",exitCode:c.CONFIG_ERROR});r.success("Doctor is happy. Your project looks healthy!")})),t.hook("preAction",r=>{let o=r.optsWithGlobals();(!n||o.noInteractive)&&(o.yes=!0)}),t.addHelpText("after",`
|
|
897
900
|
Examples:
|
|
898
901
|
$ nebutra init Initialize a new project
|
|
899
902
|
$ nebutra add cache --provider upstash-redis --yes Install a registry feature
|
|
@@ -938,4 +941,4 @@ Environment:
|
|
|
938
941
|
NEBUTRA_OUTPUT_FORMAT Output format (json|table|plain)
|
|
939
942
|
NO_COLOR Disable colored output
|
|
940
943
|
CI Auto-enable non-interactive mode
|
|
941
|
-
`),t}async function
|
|
944
|
+
`),t}async function Nd(){Io();let e=await ko(To),t=Id({version:To,isInteractive:process.stdin.isTTY!==!1&&process.stdout.isTTY!==!1});process.argv.length<=2&&(t.outputHelp(),process.exit(c.SUCCESS)),await t.parseAsync(process.argv),await e()}function $d(){if(!process.argv[1])return!1;try{return No(wn(import.meta.url))===No($o(process.argv[1]))}catch{return wn(import.meta.url)===$o(process.argv[1])}}var Td=$d();Td&&Nd().catch(e=>{process.exitCode=hn(e)});export{Id as buildProgram};
|