kaven-cli 0.4.1-alpha.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -215
- package/dist/EnvManager-NMS3NMIE.js +15 -0
- package/dist/MarketplaceClient-YCFH2VU4.js +1 -0
- package/dist/chunk-JHLQ46NG.js +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +215 -301
- package/dist/tier-table-DQMPQSI2.js +6 -0
- package/package.json +26 -11
- package/dist/EnvManager-GQMEZ6NV.js +0 -158
- package/dist/MarketplaceClient-IJGRQRC4.js +0 -7
- package/dist/chunk-3RG5ZIWI.js +0 -10
- package/dist/chunk-GHZX5OAA.js +0 -455
- package/dist/commands/aiox/index.js +0 -20
- package/dist/commands/auth/login.js +0 -122
- package/dist/commands/auth/logout.js +0 -23
- package/dist/commands/auth/whoami.js +0 -36
- package/dist/commands/cache/index.js +0 -43
- package/dist/commands/config/features.js +0 -161
- package/dist/commands/config/index.js +0 -95
- package/dist/commands/index.js +0 -2
- package/dist/commands/init/aiox-bootstrap.js +0 -83
- package/dist/commands/init/index.js +0 -210
- package/dist/commands/init-ci/index.js +0 -153
- package/dist/commands/license/index.js +0 -10
- package/dist/commands/license/status.js +0 -44
- package/dist/commands/license/tier-table.js +0 -46
- package/dist/commands/marketplace/browse.js +0 -186
- package/dist/commands/marketplace/install.js +0 -263
- package/dist/commands/marketplace/list.js +0 -122
- package/dist/commands/module/activate.js +0 -245
- package/dist/commands/module/add.js +0 -69
- package/dist/commands/module/doctor.js +0 -175
- package/dist/commands/module/list.js +0 -51
- package/dist/commands/module/publish.js +0 -258
- package/dist/commands/module/remove.js +0 -58
- package/dist/commands/telemetry/view.js +0 -27
- package/dist/commands/upgrade/check.js +0 -162
- package/dist/commands/upgrade/index.js +0 -185
- package/dist/core/AuthService.js +0 -222
- package/dist/core/CacheManager.js +0 -154
- package/dist/core/ConfigManager.js +0 -166
- package/dist/core/EnvManager.js +0 -196
- package/dist/core/ErrorRecovery.js +0 -192
- package/dist/core/LicenseService.js +0 -83
- package/dist/core/ManifestParser.js +0 -52
- package/dist/core/MarkerService.js +0 -62
- package/dist/core/ModuleDoctor.js +0 -451
- package/dist/core/ModuleInstaller.js +0 -169
- package/dist/core/ProjectInitializer.js +0 -183
- package/dist/core/RegistryResolver.js +0 -95
- package/dist/core/SchemaActivator.js +0 -278
- package/dist/core/ScriptRunner.js +0 -73
- package/dist/core/SignatureVerifier.js +0 -75
- package/dist/core/index.js +0 -2
- package/dist/infrastructure/Container.js +0 -37
- package/dist/infrastructure/MarketplaceClient.js +0 -425
- package/dist/infrastructure/TelemetryBuffer.js +0 -73
- package/dist/infrastructure/TransactionalFileSystem.js +0 -77
- package/dist/infrastructure/errors.js +0 -63
- package/dist/infrastructure/index.js +0 -2
- package/dist/lib/capabilities-catalog.js +0 -73
- package/dist/lib/module-registry.js +0 -47
- package/dist/lib/schema-modifier.js +0 -40
- package/dist/tier-table-LAL6PAVW.js +0 -52
- package/dist/types/auth.js +0 -2
- package/dist/types/manifest.js +0 -45
- package/dist/types/markers.js +0 -10
- package/dist/types/marketplace.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,35 +1,200 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const main = () => {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
2
|
+
import{a as Lt,b as Ot,c as Ft,d as Ge,e as je,f as Te,g as J}from"./chunk-JHLQ46NG.js";import{Command as Kr}from"commander";import b from"chalk";import{execSync as Ut}from"child_process";import Bt from"path";import qe from"fs-extra";import x from"fs-extra";import R from"path";import Zo from"os";var He=class{constructor(e,t,n){this.projectRoot=e;this.markerService=t;this.manifestParser=n}async checkAll(){let e=[];return e.push(...await this.checkAnchors()),e.push(...await this.checkMarkers()),e.push(...await this.checkDependencies()),e.push(...await this.checkSchemaMerge()),e.push(...await this.checkEnvCompleteness()),e.push(...await this.checkLicense()),e.push(...await this.checkFrameworkVersion()),e.push(...await this.checkPrismaClientSync()),e}async checkAnchors(){let e=[],t=[{file:"apps/api/src/app.ts",anchor:"// [KAVEN_MODULE_IMPORTS]"},{file:"apps/api/src/app.ts",anchor:"// [KAVEN_MODULE_HOOKS]"},{file:"apps/api/src/app.ts",anchor:"// [KAVEN_MODULE_REGISTRATION]"}];for(let{file:n,anchor:r}of t){let a=R.join(this.projectRoot,n);if(!await x.pathExists(a)){e.push({type:"anchor",severity:"warning",message:`File not found: ${n}`,file:n,fixable:!1});continue}(await x.readFile(a,"utf-8")).includes(r)||e.push({type:"anchor",severity:"error",message:`Missing anchor: ${r}`,file:n,fixable:!1})}return e}async checkMarkers(){let e=[],n=(await this.readKavenConfig()).modules.filter(r=>r.installed);for(let r of n){let a=R.join(this.projectRoot,".kaven/modules",r.name,"module.json");if(!await x.pathExists(a)){e.push({type:"marker",severity:"error",message:`Manifest not found for installed module: ${r.name}`,fixable:!1});continue}try{let i=await this.manifestParser.parse(a);for(let s of i.injections){let c=R.join(this.projectRoot,s.file);if(!await x.pathExists(c)){e.push({type:"marker",severity:"error",message:`Injection target not found: ${s.file}`,file:s.file,fixable:!1});continue}let l=await x.readFile(c,"utf-8"),d=s.moduleName||r.name;this.markerService.detectMarkers(l,d).found||e.push({type:"marker",severity:"error",message:`Module ${r.name} not injected in ${s.file}`,file:s.file,fixable:!0})}}catch(i){e.push({type:"marker",severity:"error",message:`Invalid manifest for module ${r.name}: ${i instanceof Error?i.message:String(i)}`,fixable:!1})}}return e}async checkDependencies(){let e=[],n=(await this.readKavenConfig()).modules.filter(i=>i.installed),r=R.join(this.projectRoot,"package.json");if(!await x.pathExists(r))return e.push({type:"dependency",severity:"error",message:"package.json not found",fixable:!1}),e;let a=await x.readJSON(r);for(let i of n){let s=R.join(this.projectRoot,".kaven/modules",i.name,"module.json");if(await x.pathExists(s))try{let c=await this.manifestParser.parse(s);for(let l of c.dependencies.npm){let[d]=l.split("@"),p=a.dependencies?.[d],u=a.devDependencies?.[d];!p&&!u&&e.push({type:"dependency",severity:"warning",message:`Missing npm dependency: ${l}`,fixable:!0})}}catch{}}return e}async checkSchemaMerge(){let e=[],t=R.join(this.projectRoot,"packages/database/prisma/schema.base.prisma");if(!await x.pathExists(t))return e.push({type:"dependency",severity:"warning",message:"Prisma base schema not found: packages/database/prisma/schema.base.prisma",file:"packages/database/prisma/schema.base.prisma",fixable:!1}),e;let n=R.dirname(t);try{let r=await x.readdir(n);for(let a of r){if(!a.endsWith(".prisma"))continue;let i=R.join(n,a);(await x.readFile(i,"utf-8")).includes("<<<<<<<")&&e.push({type:"marker",severity:"error",message:`Merge conflict detected in schema file: ${a}`,file:R.join("packages/database/prisma",a),fixable:!1})}}catch{}return e.length===0&&e.push({type:"dependency",severity:"info",message:"Prisma schema integrity OK",fixable:!1}),e}async checkEnvCompleteness(){let e=[],t=R.join(this.projectRoot,".env.example"),n=R.join(this.projectRoot,".env");if(!await x.pathExists(t))return e.push({type:"dependency",severity:"info",message:".env.example not found \u2014 skipping env completeness check",fixable:!1}),e;if(!await x.pathExists(n))return e.push({type:"dependency",severity:"warning",message:".env file not found. Copy .env.example to .env and fill in values",file:".env",fixable:!1}),e;let r=await x.readFile(t,"utf-8"),a=await x.readFile(n,"utf-8"),i=d=>{let p=new Set;for(let u of d.split(`
|
|
3
|
+
`)){let m=u.trim();if(m.startsWith("#")||!m.includes("="))continue;let g=m.split("=")[0].trim();g&&p.add(g)}return p},s=i(r),c=i(a),l=[];for(let d of s)c.has(d)||l.push(d);return l.length>0?e.push({type:"dependency",severity:"warning",message:`Missing env vars in .env: ${l.join(", ")}`,file:".env",fixable:!0}):e.push({type:"dependency",severity:"info",message:"Env vars completeness OK",fixable:!1}),e}async checkLicense(){let e=[],t=R.join(Zo.homedir(),".kaven","license.json");if(!await x.pathExists(t))return e.push({type:"dependency",severity:"warning",message:"No license found at ~/.kaven/license.json. Run 'kaven license status' to set up.",fixable:!1}),e;try{let n=await x.readJson(t);if(n.expiresAt){let r=new Date(n.expiresAt).getTime();if(Date.now()>r)return e.push({type:"dependency",severity:"error",message:`License expired on ${n.expiresAt}. Run 'kaven upgrade' to renew.`,fixable:!1}),e}e.push({type:"dependency",severity:"info",message:`License valid (tier: ${n.tier||"unknown"})`,fixable:!1})}catch{e.push({type:"dependency",severity:"warning",message:"Could not read license file. Try 'kaven license status'.",fixable:!1})}return e}async checkFrameworkVersion(){let e=[],t=R.join(this.projectRoot,"package.json");if(!await x.pathExists(t))return e.push({type:"dependency",severity:"info",message:"package.json not found \u2014 skipping framework version check",fixable:!1}),e;try{let n=await x.readJSON(t),r=n.dependencies?.["@kaven/core"]||n.devDependencies?.["@kaven/core"];if(!r)return e.push({type:"dependency",severity:"info",message:"@kaven/core not found in dependencies \u2014 not a Kaven framework project",fixable:!1}),e;let a="1.0.0",s=r.replace(/[\^~>=<]/,"").split(" ")[0].split(".").map(Number),c=a.split(".").map(Number),l=!0;for(let d=0;d<3&&!((s[d]||0)>(c[d]||0));d++)if((s[d]||0)<(c[d]||0)){l=!1;break}l?e.push({type:"dependency",severity:"info",message:`Framework version OK (${r})`,fixable:!1}):e.push({type:"dependency",severity:"warning",message:`@kaven/core version ${r} may be outdated. Minimum: ^${a}`,fixable:!1})}catch{e.push({type:"dependency",severity:"info",message:"Could not determine framework version",fixable:!1})}return e}async checkPrismaClientSync(){let e=[],t=R.join(this.projectRoot,"node_modules/@prisma/client"),n=R.join(this.projectRoot,"prisma/schema.prisma");if(!await x.pathExists(t))return e.push({type:"dependency",severity:"warning",message:"@prisma/client not found. Run 'npx prisma generate' to generate the client.",fixable:!0}),e;if(!await x.pathExists(n))return e.push({type:"dependency",severity:"info",message:"prisma/schema.prisma not found \u2014 skipping Prisma sync check",fixable:!1}),e;try{let r=await x.stat(n),a=await x.stat(t);r.mtime>a.mtime?e.push({type:"dependency",severity:"warning",message:"Prisma schema was modified after client generation. Run 'npx prisma generate'.",fixable:!0}):e.push({type:"dependency",severity:"info",message:"Prisma client is up to date",fixable:!1})}catch{e.push({type:"dependency",severity:"info",message:"Could not compare Prisma schema and client timestamps",fixable:!1})}return e}async readKavenConfig(){let e=R.join(this.projectRoot,"kaven.json");if(!await x.pathExists(e))return{modules:[]};try{return await x.readJSON(e)}catch{return{modules:[]}}}};function Ie(o){return{moduleName:o,beginMarker:`// [KAVEN_MODULE:${o} BEGIN]`,endMarker:`// [KAVEN_MODULE:${o} END]`}}var W=class{hasModule(e,t){let n=Ie(t);return e.includes(n.beginMarker)&&e.includes(n.endMarker)}detectMarkers(e,t){let n=Ie(t),r=e.split(`
|
|
4
|
+
`),a,i;for(let s=0;s<r.length;s++)if(r[s].includes(n.beginMarker)&&(a=s),r[s].includes(n.endMarker)){i=s;break}if(a!==void 0&&i!==void 0){let s=r.slice(a+1,i).join(`
|
|
5
|
+
`);return{found:!0,beginLine:a,endLine:i,content:s}}return{found:!1}}injectModule(e,t,n,r){if(this.hasModule(e,n))throw new Error(`Module ${n} already injected`);if(!e.includes(t))throw new Error(`Anchor not found: ${t}`);let a=Ie(n),i=`
|
|
6
|
+
${a.beginMarker}
|
|
7
|
+
${r}
|
|
8
|
+
${a.endMarker}
|
|
9
|
+
`;return e.replace(t,`${t}${i}`)}removeModule(e,t){let n=Ie(t),r=this.escapeRegex(n.beginMarker),a=this.escapeRegex(n.endMarker),i=new RegExp(`\\n?${r}[\\s\\S]*?${a}\\n?`,"g"),s=e.replace(i,"");if(s===e)throw new Error(`Module ${t} not found in file`);return s}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}};import Nt from"fs-extra";import{z as v}from"zod";var Qo=v.object({npm:v.array(v.string()).default([]),peerModules:v.array(v.string()).default([]),kavenVersion:v.string().default(">=0.1.0")}),it=v.object({source:v.string(),dest:v.string()}),en=v.object({backend:v.array(it).default([]),frontend:v.array(it).default([]),database:v.array(it).default([])}),tn=v.object({file:v.string(),anchor:v.string(),code:v.string(),moduleName:v.string().optional()}),on=v.object({postInstall:v.string().nullable().default(null),preRemove:v.string().nullable().default(null)}),nn=v.object({key:v.string(),required:v.boolean().default(!1),example:v.string().optional()}),Kt=v.object({name:v.string().min(1),version:v.string().regex(/^\d+\.\d+\.\d+$/),description:v.string().optional(),author:v.string().default("Kaven"),license:v.string().default("Proprietary"),dependencies:Qo,files:en,injections:v.array(tn),scripts:on,env:v.array(nn).default([])});import{ZodError as rn}from"zod";var ye=class{async parse(e){if(!await Nt.pathExists(e))throw new Error(`Manifest not found: ${e}`);let t=await Nt.readFile(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error(`Failed to parse manifest JSON: ${e}`)}try{return Kt.parse(n)}catch(r){throw r instanceof rn?new Error(`Invalid manifest:
|
|
10
|
+
${this.formatZodError(r)}`):r}}async validate(e){try{return await this.parse(e),{valid:!0,errors:[]}}catch(t){return{valid:!1,errors:[t instanceof Error?t.message:String(t)]}}}formatZodError(e){return e.issues.map(t=>` - ${t.path.map(String).join(".")}: ${t.message}`).join(`
|
|
11
|
+
`)}};function an(o){switch(o){case"error":return b.red("[ERROR]");case"warning":return b.yellow("[WARN] ");case"info":return b.cyan("[INFO] ");default:return b.green("[OK] ")}}async function sn(o,e){let t=o.filter(n=>n.fixable);if(t.length===0){console.log(b.gray(" No automatically fixable issues found."));return}for(let n of t){let r=n.message.toLowerCase();if(r.includes("missing npm dependency")||r.includes("pnpm install")){console.log(b.blue(` Fixing: ${n.message}`));try{Ut("pnpm install",{cwd:e,stdio:"inherit"}),console.log(b.green(" \u2713 pnpm install completed"))}catch{console.log(b.red(" \u2717 pnpm install failed"))}continue}if(r.includes("prisma")){console.log(b.blue(` Fixing: ${n.message}`));try{Ut("npx prisma generate",{cwd:e,stdio:"inherit"}),console.log(b.green(" \u2713 npx prisma generate completed"))}catch{console.log(b.red(" \u2717 npx prisma generate failed"))}continue}if(r.includes("missing env vars")&&n.file===".env"){let a=Bt.join(e,".env"),i=Bt.join(e,".env.example");console.log(b.blue(` Fixing: ${n.message}`));try{let s=await qe.readFile(i,"utf-8"),c=await qe.pathExists(a)?await qe.readFile(a,"utf-8"):"",l=m=>{let g=new Set;for(let k of m.split(`
|
|
12
|
+
`)){let F=k.trim();if(F.startsWith("#")||!F.includes("="))continue;let I=F.split("=")[0].trim();I&&g.add(I)}return g},d=l(s),p=l(c),u=`
|
|
13
|
+
# Added by kaven doctor --fix
|
|
14
|
+
`;for(let m of d)p.has(m)||(u+=`${m}=PLACEHOLDER
|
|
15
|
+
`);await qe.appendFile(a,u),console.log(b.green(" \u2713 Placeholder env vars appended to .env"))}catch{console.log(b.red(" \u2717 Could not append env vars"))}continue}console.log(b.yellow(` Manual action required: ${n.message}`))}}async function Vt(o){o.json||console.log(b.blue(`Running module doctor...
|
|
16
|
+
`));let e=new W,t=new ye,n=new He(process.cwd(),e,t),r=[];try{r=await n.checkAll()}catch(s){o.json?console.log(JSON.stringify({success:!1,error:s instanceof Error?s.message:String(s),results:[]})):console.error(b.red(`[ERROR] Heavy failure during doctor audit: ${s instanceof Error?s.message:String(s)}`)),process.exit(1);return}if(o.json){let s=r.filter(l=>l.severity==="error"),c=r.filter(l=>l.severity==="warning");console.log(JSON.stringify({success:s.length===0,errors:s.length,warnings:c.length,results:r},null,2)),process.exit(s.length>0?1:c.length>0?2:0);return}for(let s of r){let c=an(s.severity);console.log(`${c} ${s.message}`),s.file&&console.log(b.gray(` file: ${s.file}`)),s.fixable&&!o.fix&&console.log(b.gray(" (fixable: run with --fix)"))}let a=r.filter(s=>s.severity==="error"),i=r.filter(s=>s.severity==="warning");console.log(),a.length===0&&i.length===0?console.log(b.green("[OK] All checks passed! Your project is healthy.")):(a.length>0&&console.log(b.red(`[ERROR] Found ${a.length} error(s)`)),i.length>0&&console.log(b.yellow(`[WARN] Found ${i.length} warning(s)`)),o.fix||(console.log(b.gray(`
|
|
17
|
+
Tip: Run with --fix to attempt automatic repairs`)),console.log(b.gray("Try: kaven module doctor --fix")))),o.fix&&(console.log(),console.log(b.blue(`Applying auto-fixes...
|
|
18
|
+
`)),await sn(r,process.cwd()),console.log(b.green(`
|
|
19
|
+
Auto-fix completed.`))),a.length>0&&process.exit(1),i.length>0&&process.exit(2)}import Gt from"chalk";import pn from"ora";import De from"path";import ve from"fs-extra";import G from"fs-extra";import H from"path";import{glob as cn}from"glob";var Re=class{constructor(e,t=".agent/backups"){this.projectRoot=e;this.backupDir=H.join(e,t),this.backupId=`backup_${Date.now()}`}backupDir;backupId;filesToBackup=[];async backup(e){let t=H.join(this.backupDir,this.backupId);await G.ensureDir(t);for(let n of e){let r=H.resolve(this.projectRoot,n);if(!await G.pathExists(r))throw new Error(`File not found for backup: ${n}`);let a=H.relative(this.projectRoot,r),i=H.join(t,a);await G.ensureDir(H.dirname(i)),await G.copy(r,i),this.filesToBackup.push(r)}console.log(`\u{1F4E6} Backup created: ${this.backupId}`)}async rollback(){let e=H.join(this.backupDir,this.backupId);if(!await G.pathExists(e))throw new Error(`Backup not found: ${this.backupId}`);let t=await cn(`${e}/**/*`,{nodir:!0});for(let n of t){let r=H.relative(e,n),a=H.join(this.projectRoot,r);await G.ensureDir(H.dirname(a)),await G.copy(n,a,{overwrite:!0})}console.log(`\u267B\uFE0F Rollback complete: ${this.backupId}`)}async commit(){let e=H.join(this.backupDir,this.backupId);await G.pathExists(e)&&await G.remove(e),console.log("\u2705 Transaction committed")}getBackupId(){return this.backupId}async cleanup(){if(!await G.pathExists(this.backupDir))return;let e=await G.readdir(this.backupDir),t=Date.now(),n=10080*60*1e3;for(let r of e){let a=r.match(/backup_(\d+)/);if(a){let i=parseInt(a[1]);t-i>n&&await G.remove(H.join(this.backupDir,r))}}}};import ln from"child_process";import dn from"readline";import ze from"chalk";var _e=class{timeoutMs;constructor(e=6e4){this.timeoutMs=e}async runScript(e,t,n=!1){if(!n&&!await this.confirm(`Run ${t} script: ${e.command} ${(e.args??[]).join(" ")}?`)){console.log(ze.dim(` Skipping ${t} script.`));return}return new Promise((r,a)=>{let i=ln.spawn(e.command,e.args??[],{cwd:e.cwd,stdio:["ignore","pipe","pipe"],shell:!0}),s=ze.dim(`[${t}] `);i.stdout?.on("data",l=>{process.stdout.write(s+l.toString())}),i.stderr?.on("data",l=>{process.stderr.write(s+ze.yellow(l.toString()))});let c=setTimeout(()=>{console.warn(ze.yellow(`
|
|
20
|
+
\u26A0 ${t} script timed out after ${this.timeoutMs/1e3}s, sending SIGTERM...`)),i.kill("SIGTERM"),setTimeout(()=>{i.kill("SIGKILL")},5e3)},this.timeoutMs);i.on("close",l=>{clearTimeout(c),l===0||l===null?r():a(new Error(`${t} script exited with code ${l}`))}),i.on("error",l=>{clearTimeout(c),a(l)})})}async runScripts(e,t,n=!1){for(let r of e)await this.runScript(r,t,n)}confirm(e){return new Promise(t=>{let n=dn.createInterface({input:process.stdin,output:process.stdout});n.question(`
|
|
21
|
+
${e} [y/N] `,r=>{n.close(),t(r.toLowerCase()==="y"||r.toLowerCase()==="yes")})})}};import we from"fs-extra";import st from"path";import ct from"chalk";var ae=class{constructor(e,t){this.projectRoot=e;this.markerService=t}async isModuleInstalled(e){try{let t=await this.findProjectFiles();for(let n of t)try{let r=await we.readFile(n,"utf-8");if(this.markerService.hasModule(r,e))return!0}catch{}return!1}catch{return!1}}async findProjectFiles(){let{glob:e}=await import("glob"),t=["**/*.ts","**/*.tsx","**/*.js","**/*.jsx"],n=["**/node_modules/**","**/.next/**","**/dist/**","**/build/**"],r=[];for(let a of t){let i=await e(a,{cwd:this.projectRoot,absolute:!0,ignore:n});r.push(...i)}return[...new Set(r)]}async install(e,t){let n=new Re(this.projectRoot);try{let r=Array.from(new Set(e.injections.map(i=>i.file)));await n.backup(r);for(let i of e.injections)await this.injectCode(i);await n.commit();let a=await this.readManifest(this.projectRoot);if(a?.scripts?.postInstall?.length){let i=new _e;try{await i.runScripts(a.scripts.postInstall.map(s=>({...s,cwd:this.projectRoot})),"postInstall",!1)}catch(s){let c=s instanceof Error?s.message:String(s);console.warn(ct.yellow(`
|
|
22
|
+
\u26A0 PostInstall script failed: ${c}`)),console.warn(ct.dim(" The module is installed. Run the script manually if needed."))}}if(!t?.skipEnv&&a?.env?.length){let{EnvManager:i}=await import("./EnvManager-NMS3NMIE.js"),s=new i,c=a.env.map(l=>({name:l.key,description:l.example??l.key,required:l.required??!1}));await s.injectEnvVars(e.name,c,{projectDir:this.projectRoot,envFile:t?.envFile,skipEnv:t?.skipEnv,skipConfirmation:t?.yes})}}catch(r){let a=r instanceof Error?r.message:String(r);throw console.error(`\u274C Installation failed: ${a}`),console.log("\u{1F504} Rolling back..."),await n.rollback(),r}}async uninstall(e,t){let n=new Re(this.projectRoot);try{let r=Array.from(new Set(e.injections.map(c=>c.file)));await n.backup(r);let{EnvManager:a}=await import("./EnvManager-NMS3NMIE.js");new a().removeEnvVars(e.name,{projectDir:this.projectRoot,skipEnv:t?.skipEnv});let s=await this.readManifest(this.projectRoot);if(s?.scripts?.preRemove?.length){let c=new _e;try{await c.runScripts(s.scripts.preRemove.map(l=>({...l,cwd:this.projectRoot})),"preRemove",!1)}catch(l){let d=l instanceof Error?l.message:String(l);console.warn(ct.yellow(`
|
|
23
|
+
\u26A0 PreRemove script failed: ${d}`))}}for(let c of r)await this.removeCode(c,e.name);await n.commit()}catch(r){let a=r instanceof Error?r.message:String(r);throw console.error(`\u274C Removal failed: ${a}`),console.log("\u{1F504} Rolling back..."),await n.rollback(),r}}async injectCode(e){let t=st.join(this.projectRoot,e.file),n=await we.readFile(t,"utf-8"),r=this.markerService.injectModule(n,e.anchor,e.moduleName||"unnamed",e.code);await we.writeFile(t,r)}async removeCode(e,t){let n=st.join(this.projectRoot,e),r=await we.readFile(n,"utf-8"),a=this.markerService.removeModule(r,t);await we.writeFile(n,a)}async readManifest(e){try{let t=await we.readFile(st.join(e,"module.json"),"utf-8");return JSON.parse(t)}catch{return null}}};import We from"fs-extra";import Jt from"path";import un from"os";var j=class o{static instance;logPath;buffer=[];constructor(){this.logPath=Jt.join(un.homedir(),".kaven","telemetry.log")}static getInstance(){return o.instance||(o.instance=new o),o.instance}capture(e,t,n){let r={event:e,timestamp:new Date().toISOString(),metadata:t,duration:n};this.buffer.push(r)}async flush(){if(this.buffer.length!==0)try{let e=Jt.dirname(this.logPath);await We.ensureDir(e);let t=this.buffer.map(n=>JSON.stringify(n)).join(`
|
|
24
|
+
`)+`
|
|
25
|
+
`;await We.appendFile(this.logPath,t,"utf8"),this.buffer=[]}catch(e){console.debug("Erro ao gravar telemetria:",e)}}async getRecentEvents(e=20){if(!await We.pathExists(this.logPath))return[];try{return(await We.readFile(this.logPath,"utf8")).trim().split(`
|
|
26
|
+
`).reverse().slice(0,e).map(n=>JSON.parse(n))}catch{return[]}}};async function Ht(o,e){let t=j.getInstance(),n=Date.now();t.capture("cli.module.add.start",{manifestPath:o});let r=e||process.cwd(),a=pn("Preparando instala\xE7\xE3o do m\xF3dulo...").start();try{let i=new W,s=new ye,c=new ae(r,i),l=De.isAbsolute(o)?o:De.join(r,o);if(!await ve.pathExists(l))throw new Error(`Arquivo de manifest n\xE3o encontrado: ${o}`);a.text="Validando manifest...";let d=await s.parse(l);a.text=`Instalando ${d.name}@${d.version}...`,await c.install(d),a.text="Atualizando configura\xE7\xE3o do projeto...",await mn(r,d.name,d.version),a.text="Salvando cache do manifest...";let p=De.join(r,".kaven","modules",d.name);await ve.ensureDir(p),await ve.writeJson(De.join(p,"module.json"),d,{spaces:2}),a.succeed(Gt.green(`M\xF3dulo ${d.name} instalado com sucesso!`)),t.capture("cli.module.add.success",{name:d.name},Date.now()-n),await t.flush()}catch(i){t.capture("cli.module.add.error",{error:i.message},Date.now()-n),await t.flush(),a.fail(Gt.red(`Falha na instala\xE7\xE3o: ${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}async function mn(o,e,t){let n=De.join(o,"kaven.json"),r={modules:{}};await ve.pathExists(n)&&(r=await ve.readJson(n)),r.modules||(r.modules={}),r.modules[e]=t,await ve.writeJson(n,r,{spaces:2})}import lt from"chalk";import dt from"ora";import ut from"path";import ke from"fs-extra";async function qt(o,e){let t=j.getInstance(),n=Date.now();t.capture("cli.module.remove.start",{moduleName:o});let r=e||process.cwd(),a=dt(`Removendo m\xF3dulo ${o}...`).start();try{let i=new W,s=new ae(r,i),c=ut.join(r,"kaven.json");if(!await ke.pathExists(c))throw new Error("Arquivo kaven.json n\xE3o encontrado. Este \xE9 um projeto Kaven?");let l=await ke.readJson(c);if(!l.modules||!l.modules[o])throw new Error(`O m\xF3dulo ${o} n\xE3o est\xE1 instalado.`);let d=ut.join(r,".kaven","modules",o,"module.json");if(!await ke.pathExists(d))throw new Error(`Cache do manifest para ${o} n\xE3o encontrado em ${d}. A remo\xE7\xE3o precisa do manifest original.`);let p=await ke.readJson(d);a.text=`Removendo inje\xE7\xF5es de ${o}...`,await s.uninstall(p),a.text="Atualizando configura\xE7\xE3o do projeto...",delete l.modules[o],await ke.writeJson(c,l,{spaces:2}),await ke.remove(ut.dirname(d)),dt().succeed(lt.green(`M\xF3dulo ${o} removido com sucesso!`)),t.capture("cli.module.remove.success",{moduleName:o},Date.now()-n),await t.flush()}catch(i){t.capture("cli.module.remove.error",{error:i.message},Date.now()-n),await t.flush(),dt().fail(lt.red(`Falha ao remover m\xF3dulo ${o}:`)),a.fail(lt.red(`${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}import C from"chalk";import be from"ora";import Xe from"path";import P from"fs-extra";import Oe from"crypto";import Wt from"os";import{z as ie}from"zod";import q from"fs-extra";import pt from"path";import gn from"os";function zt(o){try{let e=o.split(".");if(e.length!==3)return null;let t=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=t+"=".repeat((4-t.length%4)%4),r=Buffer.from(n,"base64").toString("utf8");return JSON.parse(r)}catch{return null}}function fn(o){let e=Date.now(),t=new Date(o).getTime(),n=Math.max(0,Math.floor((t-e)/1e3));if(n===0)return"expired";let r=Math.floor(n/3600),a=Math.floor(n%3600/60);return r>0?`expires in ${r}h ${a}m`:`expires in ${a}m`}var T=class{configPath;constructor(){this.configPath=pt.join(gn.homedir(),".kaven","auth.json")}async saveTokens(e){let t=pt.dirname(this.configPath);await q.ensureDir(t),await q.writeJson(this.configPath,e,{spaces:2}),process.platform!=="win32"&&await q.chmod(this.configPath,384)}async storeToken(e){let t=pt.dirname(this.configPath);await q.ensureDir(t),await q.writeJson(this.configPath,{token:e},{spaces:2}),process.platform!=="win32"&&await q.chmod(this.configPath,384)}async getAuth(){if(!await q.pathExists(this.configPath))return null;try{let e=await q.readJson(this.configPath);return e.access_token?e:null}catch{return null}}async getToken(){if(!await q.pathExists(this.configPath))return null;try{let e=await q.readJson(this.configPath);return e.access_token?e.access_token:e.token||null}catch{return null}}async getValidToken(){let e=await this.getAuth();if(!e)throw new Error("Not authenticated. Run 'kaven auth login' to authenticate.");let t=new Date(e.expires_at).getTime(),n=Date.now(),r=300*1e3,a=t-n<r,i=n>=t;if(!a)return e.access_token;try{let{MarketplaceClient:s}=await import("./MarketplaceClient-YCFH2VU4.js"),l=await new s(this).refreshToken(e.refresh_token),d={access_token:l.access_token,refresh_token:l.refresh_token,expires_at:l.expires_at,user:e.user};return await this.saveTokens(d),l.access_token}catch{if(!i)return console.warn("[kaven] Warning: Failed to refresh token. Using existing token."),e.access_token;throw new Error("Session expired. Run 'kaven auth login' to re-authenticate.")}}async isAuthenticated(){try{return!!await this.getToken()}catch{return!1}}async logout(){await q.pathExists(this.configPath)&&await q.remove(this.configPath)}async clearToken(){return this.logout()}async getUserInfo(){let e=await this.getAuth();if(!e)return null;let t=zt(e.access_token);return t?{id:t.sub,email:t.email,name:t.githubId}:{id:e.user.githubId,email:e.user.email,name:void 0}}async getDecodedToken(){let e=await this.getAuth();return e?zt(e.access_token):null}async getWhoamiInfo(){let e=await this.getAuth();return e?{email:e.user.email,githubId:e.user.githubId,tier:e.user.tier.charAt(0).toUpperCase()+e.user.tier.slice(1),sessionExpiry:fn(e.expires_at)}:null}};var hn=ie.object({name:ie.string().min(1),slug:ie.string().min(1).regex(/^[a-z0-9-]+$/),version:ie.string().regex(/^\d+\.\d+\.\d+$/),description:ie.string().min(1),author:ie.string().optional(),license:ie.string().optional(),tier:ie.enum(["free","starter","complete","pro"])}),Le=Xe.join(Wt.homedir(),".kaven","signing-key.json");async function yn(){if(await P.pathExists(Le))try{let r=await P.readJson(Le),a=Oe.createPrivateKey({key:Buffer.from(r.privateKey,"base64"),type:"pkcs8",format:"der"}),i=Oe.createPublicKey(a);return{privateKey:a,publicKey:i}}catch{}let{privateKey:o,publicKey:e}=Oe.generateKeyPairSync("ed25519"),t=o.export({type:"pkcs8",format:"der"}),n=e.export({type:"spki",format:"der"});return await P.ensureDir(Xe.dirname(Le)),await P.writeJson(Le,{privateKey:t.toString("base64"),publicKey:n.toString("base64")},{spaces:2}),process.platform!=="win32"&&await P.chmod(Le,384),{privateKey:o,publicKey:e}}async function wn(o){let e=await P.readFile(o);return Oe.createHash("sha256").update(e).digest("hex")}async function vn(o,e){await(await import("tar")).create({gzip:!0,file:e,cwd:o,filter:n=>{let r=n.replace(/\\/g,"/"),a=["node_modules",".git","dist",".env"];for(let i of a)if(r.startsWith(i+"/")||r===i||r.endsWith(".log"))return!1;return!0}},["."])}async function Xt(o){let e=process.cwd(),t=Xe.join(e,"module.json");await P.pathExists(t)||(console.error(C.red("Error: module.json not found in current directory.")),console.error(C.gray("Try: run this command from inside a module directory")),process.exit(1));let n;try{let f=await P.readJson(t),S=hn.safeParse(f);if(!S.success){console.error(C.red("Error: Invalid module.json:"));for(let he of S.error.issues)console.error(C.red(` - ${he.path.join(".")}: ${he.message}`));process.exit(1)}n=S.data}catch(f){console.error(C.red(`Error: Failed to parse module.json: ${f instanceof Error?f.message:String(f)}`)),process.exit(1)}console.log(),console.log(C.bold(`Publishing module: ${n.name} v${n.version}`)),console.log(C.gray(`Slug: ${n.slug} | Tier: ${n.tier}`)),console.log();let r=Xe.join(Wt.tmpdir(),`kaven-${n.slug}-${n.version}.tar.gz`),a=be("Creating module package...").start();try{await vn(e,r);let f=await P.stat(r);a.succeed(`Package created (${(f.size/1024).toFixed(1)} KB)`)}catch(f){a.fail("Failed to create package"),console.error(C.red(f instanceof Error?f.message:String(f))),await P.remove(r).catch(()=>{}),process.exit(1)}let i=be("Computing SHA-256 checksum...").start(),s;try{s=await wn(r),i.succeed(`Checksum: ${s.substring(0,16)}...`)}catch{i.fail("Failed to compute checksum"),await P.remove(r).catch(()=>{}),process.exit(1);return}let c=be("Signing package...").start(),l,d;try{let{privateKey:f,publicKey:S}=await yn();l=Oe.sign(null,Buffer.from(s),f).toString("base64"),d=S.export({type:"spki",format:"der"}).toString("base64"),c.succeed(`Package signed (${l.substring(0,16)}...)`)}catch{c.fail("Failed to sign package"),await P.remove(r).catch(()=>{}),process.exit(1);return}if(o.dryRun){console.log(),console.log(C.yellow("Dry-run mode: skipping upload and release creation.")),console.log(C.green("\u2705 Package validated successfully.")),await P.remove(r).catch(()=>{});return}let p=new T;try{await p.getValidToken()}catch{console.error(C.red("Error: Not authenticated. Run 'kaven auth login' first.")),await P.remove(r).catch(()=>{}),process.exit(1);return}let u=new J(p),m=await P.stat(r),g=be("Getting upload URL...").start(),k,F;try{let f=await u.getUploadUrl(n.slug,n.version,m.size);k=f.uploadUrl,F=f.s3Key,g.succeed("Upload URL received")}catch(f){g.fail("Failed to get upload URL"),console.error(C.red(f instanceof Error?f.message:String(f))),await P.remove(r).catch(()=>{}),process.exit(1);return}let I=be(`Uploading package (${(m.size/1024).toFixed(1)} KB)...`).start();try{let f=await P.readFile(r),S=await fetch(k,{method:"PUT",headers:{"Content-Type":"application/gzip","Content-Length":String(m.size)},body:f});if(!S.ok)throw new Error(`Upload failed: ${S.status} ${S.statusText}`);I.succeed("Package uploaded successfully")}catch(f){I.fail("Upload failed"),console.error(C.red(f instanceof Error?f.message:String(f))),await P.remove(r).catch(()=>{}),process.exit(1);return}let Q=be("Creating release record...").start();try{let f=await u.createRelease({moduleSlug:n.slug,version:n.version,s3Key:F,checksum:s,signature:l,publicKey:d,changelog:o.changelog});Q.succeed(`Release created: ${n.slug}@${f.version} (ID: ${f.id})`)}catch(f){Q.fail("Failed to create release"),console.error(C.red(f instanceof Error?f.message:String(f))),await P.remove(r).catch(()=>{}),process.exit(1);return}await P.remove(r).catch(()=>{}),console.log(),console.log(C.green(`\u2705 Published ${n.name} v${n.version} to the Kaven Marketplace!`)),console.log(C.gray(`View your module at: https://marketplace.kaven.site/modules/${n.slug}`)),console.log(),console.log(C.bold("Next steps:")),console.log(C.gray(" 1. Share your module with the community")),console.log(C.gray(" 2. Monitor installation metrics")),console.log(C.gray(" 3. Update module with 'kaven module publish' when ready"))}import w from"chalk";import Yt from"ora";import xn from"path";import*as Zt from"@inquirer/prompts";import mt from"fs-extra";import kn from"path";var le=[{id:"auth",label:"Auth & Identity",description:"Gest\xE3o de usu\xE1rios, permiss\xF5es e sess\xF5es",models:["User","Role","Capability","AuthSession","AuditLog"],enums:["UserRole"],dependsOn:[]},{id:"billing",label:"Billing",description:"Faturamento, assinaturas e pagamentos",models:["Invoice","Order","Subscription","Plan","Payment","Product"],enums:[],dependsOn:["auth"]},{id:"projects",label:"Projects",description:"Gest\xE3o de projetos e tasks",models:["Project","Task"],enums:["ProjectStatus","TaskStatus","TaskPriority"],dependsOn:["auth"]},{id:"notifications",label:"Notifications",description:"Notifica\xE7\xF5es e prefer\xEAncias de usu\xE1rio",models:["Notification","UserPreference"],enums:[],dependsOn:["auth"]},{id:"marketing-tracking",label:"Marketing Tracking",description:"Observabilidade de an\xFAncios, GTM, GA4 e Meta CAPI",models:["TrackingEvent"],enums:["TrackingSource"],dependsOn:["auth"]}],Fe=o=>`// [KAVEN_MODULE:${o.toUpperCase()} BEGIN]`,Ke=o=>`// [KAVEN_MODULE:${o.toUpperCase()} END]`,bn=/^(\s*)\/\/\s*(.*)$/,xe=class{schemaPath;constructor(e){this.schemaPath=kn.join(e,"packages","database","prisma","schema.extended.prisma")}async exists(){return mt.pathExists(this.schemaPath)}get path(){return this.schemaPath}async readSchema(){return mt.readFile(this.schemaPath,"utf-8")}async writeSchema(e){await mt.writeFile(this.schemaPath,e,"utf-8")}validateMarkers(e,t){let n=Fe(t),r=Ke(t),a=e.includes(n),i=e.includes(r);if(a&&!i)throw new Error(`Marcador \xF3rf\xE3o detectado: Faltando END para o m\xF3dulo "${t}".`);if(!a&&i)throw new Error(`Marcador \xF3rf\xE3o detectado: Faltando BEGIN para o m\xF3dulo "${t}".`);if(!a&&!i)throw new Error(`O m\xF3dulo "${t}" n\xE3o possui uma se\xE7\xE3o marcada no schema.`);if(e.indexOf(n)>e.indexOf(r))throw new Error(`Marcadores invertidos para o m\xF3dulo "${t}".`)}async getModuleStatus(e){let t=await this.readSchema(),n=Fe(e.id),r=Ke(e.id),a=t.includes(n)&&t.includes(r),i=!1;if(a){let s=this.extractBlock(t,e.id);i=s!==null&&this.isBlockActive(s)}else i=e.models.some(s=>this.isModelActive(t,s));return{id:e.id,label:e.label,description:e.description,models:e.models,dependsOn:e.dependsOn,active:i,hasMarkers:a}}async activateModule(e){let t=await this.readSchema();this.validateMarkers(t,e.id);let n=this.uncommentBlock(t,e.id);await this.writeSchema(n)}async deactivateModule(e){let t=await this.readSchema();this.validateMarkers(t,e.id);let n=this.commentBlock(t,e.id);await this.writeSchema(n)}extractBlock(e,t){let n=Fe(t),r=Ke(t),a=e.split(`
|
|
27
|
+
`),i=-1,s=-1;for(let c=0;c<a.length;c++)if(a[c].includes(n)&&(i=c),a[c].includes(r)&&i!==-1){s=c;break}return i===-1||s===-1?null:a.slice(i+1,s).join(`
|
|
28
|
+
`)}isBlockActive(e){return e.split(`
|
|
29
|
+
`).some(t=>{let n=t.trim();return n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")})}isModelActive(e,t){let n=e.split(`
|
|
30
|
+
`);for(let r of n)if(r.trim().startsWith(`model ${t}`)&&!r.trimStart().startsWith("//"))return!0;return!1}commentBlock(e,t){let n=Fe(t),r=Ke(t),a=e.split(`
|
|
31
|
+
`),i=!1,s=[];for(let c of a){if(c.includes(n)){i=!0,s.push(c);continue}if(c.includes(r)){i=!1,s.push(c);continue}if(i){let l=c.trim();l.length===0||l.startsWith("//")?s.push(c):s.push(`// ${c}`)}else s.push(c)}return s.join(`
|
|
32
|
+
`)}uncommentBlock(e,t){let n=Fe(t),r=Ke(t),a=e.split(`
|
|
33
|
+
`),i=!1,s=[];for(let c of a){if(c.includes(n)){i=!0,s.push(c);continue}if(c.includes(r)){i=!1,s.push(c);continue}if(i){let l=c.match(bn);l?s.push(l[1]+l[2]):s.push(c)}else s.push(c)}return s.join(`
|
|
34
|
+
`)}};var En={confirm:Zt.confirm};function gt(o){return le.find(e=>e.id===o.toLowerCase())}function Qt(o,e){if(!o){let t=xn.join(e,"packages","database","prisma","schema.extended.prisma");console.error(w.red(`
|
|
35
|
+
Error: Schema not found at: ${t}`)),console.error(w.gray("Make sure you are in the root of a valid Kaven project.")),process.exit(1)}}async function ft(o,e,t={}){let n=j.getInstance(),r=Date.now();n.capture("cli.module.activate.start",{moduleName:o});let a=e??process.cwd(),i=new xe(a),s=Yt(`Activating module ${o}...`).start();try{let c=await i.exists();s.stop(),Qt(c,a);let l=gt(o);if(l||(console.error(w.red(`
|
|
36
|
+
Unknown module: "${o}".`)),console.error(w.gray(`Available modules: ${le.map(p=>p.id).join(", ")}`)),process.exit(1)),l.dependsOn.length>0){s.start("Checking dependencies...");let p=[];for(let m of l.dependsOn){let g=gt(m);if(!g)continue;let k=await i.getModuleStatus(g);p.push(k)}let u=p.filter(m=>!m.active);if(u.length>0)if(s.stop(),t.withDeps)for(let m of u)await ft(m.id,e,{...t,withDeps:!0});else console.error(w.red(`
|
|
37
|
+
Inactive dependencies for "${o}": ${u.map(m=>m.id).join(", ")}`)),console.error(w.gray(`Activate them first:
|
|
38
|
+
${u.map(m=>` kaven module activate ${m.id}`).join(`
|
|
39
|
+
`)}`)),console.log(w.gray(`
|
|
40
|
+
Or use --with-deps to activate them automatically.`)),process.exit(1);s.stop()}if((await i.getModuleStatus(l)).active){console.log(w.yellow(`
|
|
41
|
+
Module "${l.label}" is already active.`));return}if(!t.yes&&!await En.confirm({message:`Activate module "${l.label}"? This will uncomment ${l.models.length} model(s) in the schema.`,default:!0})){console.log(w.gray(`
|
|
42
|
+
Activation aborted.`));return}if(t.dryRun){console.log(w.bold(`
|
|
43
|
+
--- DRY RUN: Activating ${l.label} ---`)),console.log(`Models to uncomment: ${l.models.join(", ")}`),l.enums.length>0&&console.log(`Enums to uncomment: ${l.enums.join(", ")}`);return}s.start(`Uncommenting ${l.label} models in schema...`),await i.activateModule(l),s.succeed(w.green(`
|
|
44
|
+
Module ${l.label} activated. ${l.models.length} models added: ${l.models.join(", ")}`)),t.skipMigrate||console.log(w.cyan("\nNext step: Run `pnpm db:generate && pnpm db:migrate` to apply changes.")),n.capture("cli.module.activate.success",{moduleName:l.id,models:l.models.length},Date.now()-r),await n.flush()}catch(c){let l=Te(c);s.fail(w.red(`Failed to activate module: ${l.message}`)),n.capture("cli.module.activate.error",{moduleName:o,error:l.message},Date.now()-r),await n.flush(),process.exit(1)}}async function eo(o,e,t={}){let n=j.getInstance(),r=Date.now();n.capture("cli.module.deactivate.start",{moduleName:o});let a=e??process.cwd(),i=new xe(a),s=Yt(`Deactivating module ${o}...`).start();try{let c=await i.exists();s.stop(),Qt(c,a);let l=gt(o);l||(console.error(w.red(`
|
|
45
|
+
Unknown module: "${o}".`)),console.error(w.gray(`Available modules: ${le.map(u=>u.id).join(", ")}`)),process.exit(1)),s.start("Checking reverse dependencies...");let d=[];for(let u of le){if(u.id===l.id||!u.dependsOn.includes(l.id))continue;(await i.getModuleStatus(u)).active&&d.push(u.id)}if(d.length>0&&(s.stop(),console.error(w.red(`
|
|
46
|
+
Cannot deactivate "${o}": the following active modules depend on it:`)),console.error(w.gray(` ${d.join(", ")}`)),console.error(w.gray(`Deactivate them first:
|
|
47
|
+
${d.map(u=>` kaven module deactivate ${u}`).join(`
|
|
48
|
+
`)}`)),process.exit(1)),!(await i.getModuleStatus(l)).active){s.stop(),console.log(w.yellow(`
|
|
49
|
+
Module "${l.label}" is already inactive.`));return}if(t.dryRun){s.stop(),console.log(w.bold(`
|
|
50
|
+
--- DRY RUN: Deactivating ${l.label} ---`)),console.log(`Models to comment: ${l.models.join(", ")}`);return}s.start(`Commenting ${l.label} models in schema...`),await i.deactivateModule(l),s.succeed(w.green(`
|
|
51
|
+
Module ${l.label} deactivated successfully.`)),t.skipMigrate||console.log(w.cyan("\nNext step: Run `pnpm db:generate && pnpm db:migrate` to apply changes.")),n.capture("cli.module.deactivate.success",{moduleName:l.id},Date.now()-r),await n.flush()}catch(c){let l=Te(c);s.fail(w.red(`Failed to deactivate module: ${l.message}`)),n.capture("cli.module.deactivate.error",{moduleName:o,error:l.message},Date.now()-r),await n.flush(),process.exit(1)}}async function to(o){let e=o??process.cwd(),t=new xe(e),n=await t.exists(),r={module:18,status:10,models:44,deps:20},a=w.bold("Module".padEnd(r.module))+w.bold("Status".padEnd(r.status))+w.bold("Models".padEnd(r.models))+w.bold("Depends on"),i="\u2500".repeat(r.module+r.status+r.models+r.deps);if(console.log(),console.log(w.blue(`Kaven Schema Modules
|
|
52
|
+
`)),console.log(a),console.log(w.gray(i)),!n){for(let s of le){let c=s.id.padEnd(r.module),l=w.gray("unknown".padEnd(r.status)),d=s.models.join(", ").padEnd(r.models),p=s.dependsOn.length>0?s.dependsOn.join(", "):"\u2014";console.log(`${c}${l}${d}${p}`)}console.log(),console.log(w.yellow("Warning: schema.extended.prisma not found. Status cannot be determined.")),console.log(w.gray("Run this command in the root of a Kaven project to see real status."));return}for(let s of le){let c=await t.getModuleStatus(s),l=s.id.padEnd(r.module),d=c.active?"active":"inactive",p=c.active?w.green(d.padEnd(r.status)):w.gray(d.padEnd(r.status)),u=s.models.join(", ").padEnd(r.models),m=s.dependsOn.length>0?s.dependsOn.join(", "):"\u2014";console.log(`${l}${p}${u}${m}`)}console.log(),console.log(w.gray("To activate: kaven module activate <name> | To deactivate: kaven module deactivate <name>"))}import B from"chalk";import oo from"ora";import Sn from"open";function Cn(o){return new Promise(e=>setTimeout(e,o))}async function Pn(o,e,t,n,r){let a=Date.now()+t*1e3,i=[5,10,15,20],s=0,c=n;for(;Date.now()<a;){let l=Math.ceil((a-Date.now())/1e3),d=Math.floor(l/60),p=String(l%60).padStart(2,"0");r.text=`Waiting for authorization... (expires in ${d}:${p})`,await Cn(c*1e3);try{let u=await o.pollDeviceToken(e);if(u.status==="success"&&u.tokens)return u.tokens;switch(u.status){case"slow_down":c+=5;break;case"access_denied":throw new Error("Authorization denied by user. Try again with 'kaven auth login'.");case"expired_token":throw new Error("Device code expired. Run 'kaven auth login' again.");case"authorization_pending":s<i.length-1&&(s++,c=i[s]);break}}catch(u){if(u.message.includes("denied")||u.message.includes("expired"))throw u;let m=u;throw m.code==="ECONNREFUSED"||m.code==="ENOTFOUND"?new Error("Network error. Check your connection and try again."):u}}throw new Error("Device code expired. Run 'kaven auth login' again.")}async function no(){let o=j.getInstance(),e=Date.now();o.capture("cli.auth.login.start");let t=new J,n=new T;console.log(B.blue(`\u{1F510} Starting authentication flow...
|
|
53
|
+
`));let r=oo("Requesting device code from marketplace...").start();try{let{device_code:a,user_code:i,verification_uri:s,expires_in:c,interval:l}=await t.requestDeviceCode();r.stop(),console.log(B.yellow(`To complete login, follow these steps:
|
|
54
|
+
`)),console.log(B.bold(` Your verification code: ${B.cyan(i)}
|
|
55
|
+
`));try{await Sn(s),console.log(B.dim(" \u2713 Browser opened automatically"))}catch{console.log(B.yellow(" Open this URL in your browser:")),console.log(B.underline(` ${s}
|
|
56
|
+
`))}let d=oo("Waiting for authorization...").start(),p=await Pn(t,a,c,l,d);await n.saveTokens(p),d.succeed(B.green(`Logged in as ${B.bold(p.user.email)}`)),console.log(B.dim(` Tier: ${p.user.tier}`)),console.log(B.gray(`
|
|
57
|
+
Your credentials were saved securely in ~/.kaven/auth.json
|
|
58
|
+
`)),o.capture("cli.auth.login.success",{tier:p.user.tier},Date.now()-e),await o.flush()}catch(a){o.capture("cli.auth.login.error",{error:a.message},Date.now()-e),await o.flush(),r.fail(B.red("Authentication failed")),console.error(B.red(`
|
|
59
|
+
Error: ${a.message}
|
|
60
|
+
`)),process.exit(1)}}import ht from"chalk";async function ro(){let o=new T;try{if(!await o.isAuthenticated()){console.log(ht.yellow("You are not authenticated."));return}await o.logout(),console.log(ht.green("Logged out successfully."))}catch{console.error(ht.red("Error during logout.")),process.exit(1)}}import de from"chalk";async function ao(){let o=j.getInstance();o.capture("cli.auth.whoami.start");let e=new T;try{let t=await e.getWhoamiInfo();if(!t){console.log(de.yellow("You are not authenticated.")),console.log(de.gray("Use 'kaven auth login' to sign in.")),o.capture("cli.auth.whoami.not_authenticated"),await o.flush();return}o.capture("cli.auth.whoami.authenticated"),console.log(),console.log(` ${de.bold("Email:")} ${t.email}`),console.log(` ${de.bold("GitHub:")} ${t.githubId}`),console.log(` ${de.bold("Tier:")} ${t.tier}`),console.log(` ${de.bold("Session:")} ${t.sessionExpiry}`),console.log()}catch{console.error(de.red("Error checking authentication status.")),process.exit(1)}await o.flush()}import $ from"chalk";import $n from"ora";import An from"cli-table3";function Mn(o){switch(o.toLowerCase()){case"starter":return $.green(o.toLowerCase());case"complete":return $.yellow(o.toLowerCase());case"pro":return $.magenta(o.toLowerCase());case"enterprise":return $.blue(o.toLowerCase());default:return o}}async function io(o={}){let e=j.getInstance(),t=Date.now();e.capture("cli.marketplace.list.start");let n=new T,r=new J(n),a=o.page??1,i=Math.min(o.limit??20,100),s=o.sort??"newest";await n.isAuthenticated()||console.log($.yellow("Warning: Not authenticated. Only public modules will be shown. Run: kaven auth login"));let l=$n("Fetching modules from Marketplace...").start();try{let d=await r.listModules({category:o.category,page:a,pageSize:i,q:void 0});l.stop();let p=d.data,u=d.meta,m=d.total??u?.total??p.length;if(o.json){console.log(JSON.stringify(d,null,2)),e.capture("cli.marketplace.list.success",{count:p.length,json:!0},Date.now()-t),await e.flush();return}if(p.length===0){console.log($.yellow("No modules found matching your criteria.")),e.capture("cli.marketplace.list.success",{count:0},Date.now()-t),await e.flush();return}let g=new An({head:[$.white.bold("Slug"),$.white.bold("Name"),$.white.bold("Version"),$.white.bold("Tier"),$.white.bold("Installs")],style:{head:[],border:["gray"]}}),k=[...p];s==="popular"?k.sort((f,S)=>S.installCount-f.installCount):s==="name"&&k.sort((f,S)=>f.name.localeCompare(S.name));for(let f of k)g.push([$.cyan(f.slug),$.white(f.name),$.green(f.latestVersion??"\u2014"),Mn(f.requiredTier??f.tier??""),$.gray(String(f.installCount))]);console.log($.blue.bold(`
|
|
61
|
+
Available Marketplace Modules:
|
|
62
|
+
`)),console.log(g.toString());let F=Math.ceil(m/i),I=(a-1)*i+1,Q=Math.min(a*i,m);console.log($.gray(`
|
|
63
|
+
Showing ${I}-${Q} of ${m} modules (page ${a}/${F})`)),console.log($.gray("Use 'kaven marketplace install <slug>' to install a module.")),e.capture("cli.marketplace.list.success",{count:p.length,total:m},Date.now()-t),await e.flush()}catch(d){l.stop(),d instanceof Ge&&(console.error($.red("Could not reach marketplace. Check your connection.")),e.capture("cli.marketplace.list.error",{error:"network_error"},Date.now()-t),await e.flush(),process.exit(1)),e.capture("cli.marketplace.list.error",{error:d.message},Date.now()-t),await e.flush(),console.error($.red("Error fetching modules from Marketplace.")),console.error(d),process.exit(1)}}import V from"chalk";import Dn from"ora";import ee from"fs-extra";import Ee from"path";import On from"os";import*as co from"tar";import Ye from"crypto";import jn from"fs-extra";async function Tn(o){let e=await jn.readFile(o);return Ye.createHash("sha256").update(e).digest("hex")}var In=/^[0-9a-fA-F]+$/;function Rn(o){return In.test(o)&&o.length===128?Buffer.from(o,"hex"):Buffer.from(o,"base64")}function _n(o,e,t){try{let n=Ye.createPublicKey({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),r=Rn(e);return Ye.verify(null,Buffer.from(o),n,r)?!0:Ye.verify(null,Buffer.from(o+`
|
|
64
|
+
`),n,r)}catch{return!1}}async function so(o){let e=await Tn(o.filePath);if(e!==o.expectedChecksum)throw new je(`Checksum mismatch: expected ${o.expectedChecksum.substring(0,16)}..., got ${e.substring(0,16)}...`);if(!_n(o.expectedChecksum,o.signature,o.publicKeyBase64))throw new je("Ed25519 signature verification failed. The package may have been tampered with.")}var Ln={ora:Dn},Fn={x:co.x};async function Kn(){let o=Ee.join(On.tmpdir(),"kaven-install-");return ee.mkdtemp(o)}function Nn(o){return o<1024?`${o} B`:o<1024*1024?`${Math.round(o/1024)} KB`:`${(o/(1024*1024)).toFixed(1)} MB`}async function Un(o,e,t,n){let r=Ee.join(n,".kaven","cache","modules"),a=Ee.join(r,`${o}-${e}`);await ee.ensureDir(a),await ee.copy(t,a)}async function Ze(o,e={}){let t=j.getInstance(),n=Date.now();t.capture("cli.marketplace.install.start",{slug:o});let r=new T,a=new J(r),i=process.cwd(),s;try{s=await r.getValidToken()}catch{console.error(V.red("Authentication required. Run: kaven auth login")),t.capture("cli.marketplace.install.error",{slug:o,error:"not_authenticated"},Date.now()-n),await t.flush(),process.exit(1);return}let c=Ln.ora(`Preparing installation of '${o}'...`).start(),l=null;try{c.text=`Fetching module '${o}' from Marketplace...`;let d;try{d=await a.getModule(o)}catch(z){if(z instanceof Ft){c.fail(V.red(`Module '${o}' not found in Marketplace.`)),process.exit(1);return}throw z}let p=d.latestVersion??d.releases?.[0]?.version,u=e.version??p;if(!u){c.fail(V.red(`No published version found for '${o}'.`)),process.exit(1);return}let m=new W,g=new ae(i,m);if(await g.isModuleInstalled(o)&&!e.force){c.stop(),console.log(V.yellow(`Module '${o}' is already installed. Use --force to overwrite.`)),t.capture("cli.marketplace.install.skipped",{slug:o,reason:"already_installed"},Date.now()-n),await t.flush();return}c.text=`Creating download token for '${o}@${u}'...`;let F=await a.createDownloadToken(o,u);l=await Kn();let I=Ee.join(l,"module.tar.gz"),Q=Ee.join(l,"extracted");await ee.ensureDir(Q),c.text=`Downloading ${o} v${u}...`;let f=await a.resolveUrl(F.downloadUrl),S=await fetch(f);if(!S.ok)throw new Error(`Download failed: ${S.status} ${S.statusText}`);let he=S.headers.get("content-length"),Rt=he?` (${Nn(parseInt(he,10))})`:"";if(c.text=`Downloading ${o} v${u}${Rt}...`,!S.body)throw new Error("No response body received for download");let Me=ee.createWriteStream(I),qo=S.body.getReader();if(await new Promise((z,Dt)=>{(async()=>{try{let Je=!0;for(;Je;){let{done:Wo,value:Xo}=await qo.read();Wo?(Me.end(),Je=!1):Me.write(Xo)||await new Promise(Yo=>Me.once("drain",Yo))}Me.once("finish",z),Me.once("error",Dt)}catch(Je){Dt(Je)}})()}),(await ee.stat(I)).size===0)throw new Error("Downloaded file is empty");if(!e.skipVerify){c.text=`Verifying signature for ${o} v${u}...`;let z=await a.getReleaseInfo(o,u);z.checksum&&z.signature&&z.publicKey?(await so({filePath:I,expectedChecksum:z.checksum,signature:z.signature,publicKeyBase64:z.publicKey}),c.text=`Signature verified for ${o} v${u}`):c.text=`No signature data for ${o} v${u} \u2014 skipping verification`}c.text=`Extracting ${o} v${u}...`,await Fn.x({file:I,cwd:Q});let _t=Ee.join(Q,"module.json");if(!await ee.pathExists(_t))throw new Error(`module.json not found in extracted archive for '${o}'`);let zo=await ee.readJson(_t);c.text=`Caching baseline for ${o} v${u}...`,await Un(o,u,Q,i),c.text=`Installing ${o} v${u}...`,await g.install(zo),c.succeed(V.green(`Module '${o}@${u}' installed successfully.`)),console.log(V.gray("Use 'kaven module doctor' to verify the installation.")),t.capture("cli.marketplace.install.success",{slug:o,version:u},Date.now()-n),await t.flush()}catch(d){let p=Te(d);if(c.stop(),p instanceof je){console.error(V.red(`Signature verification failed for '${o}': ${p.message}`)),console.error(V.yellow("Use --skip-verify to bypass (not recommended).")),t.capture("cli.marketplace.install.error",{slug:o,error:"signature_verification_failed"},Date.now()-n),await t.flush(),process.exit(1);return}if(p instanceof Ot){console.error(V.red(`License required: '${o}' requires a '${p.requiredTier}' license.`)),console.error(V.yellow(`Run: kaven upgrade ${p.requiredTier}`)),t.capture("cli.marketplace.install.error",{slug:o,error:"license_required",tier:p.requiredTier},Date.now()-n),await t.flush(),process.exit(1);return}if(p instanceof Lt||p.message.includes("Not authenticated")){console.error(V.red("Authentication required. Run: kaven auth login")),t.capture("cli.marketplace.install.error",{slug:o,error:"auth_error"},Date.now()-n),await t.flush(),process.exit(1);return}if(p instanceof Ge){console.error(V.red("Could not reach marketplace. Check your connection.")),t.capture("cli.marketplace.install.error",{slug:o,error:"network_error"},Date.now()-n),await t.flush(),process.exit(1);return}t.capture("cli.marketplace.install.error",{slug:o,error:p.message},Date.now()-n),await t.flush(),c.fail(V.red(`Failed to install module '${o}'.`)),console.error(p),process.exit(1)}finally{l&&await ee.remove(l).catch(()=>{})}}import{select as yt,spinner as Gn,outro as Hn,isCancel as qn,cancel as zn}from"@clack/prompts";import A from"picocolors";import{createInstance as Bn}from"i18next";var Vn={common:{welcome:"Welcome to Kaven CLI",success:"Success",error:"Error",warning:"Warning",suggestion:"Suggestion",proceed:"Do you want to proceed?",cancelled:"Operation cancelled",exit:"Exit",back:"Back",cancel:"Cancel"},init:{intro:"Bootstrapping a new Kaven project",outro:"Project created successfully! Ready to build.",projectName:"What is the name of your project?",template:"Select a template",withSquad:"Include AIOX Squad (AI Agents)?",installing:"Installing dependencies..."},module:{activate:{title:"Module Activation: {{name}}",models:"Models to be added: {{count}}",envVars:"Env vars to inject: {{count}}",alreadyActive:"Module '{{name}}' is already active."},list:{header:"Kaven Schema Modules"}},doctor:{checking:"Running diagnostics...",allClear:"Your project is healthy!",issuesFound:"Found {{count}} issue(s).",fixSuggestion:"\u{1F4A1} Run 'kaven module doctor --fix' to resolve automatically."},marketplace:{browse:{loadingCategories:"Loading categories...",categoryLoadFailed:"Could not load categories \u2014 showing all modules.",browseByCategory:"Browse by category:",allModules:"All modules",loadingModules:"Loading modules...",errorLoadingModules:"Error loading modules: {{error}}",noModulesFound:"No modules found.",nextPage:"\u2192 Next page",prevPage:"\u2190 Previous page",backToCategories:"\u2191 Back to categories",whatToDo:"What would you like to do?",install:"Install {{name}}",backToList:"Back to module list",sessionEnded:"Browse session ended."}},config:{features:{catalogHeader:"Kaven Framework \u2014 Capability Catalog",capabilitiesTotal:"{{count}} capabilities total",tierPresets:"Tier presets:",tuiHeader:"\u{1F6E1}\uFE0F Kaven Feature Flag Configuration",selectTier:"Select a base tier:",customize:"Customize individual capabilities?",confirmOverwrite:"Seed file already exists. Overwrite?",seedWritten:"Seed file written to: {{path}}",runSeed:"Run pnpm prisma db seed to apply capabilities to your database.",dryRunHeader:"--- DRY RUN: Generated Content ---"}}},Jn={common:{welcome:"Bem-vindo \xE0 Kaven CLI",success:"Sucesso",error:"Erro",warning:"Aviso",suggestion:"Sugest\xE3o",proceed:"Deseja continuar?",cancelled:"Opera\xE7\xE3o cancelada",exit:"Sair",back:"Voltar",cancel:"Cancelar"},init:{intro:"Iniciando um novo projeto Kaven",outro:"Projeto criado com sucesso! Hora de construir.",projectName:"Qual o nome do seu projeto?",template:"Selecione um template",withSquad:"Incluir AIOX Squad (Agentes de IA)?",installing:"Instalando depend\xEAncias..."},module:{activate:{title:"Ativa\xE7\xE3o de M\xF3dulo: {{name}}",models:"Models a serem adicionados: {{count}}",envVars:"Vari\xE1veis de ambiente: {{count}}",alreadyActive:"O m\xF3dulo '{{name}}' j\xE1 est\xE1 ativo."},list:{header:"M\xF3dulos de Schema Kaven"}},doctor:{checking:"Executando diagn\xF3sticos...",allClear:"Seu projeto est\xE1 saud\xE1vel!",issuesFound:"Encontrados {{count}} problema(s).",fixSuggestion:"\u{1F4A1} Execute 'kaven module doctor --fix' para resolver automaticamente."},marketplace:{browse:{loadingCategories:"Carregando categorias...",categoryLoadFailed:"N\xE3o foi poss\xEDvel carregar categorias \u2014 exibindo todos os m\xF3dulos.",browseByCategory:"Navegar por categoria:",allModules:"Todos os m\xF3dulos",loadingModules:"Carregando m\xF3dulos...",errorLoadingModules:"Erro ao carregar m\xF3dulos: {{error}}",noModulesFound:"Nenhum m\xF3dulo encontrado.",nextPage:"\u2192 Pr\xF3xima p\xE1gina",prevPage:"\u2190 P\xE1gina anterior",backToCategories:"\u2191 Voltar \xE0s categorias",whatToDo:"O que deseja fazer?",install:"Instalar {{name}}",backToList:"Voltar \xE0 lista",sessionEnded:"Sess\xE3o de navega\xE7\xE3o encerrada."}},config:{features:{catalogHeader:"Kaven Framework \u2014 Cat\xE1logo de Capacidades",capabilitiesTotal:"{{count}} capacidades no total",tierPresets:"Presets de tier:",tuiHeader:"\u{1F6E1}\uFE0F Configura\xE7\xE3o de Feature Flags Kaven",selectTier:"Selecione um tier base:",customize:"Personalizar capacidades individualmente?",confirmOverwrite:"Arquivo de seed j\xE1 existe. Sobrescrever?",seedWritten:"Seed escrito em: {{path}}",runSeed:"Execute pnpm prisma db seed para aplicar as capacidades ao banco.",dryRunHeader:"--- DRY RUN: Conte\xFAdo Gerado ---"}}},X=class o{static instance;i18n=Bn();constructor(){}static async getInstance(){return o.instance||(o.instance=new o,await o.instance.init()),o.instance}async init(){let e=process.env.KAVEN_LANG||"en";await this.i18n.init({lng:e,fallbackLng:"en",resources:{en:{translation:Vn},"pt-BR":{translation:Jn}}})}t(e,t){return this.i18n.t(e,t)}async setLanguage(e){await this.i18n.changeLanguage(e)}getI18n(){return this.i18n}};var lo=10;function uo(o){switch(o.toUpperCase()){case"FREE":return A.dim("[FREE]");case"STARTER":return A.green("[STARTER]");case"COMPLETE":return A.yellow("[COMPLETE]");case"PRO":return A.magenta("[PRO]");case"ENTERPRISE":return A.cyan("[ENTERPRISE]");default:return A.dim(`[${o}]`)}}function wt(o){qn(o)&&(zn("Cancelled."),process.exit(0))}async function po(){let o=await X.getInstance(),e=new T,t=new J(e),n=Gn(),r={category:null,page:1,selectedModule:null,screen:"categories"};for(;r.screen!=="exit";){if(r.screen==="categories"){n.start(o.t("marketplace.browse.loadingCategories"));let a=[];try{a=await t.getCategories(),n.stop()}catch{n.stop(A.yellow(o.t("marketplace.browse.categoryLoadFailed")))}let i=[{label:o.t("marketplace.browse.allModules"),value:"__all__"},...a.map(c=>({label:c,value:c})),{label:A.dim(o.t("common.exit")),value:"__exit__"}],s=await yt({message:o.t("marketplace.browse.browseByCategory"),options:i});if(wt(s),s==="__exit__"){r.screen="exit";break}r.category=s==="__all__"?null:s,r.page=1,r.screen="list";continue}if(r.screen==="list"){n.start(o.t("marketplace.browse.loadingModules"));let a=[],i=1;try{let u=await t.listModules({category:r.category||void 0,page:r.page,pageSize:lo});a=u.data,i=Math.ceil(u.total/lo)||1,n.stop()}catch(u){n.stop(A.red(o.t("marketplace.browse.errorLoadingModules",{error:u instanceof Error?u.message:String(u)}))),r.screen="categories";continue}if(a.length===0){console.log(A.yellow(o.t("marketplace.browse.noModulesFound"))),r.screen="categories";continue}let s=r.category?` [${r.category}]`:"",c=i>1?` (${r.page}/${i})`:"",l=[...a.map(u=>({label:`${u.name} ${uo(u.requiredTier??u.tier??"")}`,hint:u.description,value:u.slug})),...r.page<i?[{label:A.cyan(o.t("marketplace.browse.nextPage")),value:"__next__"}]:[],...r.page>1?[{label:A.cyan(o.t("marketplace.browse.prevPage")),value:"__prev__"}]:[],{label:A.dim(o.t("marketplace.browse.backToCategories")),value:"__back__"},{label:A.dim(o.t("common.exit")),value:"__exit__"}],d=await yt({message:`Modules${s}${c}:`,options:l});if(wt(d),d==="__exit__"){r.screen="exit";break}if(d==="__back__"){r.screen="categories";continue}if(d==="__next__"){r.page++;continue}if(d==="__prev__"){r.page=Math.max(1,r.page-1);continue}let p=a.find(u=>u.slug===d);p&&(r.selectedModule=p,r.screen="detail");continue}if(r.screen==="detail"&&r.selectedModule){let a=r.selectedModule;console.log(),console.log(A.bold(a.name),uo(a.requiredTier??a.tier??"")),console.log(A.dim(`Version: ${a.latestVersion||"latest"}`)),a.installCount!==void 0&&console.log(A.dim(`Installs: ${a.installCount.toLocaleString()}`)),a.description&&(console.log(),console.log(a.description)),console.log();let i=await yt({message:o.t("marketplace.browse.whatToDo"),options:[{label:o.t("marketplace.browse.install",{name:a.name}),value:"install"},{label:A.dim(o.t("marketplace.browse.backToList")),value:"back"},{label:A.dim(o.t("common.exit")),value:"exit"}]});if(wt(i),i==="exit"){r.screen="exit";break}if(i==="back"){r.selectedModule=null,r.screen="list";continue}if(i==="install"){console.log(),await Ze(a.slug,{force:!1,skipEnv:!1}),r.screen="exit";break}}}Hn(A.dim(o.t("marketplace.browse.sessionEnded")))}import te from"chalk";async function mo(o=10){let t=await j.getInstance().getRecentEvents(o);if(t.length===0){console.log(te.yellow(`
|
|
65
|
+
Nenhum evento de telemetria encontrado localmente.
|
|
66
|
+
`));return}console.log(te.blue.bold(`
|
|
67
|
+
\u{1F4CA} \xDAltimos ${t.length} eventos de telemetria:
|
|
68
|
+
`)),t.forEach(n=>{let r=te.gray(`[${new Date(n.timestamp).toLocaleTimeString()}]`),a=n.event.includes("error")?te.red("\u2716"):te.green("\u2714"),i=n.duration?te.yellow(` (${n.duration}ms)`):"";console.log(`${r} ${a} ${te.cyan(n.event)}${i}`),n.metadata&&Object.keys(n.metadata).length>0&&console.log(te.gray(` > ${JSON.stringify(n.metadata)}`))}),console.log(te.gray(`
|
|
69
|
+
Log local: ~/.kaven/telemetry.log
|
|
70
|
+
`))}import{Command as Yn}from"commander";import{Command as Xn}from"commander";import Y from"chalk";import vt from"fs/promises";import fo from"path";import ho from"os";var go=fo.join(ho.homedir(),".kaven","cache","licenses.json"),Wn=3600*1e3,Qe=class{cacheDir=fo.join(ho.homedir(),".kaven","cache");isValidFormat(e){return/^KAVEN-(STARTER|COMPLETE|PRO|ENTERPRISE)-[A-Z0-9]{8}-[A-Z0-9]{2}$/.test(e)}async readCache(){try{let e=await vt.readFile(go,"utf-8");return JSON.parse(e)}catch{return{}}}async writeCache(e){await vt.mkdir(this.cacheDir,{recursive:!0}),await vt.writeFile(go,JSON.stringify(e,null,2),"utf-8")}isCacheValid(e){return Date.now()-e.validatedAt<Wn}async getCached(e){let n=(await this.readCache())[e];return n&&this.isCacheValid(n)?n:null}async setCached(e){let t=await this.readCache();t[e.key]={...e,validatedAt:Date.now()},await this.writeCache(t)}async validateLicense(e,t){let n=await this.getCached(e);if(n)return{valid:!0,tier:n.tier,expiresAt:n.expiresAt,source:"cache"};if(!this.isValidFormat(e))throw new Error("Invalid license key format");let{MarketplaceClient:r}=await import("./MarketplaceClient-YCFH2VU4.js"),i=await new r().validateLicense(e,t);return await this.setCached({key:e,tier:i.tier,expiresAt:i.expiresAt,validatedAt:Date.now()}),{...i,source:"api"}}async getLicenseStatus(e){let{MarketplaceClient:t}=await import("./MarketplaceClient-YCFH2VU4.js");return new t().getLicenseStatus(e)}tierLevel(e){return{STARTER:1,COMPLETE:2,PRO:3,ENTERPRISE:4}[e.toUpperCase()]??0}userHasRequiredTier(e,t){return this.tierLevel(e)>=this.tierLevel(t)}};function yo(){return new Xn("status").description("Show license status and tier information").argument("[license-key]","License key to check (uses stored license if omitted)").action(async o=>{let e=new Qe,t=o??process.env.KAVEN_LICENSE_KEY;t||(console.error(Y.red("\u2717 No license key provided. Pass as argument or set KAVEN_LICENSE_KEY.")),process.exit(1));try{console.log(Y.dim("Checking license status..."));let n=await e.getLicenseStatus(t);if(console.log(`
|
|
71
|
+
`+Y.bold("License Status")+`
|
|
72
|
+
`),console.log(` Key: ${Y.dim(n.key.substring(0,16)+"...")}`),console.log(` Tier: ${Y.magenta(n.tier)}`),n.expiresAt){let r=n.daysUntilExpiry,a=r!==null&&r<30?Y.red:Y.green;console.log(` Expires: ${a(n.expiresAt)}${r!==null?Y.dim(` (${r} days)`):""}`)}else console.log(` Expires: ${Y.green("Never")}`);console.log()}catch(n){let r=n instanceof Error?n.message:"Failed to check license status";console.error(Y.red("\u2717 "+r)),process.exit(1)}})}function wo(){let o=new Yn("license").description("Manage Kaven licenses");return o.addCommand(yo()),o}import Ne from"path";import Ue from"fs-extra";import{fileURLToPath as sr}from"url";import{intro as cr,outro as lr,text as rt,select as So,confirm as dr,spinner as ur,note as pr,isCancel as mr,cancel as Et}from"@clack/prompts";import K from"picocolors";import _ from"fs-extra";import se from"path";import{spawn as Zn}from"child_process";var Qn="https://github.com/kaven-co/kaven-template.git",er="https://github.com/bychrisr/kaven-squad";function ue(o,e,t,n){return new Promise((r,a)=>{let i=Zn(o,e,{cwd:t,stdio:n?"pipe":"inherit"});n&&i.stdout&&i.stdout.on("data",s=>n(s.toString())),n&&i.stderr&&i.stderr.on("data",s=>n(s.toString())),i.on("error",a),i.on("close",s=>r(s??0))})}var et=class{validateName(e){return!e||e.trim().length===0?{valid:!1,reason:"Project name cannot be empty"}:/\s/.test(e)?{valid:!1,reason:"Project name cannot contain spaces"}:/^[a-z0-9-]+$/.test(e)?{valid:!0}:{valid:!1,reason:"Project name must only contain lowercase letters, numbers, and hyphens"}}async cloneTemplate(e,t){let n=t||Qn;if(console.log(`[INIT] Clone Source: ${n}`),console.log(`[INIT] Target Dir: ${e}`),await _.pathExists(n)&&(n.startsWith("/")||n.startsWith("./")||n.startsWith("../"))){console.log("[INIT] Local Path Detected. Copying..."),await _.copy(n,e,{filter:a=>!a.includes("node_modules")&&!a.includes(".git")&&!a.includes(".turbo")}),console.log("[INIT] Local Copy Done.");return}let r=await ue("git",["clone","--depth","1",n,e],process.cwd());if(r!==0)throw new Error(`git clone failed with exit code ${r}`)}async removeGitDir(e){let t=se.join(e,".git");await _.pathExists(t)&&await _.remove(t)}async replacePlaceholders(e,t){let n={"{{PROJECT_NAME}}":t.projectName,"{{DATABASE_URL}}":t.dbUrl,"{{DEFAULT_LOCALE}}":t.locale,"{{DEFAULT_CURRENCY}}":t.currency},r=["package.json",".env.example","packages/database/prisma/schema.prisma","apps/api/package.json","apps/admin/package.json","apps/tenant/package.json","docs/architecture/tech-stack.md","docs/architecture/source-tree.md","docs/architecture/coding-standards.md"];for(let i of r){let s=se.join(e,i);if(!await _.pathExists(s))continue;let c=await _.readFile(s,"utf-8");for(let[l,d]of Object.entries(n))c=c.split(l).join(d);await _.writeFile(s,c,"utf-8")}let a=se.join(e,"package.json");if(await _.pathExists(a)){let i=await _.readJson(a);i.name!==t.projectName&&(i.name=t.projectName,await _.writeJson(a,i,{spaces:2}))}}async runInstall(e){let t=await ue("pnpm",["install"],e);if(t!==0)throw new Error(`pnpm install failed with exit code ${t}`)}async initGit(e){await ue("git",["init"],e),await ue("git",["add","."],e),await ue("git",["commit","-m","chore: initial kaven setup"],e)}async installSquad(e){let t=se.join(e,"squads"),n=se.join(t,"kaven-squad");if(await _.pathExists(n))return{installed:!1,reason:"already-exists"};await _.ensureDir(t);let r=await ue("git",["clone","--depth","1",er,n],process.cwd());if(r!==0)return{installed:!1,reason:`git clone exited with code ${r}`};let a=se.join(n,".git");return await _.pathExists(a)&&await _.remove(a),{installed:!0}}async installAIOXCore(e){let t=await ue("npx",["aiox-core@5.0.3","install","--quiet"],e);return t!==0?{installed:!1,reason:`npx aiox-core exited with code ${t}`}:{installed:!0}}async healthCheck(e){let t=[],n=["package.json",".env.example","packages/database/prisma/schema.prisma"];for(let a of n)await _.pathExists(se.join(e,a))||t.push(`Missing required file: ${a}`);return await _.pathExists(se.join(e,"node_modules"))||t.push("Dependencies not installed. Run: pnpm install"),{healthy:t.length===0,issues:t}}};import pe from"path";import oe from"fs-extra";import tr from"os";import vo from"js-yaml";import{z as E}from"zod";var tt=pe.join(tr.homedir(),".kaven"),kt=pe.join(tt,"config.json"),ko="kaven-config.yaml",bo=E.object({registry:E.string().url().default("https://marketplace.kaven.site"),telemetry:E.boolean().default(!0),theme:E.enum(["light","dark"]).default("dark"),language:E.enum(["en","pt-BR"]).default("en"),customRegistry:E.string().url().optional(),projectId:E.string().uuid().optional(),activeModules:E.array(E.string()).default([]),capabilities:E.record(E.string(),E.union([E.string(),E.boolean(),E.number()])).default({}),lastLogin:E.string().datetime().optional(),projectDefaults:E.object({dbUrl:E.string().optional(),emailProvider:E.enum(["postmark","resend","ses","smtp"]).optional(),locale:E.string().optional(),currency:E.string().optional()}).optional()}),bt=class{globalConfig={};projectConfig={};currentConfig;constructor(){this.currentConfig=bo.parse({})}async initialize(){if(await oe.ensureDir(tt),await oe.pathExists(kt))try{this.globalConfig=await oe.readJson(kt)}catch{this.globalConfig={}}let e=this.findProjectRoot();if(e){let t=pe.join(e,ko);if(await oe.pathExists(t))try{let n=await oe.readFile(t,"utf-8");this.projectConfig=vo.load(n)}catch{this.projectConfig={}}}this.resolve()}resolve(){this.currentConfig=bo.parse({...this.globalConfig,...this.projectConfig})}findProjectRoot(){let e=process.cwd();for(;e!==pe.parse(e).root;){if(oe.existsSync(pe.join(e,"package.json")))return e;e=pe.dirname(e)}return null}get(e){let t=`KAVEN_${e.toUpperCase()}`;if(process.env[t]!==void 0){let n=process.env[t];return typeof this.currentConfig[e]=="boolean"?n==="true":typeof this.currentConfig[e]=="number"?Number(n):n}return this.currentConfig[e]}async set(e,t,n="project"){n==="project"?(this.projectConfig[e]=t,await this.persistProject()):(this.globalConfig[e]=t,await this.persistGlobal()),this.resolve()}async persistGlobal(){await oe.ensureDir(tt),await oe.writeJson(kt,this.globalConfig,{spaces:2})}async persistProject(){let e=this.findProjectRoot();if(!e)return;let t=pe.join(e,ko),n=vo.dump(this.projectConfig,{lineWidth:120,noRefs:!0});await oe.writeFile(t,n,"utf-8")}async reset(){this.globalConfig={},this.projectConfig={},await this.persistGlobal(),await this.persistProject(),this.resolve()}getRegistry(){return this.currentConfig.customRegistry||this.currentConfig.registry}getAll(){return{...this.currentConfig}}getProjectRoot(){return this.findProjectRoot()}getConfigDir(){return tt}},D=new bt;import ce from"picocolors";var or=`
|
|
73
|
+
\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557
|
|
74
|
+
\u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551
|
|
75
|
+
\u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551
|
|
76
|
+
\u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551
|
|
77
|
+
\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551
|
|
78
|
+
\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D
|
|
79
|
+
`;function xo(){return`
|
|
80
|
+
${or.split(`
|
|
81
|
+
`).map(t=>ce.cyan(t)).join(`
|
|
82
|
+
`)}
|
|
83
|
+
${ce.dim(" The Premium Framework Orchestrator for SaaS")}
|
|
84
|
+
`}var hc={primary:ce.cyan,secondary:ce.magenta,success:ce.green,warning:ce.yellow,error:ce.red,dim:ce.dim};import*as nr from"child_process";import xt from"fs-extra";import*as ot from"path";import ar from"ora";import Eo from"chalk";var rr={...nr},ir={ora:ar};async function nt(o,e={}){if(e.skipAiox)return;let t=ot.join(o,".aiox-core");if(!xt.existsSync(t)&&!xt.existsSync(ot.join(o,".aiox")))return;let n=ir.ora("Bootstrapping AIOX environment...").start();try{let r=xt.existsSync(ot.join(o,".aiox-core/bin/aiox.js"))?".aiox-core/bin/aiox.js":".aiox/bin/aiox.js";rr.execSync(`node ${r} devops environment-bootstrap --quiet`,{cwd:o,stdio:"pipe",timeout:6e4}),n.succeed("AIOX environment bootstrapped")}catch(r){n.warn("AIOX environment bootstrap failed"),console.log(Eo.yellow(" \u26A0 Run manually inside the project: kaven aiox bootstrap")),process.env.KAVEN_DEBUG&&console.error(Eo.gray(` Error: ${r.message}`))}}function me(o){mr(o)&&(Et("Operation cancelled."),process.exit(0))}async function Co(o,e){let t=await X.getInstance(),n=new et,r=await So({message:"\u{1F310} Select Language / Selecione o Idioma:",options:[{label:"English",value:"en"},{label:"Portugu\xEAs (Brasil)",value:"pt-BR"}],initialValue:"en"});me(r),await t.setLanguage(r),await D.initialize(),await D.set("language",r,"global"),console.log(xo()),cr(K.cyan(t.t("init.intro")));let a=o;a||(e.defaults?a="my-kaven-app":(a=await rt({message:t.t("init.projectName"),placeholder:"my-kaven-app",validate:l=>{let d=n.validateName(l||"");return d.valid?void 0:d.reason}}),me(a)));let i=Ne.resolve(process.cwd(),a);await Ue.pathExists(i)&&!e.force&&(Et(K.red(`Error: Directory "${a}" already exists. Use --force to overwrite.`)),process.exit(1));let s;if(e.defaults){let l=D.getAll().projectDefaults||{};s={dbUrl:e.dbUrl||l.dbUrl||`postgresql://user:password@localhost:5432/${a}`,emailProvider:e.emailProvider||l.emailProvider||"postmark",locale:e.locale||l.locale||"en-US",currency:e.currency||l.currency||"USD"}}else{let l=D.getAll().projectDefaults||{},d=await rt({message:"Database URL (PostgreSQL):",initialValue:l.dbUrl||`postgresql://user:password@localhost:5432/${a}`});me(d);let p=await So({message:"Email provider:",options:[{label:"Postmark",value:"postmark"},{label:"Resend",value:"resend"},{label:"AWS SES",value:"ses"},{label:"SMTP",value:"smtp"}],initialValue:l.emailProvider||"postmark"});me(p);let u=await rt({message:"Default locale:",initialValue:l.locale||"en-US"});me(u);let m=await rt({message:"Default currency:",initialValue:l.currency||"USD"});me(m);let g=await dr({message:t.t("init.withSquad"),initialValue:!0});me(g),e.withSquad=g,s={dbUrl:d,emailProvider:p,locale:u,currency:m}}let c=ur();c.start("Cloning kaven-template...");try{await n.cloneTemplate(i,e.template),c.stop(K.green("Template cloned"))}catch(l){let d=l instanceof Error?l:new Error(String(l));c.stop(K.red("Clone failed")),Et(d.message),process.exit(1)}c.start("Configuring project..."),await n.removeGitDir(i),await n.replacePlaceholders(i,{...s,projectName:a});try{let l=Ne.join(i,".claude","CLAUDE.md");await Ue.ensureDir(Ne.dirname(l));let d=sr(import.meta.url),p=Ne.dirname(d),u=Ne.resolve(p,"../../core/templates/CLAUDE.md.hbs");if(await Ue.pathExists(u)){let g=(await Ue.readFile(u,"utf-8")).replace("${new Date().toLocaleDateString()}",new Date().toLocaleDateString());await Ue.writeFile(l,g,"utf-8")}}catch(l){console.warn(K.dim(`[init] CLAUDE.md injection skipped: ${l instanceof Error?l.message:String(l)}`))}if(c.stop(K.green("Project configured")),!e.skipInstall){c.start(t.t("init.installing"));try{await n.runInstall(i),c.stop(K.green("Dependencies installed"))}catch{c.stop(K.yellow("pnpm install failed (skip)"))}}if(!e.skipGit){c.start("Initializing git...");try{await n.initGit(i),c.stop(K.green("Git initialized"))}catch{c.stop(K.yellow("Git init failed (skip)"))}}e.withSquad&&(c.start("Infecting AIOX intelligence..."),(await n.installSquad(i)).installed?(await n.installAIOXCore(i),c.stop(K.green("Kaven Squad online \u{1F916}"))):c.stop(K.yellow("AIOX bootstrap skipped or failed"))),await nt(i,{skipAiox:e.skipAiox}),pr(`cd ${K.cyan(a)}
|
|
85
|
+
cp .env.example .env
|
|
86
|
+
npx prisma migrate dev
|
|
87
|
+
pnpm dev`,"Next Steps"),lr(K.cyan(t.t("init.outro")));try{await D.set("projectDefaults",{dbUrl:s.dbUrl,emailProvider:s.emailProvider,locale:s.locale,currency:s.currency},"global")}catch(l){console.warn(K.dim(`[init] Config save skipped: ${l instanceof Error?l.message:String(l)}`))}}import M from"chalk";import $t from"ora";import kr from"open";import To from"path";import Ce from"fs-extra";import br from"os";import L from"chalk";import St from"ora";import at from"path";import{fileURLToPath as gr}from"url";import{spawn as fr}from"child_process";import Po from"fs";var hr=gr(import.meta.url),$o=at.dirname(hr);function yr(){let o=[at.join($o,"../../package.json"),at.join($o,"../../../package.json"),at.join(process.cwd(),"package.json")];for(let e of o)if(Po.existsSync(e))try{return JSON.parse(Po.readFileSync(e,"utf8"))}catch{continue}return{version:"0.4.2-alpha.0"}}var wr=yr(),Se=wr.version,ge="kaven-cli";async function Ct(){let o=St("Checking for updates...").start();try{let e=await fetch(`https://registry.npmjs.org/${ge}`);if(!e.ok){o.fail("Could not check for updates");return}let r=(await e.json())["dist-tags"]?.latest||Se;if(o.stop(),console.log(),console.log(L.bold("Version Check:")),console.log(` Current: ${L.cyan(Se)}`),console.log(` Latest: ${L.cyan(r)}`),console.log(),r===Se){console.log(L.green("\u2705 You're on the latest version!"));return}let a=Ao(Se),i=Ao(r);i.major>a.major||i.major===a.major&&i.minor>a.minor||i.major===a.major&&i.minor===a.minor&&i.patch>a.patch?(console.log(L.yellow(`\u26A0 Update available: ${r}`)),console.log(),console.log(L.bold("To upgrade, run:")),console.log(L.cyan(` npm install -g ${ge}@latest`)),console.log(L.cyan(" or")),console.log(L.cyan(` pnpm add -g ${ge}@latest`)),console.log(),console.log(L.gray("Release notes: https://github.com/kaven-co/kaven-cli/releases"))):console.log(L.green("\u2705 You're on the latest version!"))}catch(e){o.fail(`Check failed: ${e instanceof Error?e.message:String(e)}`),console.log(L.gray("You can manually check at: https://www.npmjs.com/package/kaven-cli"))}}async function Pt(){console.log();let o=St("Fetching latest version...").start();try{let e=await fetch(`https://registry.npmjs.org/${ge}`);if(!e.ok)throw new Error("Failed to fetch package info");let r=(await e.json())["dist-tags"]?.latest||Se;if(r===Se){o.succeed("Already on latest version");return}o.text=`Installing ${ge}@${r}...`;let a=process.env.npm_config_user_agent?.includes("pnpm")?"pnpm":"npm",i=await Mo(a,["install","-g",`${ge}@${r}`]);if(i!==0){o.fail(`Installation failed with exit code ${i}`),console.error(L.gray(`Try: ${a} install -g ${ge}@latest`)),process.exit(1);return}o.succeed(`Updated to ${r}`);let s=St("Running health check...").start(),c=await vr();c.ok?(s.succeed("Installation verified"),console.log(),console.log(L.green("\u2705 CLI upgraded successfully!")),console.log(L.gray("Try: kaven --version"))):(s.warn("Installation verification failed"),console.log(L.yellow(c.errors.join(`
|
|
88
|
+
`))))}catch(e){o.fail(`Installation failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}async function vr(){let o=[];try{await Mo("kaven",["--version"],{stdio:"pipe"})!==0&&o.push("kaven command not available in PATH")}catch{o.push("Could not execute kaven command")}return{ok:o.length===0,errors:o}}function Mo(o,e,t){return new Promise((n,r)=>{let a=fr(o,e,t||{stdio:"inherit"});a.on("error",r),a.on("close",i=>n(i??0))})}function Ao(o){let e=o.replace(/^v/,"").split("-")[0],[t,n,r]=e.split(".").map(Number);return{major:t||0,minor:n||0,patch:r||0}}var Pe=To.join(br.homedir(),".kaven","license.json"),xr=["starter","complete","pro","enterprise"],Be={starter:"Starter",complete:"Complete",pro:"Pro",enterprise:"Enterprise"},Er=5e3,jo=120;async function Sr(){if(!await Ce.pathExists(Pe))return null;try{return(await Ce.readJson(Pe)).key||null}catch{return null}}async function Cr(o){let e={};if(await Ce.pathExists(Pe))try{e=await Ce.readJson(Pe)}catch{}await Ce.ensureDir(To.dirname(Pe)),await Ce.writeJson(Pe,{...e,tier:o},{spaces:2})}function Pr(o){return new Promise(e=>setTimeout(e,o))}async function Io(o){let e=new T;try{await e.getValidToken()}catch{console.error(M.red("Error: Not authenticated. Run 'kaven auth login' first.")),process.exit(1);return}let t=await Sr();if(!t){console.error(M.red("Error: No license found. Add your license key first with 'kaven license status'.")),process.exit(1);return}let n=new J(e),r=$t("Loading your current license...").start(),a;try{a=(await n.getLicenseStatus(t)).tier.toLowerCase(),r.succeed(`Current tier: ${M.bold(Be[a]||a)}`)}catch{r.fail("Could not load license status"),console.error(M.gray("Try: kaven license status")),process.exit(1);return}let{printTierComparisonTable:i}=await import("./tier-table-DQMPQSI2.js");i(a,"pro"),console.log();let{select:s}=await import("@inquirer/prompts"),c=xr.filter(g=>g!==a&&g!=="enterprise");if(c.length===0){console.log(M.yellow(`You're already on the highest available tier (${Be[a]||a}).`)),console.log(M.gray("For Enterprise plans, contact: enterprise@kaven.site"));return}let l=await s({message:"Select target tier:",choices:c.map(g=>({name:Be[g],value:g}))});if(l===a){console.log(M.yellow(`Already on ${Be[a]||a}.`));return}let d=$t("Creating checkout session...").start(),p,u;try{let g=await n.createCheckoutSession(l,t);p=g.sessionUrl,u=g.sessionId,d.succeed("Checkout session created")}catch(g){d.fail("Failed to create checkout session"),console.error(M.red(g instanceof Error?g.message:String(g))),process.exit(1);return}if(o.browser!==!1){console.log(M.cyan("Opening checkout in your browser...")),console.log(M.gray(`URL: ${p}`));try{await kr(p)}catch{console.log(M.yellow("Could not open browser automatically. Open this URL manually:")),console.log(M.cyan(p))}}else console.log(M.cyan("Open this URL to complete checkout:")),console.log(M.bold(p));console.log();let m=$t("Waiting for payment confirmation (checking every 5s, max 10 min)...").start();for(let g=0;g<jo;g++){await Pr(Er);let k=jo-g-1;m.text=`Waiting for payment confirmation... (${k*5}s remaining)`;try{let F=await n.getCheckoutStatus(u);if(F.status==="confirmed"){m.succeed("Payment confirmed!");let I=F.tier||l;await Cr(I),console.log(),console.log(M.green(`\u2705 Successfully upgraded to ${Be[I]||I}!`)),console.log(M.gray("Your new features are now unlocked."));return}if(F.status==="cancelled"){m.fail("Checkout was cancelled."),console.log(M.gray("No changes were made to your subscription."));return}if(F.status==="failed"){m.fail("Payment failed."),console.log(M.gray("Please try again or contact support@kaven.site")),process.exit(1);return}}catch{}}m.warn("Timed out waiting for payment confirmation."),console.log(),console.log(M.yellow("If you completed payment, your upgrade may take a few minutes to activate.")),console.log(M.gray("Check your upgrade status at: https://dashboard.kaven.site/billing"))}import ne from"chalk";import Z from"fs-extra";import $e from"path";import $r from"os";var Mt=class{cacheDir;maxSizeBytes;indexPath;constructor(e,t){this.cacheDir=e??$e.join($r.homedir(),".kaven","cache"),this.maxSizeBytes=t??50*1024*1024,this.indexPath=$e.join(this.cacheDir,"_index.json")}async ensureDir(){await Z.ensureDir(this.cacheDir)}keyToFileName(e){return e.replace(/[^a-zA-Z0-9-_:.]/g,"_")+".json"}async readIndex(){try{if(await Z.pathExists(this.indexPath))return await Z.readJson(this.indexPath)}catch{}return{}}async writeIndex(e){await this.ensureDir(),await Z.writeJson(this.indexPath,e,{spaces:2})}async get(e){let n=(await this.readIndex())[e];if(!n||Date.now()>n.expiresAt)return null;try{let r=$e.join(this.cacheDir,n.file);return(await Z.readJson(r)).data}catch{return null}}async getStale(e){let n=(await this.readIndex())[e];if(!n)return null;try{let r=$e.join(this.cacheDir,n.file);return(await Z.readJson(r)).data}catch{return null}}async set(e,t,n){await this.ensureDir();let r=JSON.stringify(t),a=Buffer.byteLength(r,"utf8"),i=Date.now(),s=i+n,c=this.keyToFileName(e),l=$e.join(this.cacheDir,c),d={data:t,expiresAt:s,size:a,createdAt:i};await Z.writeJson(l,d,{spaces:2});let p=await this.readIndex();p[e]={file:c,expiresAt:s,size:a,createdAt:i},await this.writeIndex(p),await this.evict()}async evict(){let e=await this.readIndex(),t=Object.entries(e),n=t.reduce((a,[,i])=>a+i.size,0);if(n<=this.maxSizeBytes)return;t.sort(([,a],[,i])=>a.createdAt-i.createdAt);let r={...e};for(let[a,i]of t){if(n<=this.maxSizeBytes)break;try{let s=$e.join(this.cacheDir,i.file);await Z.remove(s),delete r[a],n-=i.size}catch{}}await this.writeIndex(r)}async stats(){let e=await this.readIndex(),t=Object.values(e);if(t.length===0)return{totalSize:0,entries:0};let n=t.reduce((s,c)=>s+c.size,0),r=t.map(s=>s.createdAt),a=new Date(Math.min(...r)),i=new Date(Math.max(...r));return{totalSize:n,entries:t.length,oldest:a,newest:i}}async clear(){await Z.pathExists(this.cacheDir)&&await Z.remove(this.cacheDir)}},At=null;function jt(){return At||(At=new Mt),At}function Ro(o){if(o===0)return"0 B";let e=1024,t=["B","KB","MB","GB"],n=Math.floor(Math.log(o)/Math.log(e));return`${parseFloat((o/Math.pow(e,n)).toFixed(1))} ${t[n]}`}async function _o(){let o=jt(),e=await o.stats();console.log(ne.bold(`
|
|
89
|
+
Kaven CLI Cache Status
|
|
90
|
+
`)),console.log(` Cache directory: ${ne.cyan(o.cacheDir)}`),console.log(` Total size: ${ne.cyan(Ro(e.totalSize))}`),console.log(` Cached entries: ${ne.cyan(e.entries.toString())}`),e.oldest&&console.log(` Oldest entry: ${ne.gray(e.oldest.toLocaleString())}`),e.newest&&console.log(` Newest entry: ${ne.gray(e.newest.toLocaleString())}`),console.log(),console.log(ne.gray("Run 'kaven cache clear' to remove all cached data."))}async function Do(){let o=jt(),e=await o.stats();if(e.entries===0){console.log(ne.gray("Cache is already empty."));return}await o.clear(),console.log(ne.green(`Cache cleared: ${e.entries} entries (${Ro(e.totalSize)}) removed.`))}import N from"chalk";async function Lo(o,e){(!o||!e)&&(console.error(N.red("Error: Both key and value are required")),console.error(N.gray("Usage: kaven config set KEY VALUE")),process.exit(1)),await D.initialize();try{await D.set(o,e),console.log(N.green(`\u2705 Set ${N.bold(o)} = ${N.bold(e)}`))}catch(t){console.error(N.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function Oo(o,e){o||(console.error(N.red("Error: Key is required")),console.error(N.gray("Usage: kaven config get KEY")),process.exit(1)),await D.initialize();try{let t=D.get(o);e.json?console.log(JSON.stringify({[o]:t},null,2)):console.log(t)}catch(t){console.error(N.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function Fo(o){await D.initialize();let e=D.getAll();if(o.json)console.log(JSON.stringify(e,null,2));else{console.log(N.bold("Kaven Configuration:")),console.log(N.gray(`Location: ${D.getConfigDir()}/config.json`)),console.log();let t=Object.entries(e),n=Math.max(...t.map(([r])=>r.length));for(let[r,a]of t){let i=" ".repeat(n-r.length),s=typeof a=="object"?JSON.stringify(a,null,2).replace(/\n/g,`
|
|
91
|
+
`+" ".repeat(n+3)):a;console.log(` ${r}${i} ${N.cyan(s)}`)}}}async function Ko(){let{confirm:o}=await import("@inquirer/prompts");if(!await o({message:"Are you sure you want to reset config to defaults?",default:!1})){console.log(N.yellow("Cancelled."));return}await D.initialize(),await D.reset(),console.log(N.green("\u2705 Config reset to defaults"))}import{select as Ar,confirm as No,text as Mr,multiselect as jr,isCancel as Tr,cancel as Ir}from"@clack/prompts";import O from"picocolors";import It from"fs-extra";import Uo from"path";var re=[{key:"FEATURE_EMAIL_VERIFICATION",type:"boolean",description:"Email verification on signup",category:"Auth",defaultValue:"true"},{key:"FEATURE_2FA_TOTP",type:"boolean",description:"Two-factor authentication via TOTP",category:"Auth",defaultValue:"false"},{key:"FEATURE_SSO_SAML",type:"boolean",description:"Single Sign-On via SAML/OIDC",category:"Auth",defaultValue:"false"},{key:"FEATURE_SOCIAL_LOGIN",type:"boolean",description:"Login via Google, GitHub, etc.",category:"Auth",defaultValue:"true"},{key:"FEATURE_MAGIC_LINK",type:"boolean",description:"Passwordless login via email",category:"Auth",defaultValue:"false"},{key:"FEATURE_CUSTOM_DOMAIN",type:"boolean",description:"Custom domain per tenant",category:"Tenancy",defaultValue:"false"},{key:"FEATURE_WHITE_LABEL",type:"boolean",description:"Remove Kaven branding",category:"Tenancy",defaultValue:"false"},{key:"FEATURE_MULTI_BUSINESS",type:"boolean",description:"Multiple businesses per user",category:"Tenancy",defaultValue:"false"},{key:"FEATURE_AGENCY_HUB",type:"boolean",description:"Agency management dashboard",category:"Tenancy",defaultValue:"false"},{key:"FEATURE_TENANT_THEMES",type:"boolean",description:"Custom themes for tenants",category:"Tenancy",defaultValue:"true"},{key:"FEATURE_SUBSCRIPTIONS",type:"boolean",description:"Subscription management",category:"Billing",defaultValue:"true"},{key:"FEATURE_INVOICING",type:"boolean",description:"Automatic invoicing",category:"Billing",defaultValue:"true"},{key:"FEATURE_USAGE_BILLING",type:"boolean",description:"Metered usage billing",category:"Billing",defaultValue:"false"},{key:"FEATURE_PADDLE_CHECKOUT",type:"boolean",description:"Paddle payment integration",category:"Billing",defaultValue:"true"},{key:"FEATURE_PAGUBIT_PIX",type:"boolean",description:"Pix payment support",category:"Billing",defaultValue:"false"},{key:"FEATURE_API_ACCESS",type:"boolean",description:"External API access",category:"API",defaultValue:"false"},{key:"FEATURE_WEBHOOKS",type:"boolean",description:"Outgoing webhooks",category:"API",defaultValue:"false"},{key:"FEATURE_MARKETPLACE_ACCESS",type:"boolean",description:"Kaven Marketplace access",category:"API",defaultValue:"true"},{key:"MAX_API_CALLS_MONTH",type:"numeric",description:"Maximum API calls per month",category:"API",defaultValue:"10000"},{key:"MAX_AGENT_API_CALLS_HOUR",type:"numeric",description:"Maximum agent calls per hour",category:"API",defaultValue:"100"},{key:"MAX_TEAM_MEMBERS",type:"numeric",description:"Maximum team members per tenant",category:"Limits",defaultValue:"5"},{key:"MAX_PROJECTS",type:"numeric",description:"Maximum projects per tenant",category:"Limits",defaultValue:"3"},{key:"MAX_STORAGE_GB",type:"numeric",description:"Maximum storage in GB",category:"Limits",defaultValue:"1"},{key:"MAX_TENANTS",type:"numeric",description:"Maximum sub-tenants",category:"Limits",defaultValue:"1"},{key:"FEATURE_PRIORITY_SUPPORT",type:"boolean",description:"Priority support queue",category:"Support",defaultValue:"false"},{key:"FEATURE_AUDIT_COMPLIANCE",type:"boolean",description:"Audit logs and compliance",category:"Support",defaultValue:"false"},{key:"FEATURE_DATA_EXPORT",type:"boolean",description:"Customer data export",category:"Support",defaultValue:"true"}],Tt={starter:{FEATURE_EMAIL_VERIFICATION:!0,FEATURE_SOCIAL_LOGIN:!0,FEATURE_MARKETPLACE_ACCESS:!0,MAX_TEAM_MEMBERS:"5",MAX_PROJECTS:"3",MAX_API_CALLS_MONTH:"10000",MAX_AGENT_API_CALLS_HOUR:"100"},complete:{FEATURE_EMAIL_VERIFICATION:!0,FEATURE_SOCIAL_LOGIN:!0,FEATURE_CUSTOM_DOMAIN:!0,FEATURE_API_ACCESS:!0,FEATURE_MARKETPLACE_ACCESS:!0,MAX_TEAM_MEMBERS:"25",MAX_PROJECTS:"20",MAX_API_CALLS_MONTH:"100000",MAX_AGENT_API_CALLS_HOUR:"500"},pro:{FEATURE_EMAIL_VERIFICATION:!0,FEATURE_SOCIAL_LOGIN:!0,FEATURE_CUSTOM_DOMAIN:!0,FEATURE_WHITE_LABEL:!0,FEATURE_API_ACCESS:!0,FEATURE_MARKETPLACE_ACCESS:!0,MAX_TEAM_MEMBERS:"100",MAX_PROJECTS:"100",MAX_API_CALLS_MONTH:"1000000",MAX_AGENT_API_CALLS_HOUR:"2000"},enterprise:{}};function Ve(o){Tr(o)&&(Ir("Cancelled."),process.exit(0))}async function Bo(o){let e=o.outputPath??Uo.join(process.cwd(),"packages","database","prisma","seeds","capabilities.seed.ts");if(o.list){let t=await X.getInstance();Rr(t);return}if(o.tier){await Vo(o.tier,e,o);return}await _r(e,o)}function Rr(o){console.log(),console.log(O.bold(O.underline(o.t("config.features.catalogHeader")))),console.log(O.dim(o.t("config.features.capabilitiesTotal",{count:re.length})+`
|
|
92
|
+
`));let e=[...new Set(re.map(t=>t.category))];for(let t of e){let n=re.filter(r=>r.category===t);console.log(O.bold(O.cyan(` ${t} (${n.length})`)));for(let r of n)console.log(` ${O.white(r.key.padEnd(30))} ${O.dim(`[${r.type}]`)}`),console.log(` ${O.dim(r.description)}`);console.log()}console.log(O.bold(o.t("config.features.tierPresets")));for(let t of["starter","complete","pro","enterprise"])console.log(` ${O.white(t.padEnd(12))}`);console.log()}async function Vo(o,e,t){let n=Tt[o]||{},r={};for(let a of re)o==="enterprise"?r[a.key]=a.type==="boolean"?!0:"-1":r[a.key]=n[a.key]??(a.type==="boolean"?!1:a.defaultValue);await Jo(r,e,t,o)}async function _r(o,e){let t=await X.getInstance();console.log(),console.log(O.bold(O.underline(t.t("config.features.tuiHeader"))));let n=await Ar({message:t.t("config.features.selectTier"),options:[{label:"Starter \u2014 Essential SaaS features",value:"starter"},{label:"Complete \u2014 White-label + Custom Domains",value:"complete"},{label:"Pro \u2014 Extended API + Limits",value:"pro"},{label:"Enterprise \u2014 Unlimited everything",value:"enterprise"},{label:O.dim(t.t("common.cancel")),value:"cancel"}]});if(Ve(n),n==="cancel")return;let r=n,a=Tt[r]||{},i={},s=await No({message:t.t("config.features.customize"),initialValue:!1});if(Ve(s),!s)return Vo(r,o,e);let c=[...new Set(re.map(l=>l.category))];for(let l of c){let d=re.filter(m=>m.category===l),p=d.filter(m=>m.type==="boolean"),u=d.filter(m=>m.type==="numeric");if(p.length>0){let m=p.filter(k=>r==="enterprise"||a[k.key]===!0).map(k=>k.key),g=await jr({message:`${l} features:`,options:p.map(k=>({label:`${k.key.padEnd(30)} \u2014 ${k.description}`,value:k.key})),initialValues:m,required:!1});Ve(g);for(let k of p)i[k.key]=g.includes(k.key)}for(let m of u){let g=r==="enterprise"?"-1":a[m.key]||m.defaultValue,k=await Mr({message:`${m.key} (${m.description}):`,placeholder:g,defaultValue:g});Ve(k),i[m.key]=k}}await Jo(i,o,e,r)}async function Jo(o,e,t,n){let r=await X.getInstance(),a=re.map(s=>{let c=o[s.key];return` { key: "${s.key}", type: "${s.type}", defaultValue: "${c}", description: "${s.description}" },`}).join(`
|
|
93
|
+
`),i=`// packages/database/prisma/seeds/capabilities.seed.ts
|
|
94
|
+
// Generated by kaven config features \u2014 ${new Date().toISOString()}
|
|
95
|
+
// Tier: ${n}
|
|
96
|
+
|
|
97
|
+
import { PrismaClient } from "@prisma/client";
|
|
98
|
+
|
|
99
|
+
export async function seedCapabilities(prisma: PrismaClient) {
|
|
100
|
+
const capabilities = [
|
|
101
|
+
${a}
|
|
102
|
+
];
|
|
103
|
+
|
|
104
|
+
console.log("\u{1F510} Seeding ${re.length} Capabilities...");
|
|
105
|
+
|
|
106
|
+
for (const cap of capabilities) {
|
|
107
|
+
await prisma.capability.upsert({
|
|
108
|
+
where: { key: cap.key },
|
|
109
|
+
update: cap,
|
|
110
|
+
create: cap,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
`;if(t.dryRun){console.log(O.bold(`
|
|
115
|
+
`+r.t("config.features.dryRunHeader"))),console.log(i);return}if(It.existsSync(e)&&!t.force){let s=await No({message:r.t("config.features.confirmOverwrite"),initialValue:!1});if(Ve(s),!s)return}await It.ensureDir(Uo.dirname(e)),await It.writeFile(e,i,"utf-8"),console.log(O.green(`
|
|
116
|
+
\u2705 ${r.t("config.features.seedWritten",{path:e})}`)),console.log(O.dim(r.t("config.features.runSeed")))}import U from"chalk";import Dr from"ora";import Ae from"path";import fe from"fs-extra";var Lr=`name: Tests
|
|
117
|
+
on:
|
|
118
|
+
push:
|
|
119
|
+
branches: [main, develop]
|
|
120
|
+
pull_request:
|
|
121
|
+
branches: [main, develop]
|
|
122
|
+
|
|
123
|
+
jobs:
|
|
124
|
+
test:
|
|
125
|
+
runs-on: ubuntu-latest
|
|
126
|
+
services:
|
|
127
|
+
postgres:
|
|
128
|
+
image: postgres:15
|
|
129
|
+
env:
|
|
130
|
+
POSTGRES_PASSWORD: postgres
|
|
131
|
+
options: >-
|
|
132
|
+
--health-cmd pg_isready
|
|
133
|
+
--health-interval 10s
|
|
134
|
+
--health-timeout 5s
|
|
135
|
+
--health-retries 5
|
|
136
|
+
ports:
|
|
137
|
+
- 5432:5432
|
|
138
|
+
steps:
|
|
139
|
+
- uses: actions/checkout@v3
|
|
140
|
+
- uses: pnpm/action-setup@v2
|
|
141
|
+
with:
|
|
142
|
+
version: 8
|
|
143
|
+
- uses: actions/setup-node@v3
|
|
144
|
+
with:
|
|
145
|
+
node-version: 20
|
|
146
|
+
cache: 'pnpm'
|
|
147
|
+
- run: pnpm install
|
|
148
|
+
- run: pnpm typecheck
|
|
149
|
+
- run: pnpm lint
|
|
150
|
+
- run: pnpm test
|
|
151
|
+
- run: pnpm build
|
|
152
|
+
`,Or=`name: Publish Module
|
|
153
|
+
on:
|
|
154
|
+
push:
|
|
155
|
+
tags:
|
|
156
|
+
- 'v*'
|
|
157
|
+
|
|
158
|
+
jobs:
|
|
159
|
+
publish:
|
|
160
|
+
runs-on: ubuntu-latest
|
|
161
|
+
steps:
|
|
162
|
+
- uses: actions/checkout@v3
|
|
163
|
+
- uses: pnpm/action-setup@v2
|
|
164
|
+
with:
|
|
165
|
+
version: 8
|
|
166
|
+
- uses: actions/setup-node@v3
|
|
167
|
+
with:
|
|
168
|
+
node-version: 20
|
|
169
|
+
cache: 'pnpm'
|
|
170
|
+
- run: pnpm install
|
|
171
|
+
- run: pnpm build
|
|
172
|
+
- name: Publish to Kaven Marketplace
|
|
173
|
+
env:
|
|
174
|
+
KAVEN_LICENSE_KEY: \${{ secrets.KAVEN_LICENSE_KEY }}
|
|
175
|
+
run: kaven module publish
|
|
176
|
+
`,Fr=`#!/bin/bash
|
|
177
|
+
# Pre-commit hook for Kaven projects
|
|
178
|
+
set -e
|
|
179
|
+
|
|
180
|
+
echo "\u{1F50D} Running pre-commit checks..."
|
|
181
|
+
|
|
182
|
+
# Lint
|
|
183
|
+
echo " Linting..."
|
|
184
|
+
pnpm lint || exit 1
|
|
185
|
+
|
|
186
|
+
# Type check
|
|
187
|
+
echo " Type checking..."
|
|
188
|
+
pnpm typecheck || exit 1
|
|
189
|
+
|
|
190
|
+
# Format check
|
|
191
|
+
if command -v pnpm format &> /dev/null; then
|
|
192
|
+
echo " Format checking..."
|
|
193
|
+
pnpm format || exit 1
|
|
194
|
+
fi
|
|
195
|
+
|
|
196
|
+
echo "\u2705 All pre-commit checks passed"
|
|
197
|
+
`;async function Go(o){let e=process.cwd(),t=Ae.join(e,"package.json");await fe.pathExists(t)||(console.error(U.red("Error: package.json not found. Run this in a Kaven project root.")),process.exit(1));let n=Dr("Setting up CI/CD configuration...").start();try{let r=Ae.join(e,".github","workflows");await fe.ensureDir(r);let a=Ae.join(r,"test.yml");o.dryRun||await fe.writeFile(a,Lr),n.text=`Creating ${U.cyan(".github/workflows/test.yml")}...`;let i=Ae.join(r,"publish.yml");o.dryRun||await fe.writeFile(i,Or),n.text=`Creating ${U.cyan(".github/workflows/publish.yml")}...`;let s=Ae.join(e,".husky");await fe.ensureDir(s);let c=Ae.join(s,"pre-commit");o.dryRun||(await fe.writeFile(c,Fr),await fe.chmod(c,493)),n.text=`Creating ${U.cyan(".husky/pre-commit")}...`,n.succeed("CI/CD configuration created"),console.log(),console.log(U.bold("Files created:")),console.log(` ${U.cyan(".github/workflows/test.yml")} - Run tests on push/PR`),console.log(` ${U.cyan(".github/workflows/publish.yml")} - Publish on git tags`),console.log(` ${U.cyan(".husky/pre-commit")} - Local pre-commit validation`),console.log(),console.log(U.bold("Next steps:")),console.log(U.gray(" 1. Install husky: pnpm husky install")),console.log(U.gray(" 2. Add GitHub secrets: KAVEN_LICENSE_KEY")),console.log(U.gray(" 3. Push to GitHub and watch workflows run")),o.dryRun&&(console.log(),console.log(U.yellow("(Dry-run: No files were actually created)")))}catch(r){n.fail("Failed to create CI/CD configuration"),console.error(U.red(r instanceof Error?r.message:String(r))),process.exit(1)}}function Ho(o){o.command("aiox").description("AIOX integration utilities").command("bootstrap").description("Run AIOX environment bootstrap in current project").option("--skip-aiox","Skip AIOX logic (for testing)").action(async t=>{let n=process.cwd();await nt(n,t)})}var Nr=()=>{let o=new Kr;o.name("kaven").description("The official CLI for the Kaven SaaS boilerplate ecosystem").version("0.4.2-alpha.0").addHelpText("after",`
|
|
33
198
|
Examples:
|
|
34
199
|
$ kaven init my-saas-app Bootstrap a new Kaven project
|
|
35
200
|
$ kaven auth login Authenticate with Kaven Marketplace
|
|
@@ -40,44 +205,13 @@ Examples:
|
|
|
40
205
|
|
|
41
206
|
Documentation: https://docs.kaven.site/cli
|
|
42
207
|
Support: https://github.com/kaven-co/kaven-cli/issues
|
|
43
|
-
`)
|
|
44
|
-
/**
|
|
45
|
-
* Init command — Bootstrap a new Kaven project
|
|
46
|
-
*/
|
|
47
|
-
program
|
|
48
|
-
.command("init [project-name]")
|
|
49
|
-
.description("Bootstrap a new Kaven project from the official template")
|
|
50
|
-
.option("--defaults", "Skip interactive prompts and use default values")
|
|
51
|
-
.option("--skip-install", "Skip running pnpm install after setup")
|
|
52
|
-
.option("--skip-git", "Skip git init and initial commit")
|
|
53
|
-
.option("--force", "Overwrite existing directory if it exists")
|
|
54
|
-
.option("--template <path>", "Path to a local template or custom git repository URL")
|
|
55
|
-
.option("--with-squad", "Install kaven-squad (AIOX) into squads/kaven-squad/ after scaffold")
|
|
56
|
-
.option("--skip-aiox", "Skip AIOX environment bootstrap")
|
|
57
|
-
.addHelpText("after", `
|
|
208
|
+
`),o.command("init [project-name]").description("Bootstrap a new Kaven project from the official template").option("--defaults","Skip interactive prompts and use default values").option("--skip-install","Skip running pnpm install after setup").option("--skip-git","Skip git init and initial commit").option("--force","Overwrite existing directory if it exists").option("--template <path>","Path to a local template or custom git repository URL").option("--with-squad","Install kaven-squad (AIOX) into squads/kaven-squad/ after scaffold").option("--skip-aiox","Skip AIOX environment bootstrap").addHelpText("after",`
|
|
58
209
|
Examples:
|
|
59
210
|
$ kaven init my-app Interactive setup
|
|
60
211
|
$ kaven init my-app --defaults Use defaults (no prompts)
|
|
61
212
|
$ kaven init my-app --skip-git Skip git initialization
|
|
62
213
|
$ kaven init my-app --with-squad Install kaven-squad for AIOX integration
|
|
63
|
-
`)
|
|
64
|
-
.action((name, opts) => (0, index_1.initProject)(name, {
|
|
65
|
-
defaults: opts.defaults,
|
|
66
|
-
skipInstall: opts.skipInstall,
|
|
67
|
-
skipGit: opts.skipGit,
|
|
68
|
-
force: opts.force,
|
|
69
|
-
template: opts.template,
|
|
70
|
-
withSquad: opts.withSquad,
|
|
71
|
-
skipAiox: opts.skipAiox,
|
|
72
|
-
}));
|
|
73
|
-
/**
|
|
74
|
-
* Modules Group
|
|
75
|
-
*/
|
|
76
|
-
const moduleCommand = program
|
|
77
|
-
.command("module")
|
|
78
|
-
.alias("m")
|
|
79
|
-
.description("Manage Kaven modules: install, remove, publish, activate, and diagnose")
|
|
80
|
-
.addHelpText("after", `
|
|
214
|
+
`).action((c,l)=>Co(c,{defaults:l.defaults,skipInstall:l.skipInstall,skipGit:l.skipGit,force:l.force,template:l.template,withSquad:l.withSquad,skipAiox:l.skipAiox}));let e=o.command("module").alias("m").description("Manage Kaven modules: install, remove, publish, activate, and diagnose").addHelpText("after",`
|
|
81
215
|
Examples:
|
|
82
216
|
$ kaven module doctor Check module integrity
|
|
83
217
|
$ kaven module doctor --fix Auto-fix detected issues
|
|
@@ -87,13 +221,7 @@ Examples:
|
|
|
87
221
|
$ kaven module list List schema modules and their status
|
|
88
222
|
$ kaven module activate billing Activate schema module (uncomment models)
|
|
89
223
|
$ kaven module deactivate billing Deactivate schema module (comment models)
|
|
90
|
-
`);
|
|
91
|
-
moduleCommand
|
|
92
|
-
.command("doctor")
|
|
93
|
-
.description("Run comprehensive project and module health checks")
|
|
94
|
-
.option("--fix", "Attempt to auto-fix detected issues (pnpm install, prisma generate, env vars)")
|
|
95
|
-
.option("--json", "Output results as machine-readable JSON")
|
|
96
|
-
.addHelpText("after", `
|
|
224
|
+
`);e.command("doctor").description("Run comprehensive project and module health checks").option("--fix","Attempt to auto-fix detected issues (pnpm install, prisma generate, env vars)").option("--json","Output results as machine-readable JSON").addHelpText("after",`
|
|
97
225
|
Exit codes:
|
|
98
226
|
0 All checks passed
|
|
99
227
|
1 One or more errors found
|
|
@@ -103,32 +231,15 @@ Examples:
|
|
|
103
231
|
$ kaven module doctor
|
|
104
232
|
$ kaven module doctor --fix
|
|
105
233
|
$ kaven module doctor --json
|
|
106
|
-
`)
|
|
107
|
-
.action((options) => (0, doctor_1.moduleDoctor)({ fix: options.fix, json: options.json }));
|
|
108
|
-
moduleCommand
|
|
109
|
-
.command("add <path>")
|
|
110
|
-
.description("Install a module from a local manifest file")
|
|
111
|
-
.addHelpText("after", `
|
|
234
|
+
`).action(c=>Vt({fix:c.fix,json:c.json})),e.command("add <path>").description("Install a module from a local manifest file").addHelpText("after",`
|
|
112
235
|
Examples:
|
|
113
236
|
$ kaven module add ./modules/payments/module.json
|
|
114
237
|
$ kaven module add /absolute/path/to/module.json
|
|
115
|
-
`)
|
|
116
|
-
.action((path) => (0, add_1.moduleAdd)(path));
|
|
117
|
-
moduleCommand
|
|
118
|
-
.command("remove <name>")
|
|
119
|
-
.description("Remove an installed module and clean up injected code")
|
|
120
|
-
.addHelpText("after", `
|
|
238
|
+
`).action(c=>Ht(c)),e.command("remove <name>").description("Remove an installed module and clean up injected code").addHelpText("after",`
|
|
121
239
|
Examples:
|
|
122
240
|
$ kaven module remove payments
|
|
123
241
|
$ kaven module remove notifications
|
|
124
|
-
`)
|
|
125
|
-
.action((name) => (0, remove_1.moduleRemove)(name));
|
|
126
|
-
moduleCommand
|
|
127
|
-
.command("publish")
|
|
128
|
-
.description("Publish the current directory as a module to Kaven Marketplace")
|
|
129
|
-
.option("--dry-run", "Validate and package the module without uploading")
|
|
130
|
-
.option("--changelog <text>", "Release notes for this version")
|
|
131
|
-
.addHelpText("after", `
|
|
242
|
+
`).action(c=>qt(c)),e.command("publish").description("Publish the current directory as a module to Kaven Marketplace").option("--dry-run","Validate and package the module without uploading").option("--changelog <text>","Release notes for this version").addHelpText("after",`
|
|
132
243
|
Requirements:
|
|
133
244
|
- module.json must exist in the current directory
|
|
134
245
|
- Must be authenticated: run 'kaven auth login' first
|
|
@@ -137,19 +248,7 @@ Examples:
|
|
|
137
248
|
$ kaven module publish
|
|
138
249
|
$ kaven module publish --dry-run
|
|
139
250
|
$ kaven module publish --changelog "Added dark mode support"
|
|
140
|
-
`)
|
|
141
|
-
.action((opts) => (0, publish_1.modulePublish)({
|
|
142
|
-
dryRun: opts.dryRun,
|
|
143
|
-
changelog: opts.changelog,
|
|
144
|
-
}));
|
|
145
|
-
moduleCommand
|
|
146
|
-
.command("activate <name> [root]")
|
|
147
|
-
.description("Activate a Kaven schema module by uncommenting its models in schema.extended.prisma")
|
|
148
|
-
.option("--with-deps", "Automatically activate required dependencies")
|
|
149
|
-
.option("--skip-migrate", "Skip db:generate and db:migrate after activation")
|
|
150
|
-
.option("--dry-run", "Show affected models without modifying schema")
|
|
151
|
-
.option("--yes", "Skip confirmation prompt")
|
|
152
|
-
.addHelpText("after", `
|
|
251
|
+
`).action(c=>Xt({dryRun:c.dryRun,changelog:c.changelog})),e.command("activate <name> [root]").description("Activate a Kaven schema module by uncommenting its models in schema.extended.prisma").option("--with-deps","Automatically activate required dependencies").option("--skip-migrate","Skip db:generate and db:migrate after activation").option("--dry-run","Show affected models without modifying schema").option("--yes","Skip confirmation prompt").addHelpText("after",`
|
|
153
252
|
Modules: billing, projects, notifications
|
|
154
253
|
|
|
155
254
|
Examples:
|
|
@@ -157,187 +256,50 @@ Examples:
|
|
|
157
256
|
$ kaven module activate projects
|
|
158
257
|
$ kaven module activate projects ./my-app
|
|
159
258
|
$ kaven module activate billing --with-deps
|
|
160
|
-
`)
|
|
161
|
-
.action((name, root, opts) => (0, activate_1.moduleActivate)(name, root, opts));
|
|
162
|
-
moduleCommand
|
|
163
|
-
.command("deactivate <name> [root]")
|
|
164
|
-
.description("Deactivate a Kaven schema module by commenting its models in schema.extended.prisma")
|
|
165
|
-
.option("--skip-migrate", "Skip db:generate and db:migrate")
|
|
166
|
-
.option("--dry-run", "Show affected models without modifying schema")
|
|
167
|
-
.option("--yes", "Skip confirmation prompt")
|
|
168
|
-
.addHelpText("after", `
|
|
259
|
+
`).action((c,l,d)=>ft(c,l,d)),e.command("deactivate <name> [root]").description("Deactivate a Kaven schema module by commenting its models in schema.extended.prisma").option("--skip-migrate","Skip db:generate and db:migrate").option("--dry-run","Show affected models without modifying schema").option("--yes","Skip confirmation prompt").addHelpText("after",`
|
|
169
260
|
Modules: billing, projects, notifications
|
|
170
261
|
|
|
171
262
|
Examples:
|
|
172
263
|
$ kaven module deactivate billing
|
|
173
264
|
$ kaven module deactivate projects
|
|
174
265
|
$ kaven module deactivate projects ./my-app
|
|
175
|
-
`)
|
|
176
|
-
.action((name, root, opts) => (0, activate_1.moduleDeactivate)(name, root, opts));
|
|
177
|
-
moduleCommand
|
|
178
|
-
.command("list [root]")
|
|
179
|
-
.description("List available Kaven schema modules with their status, models, and dependencies")
|
|
180
|
-
.addHelpText("after", `
|
|
266
|
+
`).action((c,l,d)=>eo(c,l,d)),e.command("list [root]").description("List available Kaven schema modules with their status, models, and dependencies").addHelpText("after",`
|
|
181
267
|
Examples:
|
|
182
268
|
$ kaven module list
|
|
183
269
|
$ kaven module list ./my-app
|
|
184
|
-
`)
|
|
185
|
-
.action((root) => (0, activate_1.moduleListActivation)(root));
|
|
186
|
-
/**
|
|
187
|
-
* Auth Group
|
|
188
|
-
*/
|
|
189
|
-
const authCommand = program
|
|
190
|
-
.command("auth")
|
|
191
|
-
.description("Manage authentication and session tokens")
|
|
192
|
-
.addHelpText("after", `
|
|
270
|
+
`).action(c=>to(c));let t=o.command("auth").description("Manage authentication and session tokens").addHelpText("after",`
|
|
193
271
|
Examples:
|
|
194
272
|
$ kaven auth login Start device code authentication flow
|
|
195
273
|
$ kaven auth whoami Show current user info
|
|
196
274
|
$ kaven auth logout End the local session
|
|
197
|
-
`);
|
|
198
|
-
authCommand
|
|
199
|
-
.command("login")
|
|
200
|
-
.description("Start the interactive device code authentication flow (RFC 8628)")
|
|
201
|
-
.action(() => (0, login_1.authLogin)());
|
|
202
|
-
authCommand
|
|
203
|
-
.command("logout")
|
|
204
|
-
.description("Clear the local authentication session")
|
|
205
|
-
.action(() => (0, logout_1.authLogout)());
|
|
206
|
-
authCommand
|
|
207
|
-
.command("whoami")
|
|
208
|
-
.description("Display information about the currently authenticated user")
|
|
209
|
-
.action(() => (0, whoami_1.authWhoami)());
|
|
210
|
-
/**
|
|
211
|
-
* Marketplace Group
|
|
212
|
-
*/
|
|
213
|
-
const marketplaceCommand = program
|
|
214
|
-
.command("marketplace")
|
|
215
|
-
.alias("mkt")
|
|
216
|
-
.alias("market")
|
|
217
|
-
.description("Explore, browse, and install modules from the Kaven Marketplace")
|
|
218
|
-
.addHelpText("after", `
|
|
275
|
+
`);t.command("login").description("Start the interactive device code authentication flow (RFC 8628)").action(()=>no()),t.command("logout").description("Clear the local authentication session").action(()=>ro()),t.command("whoami").description("Display information about the currently authenticated user").action(()=>ao());let n=o.command("marketplace").alias("mkt").alias("market").description("Explore, browse, and install modules from the Kaven Marketplace").addHelpText("after",`
|
|
219
276
|
Examples:
|
|
220
277
|
$ kaven marketplace list
|
|
221
278
|
$ kaven marketplace list --category auth --sort popular
|
|
222
279
|
$ kaven marketplace install payments
|
|
223
280
|
$ kaven marketplace browse
|
|
224
|
-
`);
|
|
225
|
-
marketplaceCommand
|
|
226
|
-
.command("list")
|
|
227
|
-
.description("List all modules available in the marketplace")
|
|
228
|
-
.option("--category <category>", "Filter modules by category")
|
|
229
|
-
.option("--sort <field>", "Sort order: newest (default), popular, name", "newest")
|
|
230
|
-
.option("--page <n>", "Page number (default: 1)", "1")
|
|
231
|
-
.option("--limit <n>", "Results per page (default: 20, max: 100)", "20")
|
|
232
|
-
.option("--json", "Output raw JSON instead of formatted table")
|
|
233
|
-
.action((options) => (0, list_1.marketplaceList)({
|
|
234
|
-
category: options.category,
|
|
235
|
-
sort: options.sort,
|
|
236
|
-
page: parseInt(options.page, 10),
|
|
237
|
-
limit: parseInt(options.limit, 10),
|
|
238
|
-
json: options.json ?? false,
|
|
239
|
-
}));
|
|
240
|
-
marketplaceCommand
|
|
241
|
-
.command("install <moduleId>")
|
|
242
|
-
.description("Download and install a module from the Kaven Marketplace")
|
|
243
|
-
.option("--version <ver>", "Install a specific version (default: latest)")
|
|
244
|
-
.option("--force", "Skip overwrite confirmation")
|
|
245
|
-
.option("--skip-env", "Skip environment variable injection")
|
|
246
|
-
.option("--skip-verify", "Skip Ed25519 signature verification (dev only)")
|
|
247
|
-
.option("--env-file <path>", "Target .env file (default: .env)")
|
|
248
|
-
.addHelpText("after", `
|
|
281
|
+
`);n.command("list").description("List all modules available in the marketplace").option("--category <category>","Filter modules by category").option("--sort <field>","Sort order: newest (default), popular, name","newest").option("--page <n>","Page number (default: 1)","1").option("--limit <n>","Results per page (default: 20, max: 100)","20").option("--json","Output raw JSON instead of formatted table").action(c=>io({category:c.category,sort:c.sort,page:parseInt(c.page,10),limit:parseInt(c.limit,10),json:c.json??!1})),n.command("install <moduleId>").description("Download and install a module from the Kaven Marketplace").option("--version <ver>","Install a specific version (default: latest)").option("--force","Skip overwrite confirmation").option("--skip-env","Skip environment variable injection").option("--skip-verify","Skip Ed25519 signature verification (dev only)").option("--env-file <path>","Target .env file (default: .env)").addHelpText("after",`
|
|
249
282
|
Examples:
|
|
250
283
|
$ kaven marketplace install payments
|
|
251
284
|
$ kaven marketplace install payments --version 1.2.0
|
|
252
285
|
$ kaven marketplace install auth --skip-env
|
|
253
286
|
$ kaven marketplace install my-module --skip-verify
|
|
254
|
-
`)
|
|
255
|
-
.action((moduleId, options) => (0, install_1.marketplaceInstall)(moduleId, {
|
|
256
|
-
version: options.version,
|
|
257
|
-
force: options.force ?? false,
|
|
258
|
-
skipEnv: options.skipEnv ?? false,
|
|
259
|
-
skipVerify: options.skipVerify ?? false,
|
|
260
|
-
envFile: options.envFile,
|
|
261
|
-
}));
|
|
262
|
-
marketplaceCommand
|
|
263
|
-
.command("browse")
|
|
264
|
-
.description("Interactive TUI module browser — explore modules by category")
|
|
265
|
-
.addHelpText("after", `
|
|
287
|
+
`).action((c,l)=>Ze(c,{version:l.version,force:l.force??!1,skipEnv:l.skipEnv??!1,skipVerify:l.skipVerify??!1,envFile:l.envFile})),n.command("browse").description("Interactive TUI module browser \u2014 explore modules by category").addHelpText("after",`
|
|
266
288
|
Navigate with arrow keys, press Enter to select.
|
|
267
289
|
Supports category filtering and pagination.
|
|
268
|
-
`)
|
|
269
|
-
.action(() => (0, browse_1.marketplaceBrowse)());
|
|
270
|
-
/**
|
|
271
|
-
* Upgrade Group — License tier upgrades and CLI updates
|
|
272
|
-
*/
|
|
273
|
-
const upgradeCommandGroup = program
|
|
274
|
-
.command("upgrade")
|
|
275
|
-
.description("Upgrade your license tier or CLI version")
|
|
276
|
-
.addHelpText("after", `
|
|
290
|
+
`).action(()=>po());let r=o.command("upgrade").description("Upgrade your license tier or CLI version").addHelpText("after",`
|
|
277
291
|
Examples:
|
|
278
292
|
$ kaven upgrade Upgrade license tier
|
|
279
293
|
$ kaven upgrade check Check for CLI updates
|
|
280
294
|
$ kaven upgrade install Install latest CLI version
|
|
281
|
-
`);
|
|
282
|
-
upgradeCommandGroup
|
|
283
|
-
.command("tier")
|
|
284
|
-
.description("Upgrade your Kaven license to a higher tier (default)")
|
|
285
|
-
.option("--no-browser", "Print the checkout URL instead of opening the browser")
|
|
286
|
-
.action((opts) => (0, index_2.upgradeCommand)({
|
|
287
|
-
browser: opts.browser !== false,
|
|
288
|
-
}));
|
|
289
|
-
upgradeCommandGroup
|
|
290
|
-
.command("check")
|
|
291
|
-
.description("Check for Kaven CLI updates")
|
|
292
|
-
.action(() => (0, index_2.upgradeCheck)());
|
|
293
|
-
upgradeCommandGroup
|
|
294
|
-
.command("install")
|
|
295
|
-
.description("Install the latest Kaven CLI version")
|
|
296
|
-
.action(() => (0, index_2.upgradeInstall)());
|
|
297
|
-
/**
|
|
298
|
-
* Telemetry Group
|
|
299
|
-
*/
|
|
300
|
-
const telemetryCommand = program
|
|
301
|
-
.command("telemetry")
|
|
302
|
-
.description("View observability and command audit logs");
|
|
303
|
-
telemetryCommand
|
|
304
|
-
.command("view")
|
|
305
|
-
.description("Display the most recent local telemetry events")
|
|
306
|
-
.option("-l, --limit <number>", "Number of events to display", "10")
|
|
307
|
-
.action((options) => (0, view_1.telemetryView)(parseInt(options.limit)));
|
|
308
|
-
/**
|
|
309
|
-
* License Group
|
|
310
|
-
*/
|
|
311
|
-
program.addCommand((0, index_js_1.buildLicenseCommand)());
|
|
312
|
-
/**
|
|
313
|
-
* Cache Group
|
|
314
|
-
*/
|
|
315
|
-
const cacheCommand = program
|
|
316
|
-
.command("cache")
|
|
317
|
-
.description("Manage the local API response cache")
|
|
318
|
-
.addHelpText("after", `
|
|
295
|
+
`);r.command("tier").description("Upgrade your Kaven license to a higher tier (default)").option("--no-browser","Print the checkout URL instead of opening the browser").action(c=>Io({browser:c.browser!==!1})),r.command("check").description("Check for Kaven CLI updates").action(()=>Ct()),r.command("install").description("Install the latest Kaven CLI version").action(()=>Pt()),o.command("telemetry").description("View observability and command audit logs").command("view").description("Display the most recent local telemetry events").option("-l, --limit <number>","Number of events to display","10").action(c=>mo(parseInt(c.limit))),o.addCommand(wo());let i=o.command("cache").description("Manage the local API response cache").addHelpText("after",`
|
|
319
296
|
Cache directory: ~/.kaven/cache (max 50 MB)
|
|
320
297
|
Cached data: module listings (24h TTL), manifests (7d), license status (1h)
|
|
321
298
|
|
|
322
299
|
Examples:
|
|
323
300
|
$ kaven cache status
|
|
324
301
|
$ kaven cache clear
|
|
325
|
-
`);
|
|
326
|
-
cacheCommand
|
|
327
|
-
.command("status")
|
|
328
|
-
.description("Show cache statistics (size, entry count, age)")
|
|
329
|
-
.action(() => (0, index_3.cacheStatus)());
|
|
330
|
-
cacheCommand
|
|
331
|
-
.command("clear")
|
|
332
|
-
.description("Delete all locally cached API responses")
|
|
333
|
-
.action(() => (0, index_3.cacheClear)());
|
|
334
|
-
/**
|
|
335
|
-
* Config Group — Manage Kaven CLI configuration
|
|
336
|
-
*/
|
|
337
|
-
const configCommand = program
|
|
338
|
-
.command("config")
|
|
339
|
-
.description("Manage Kaven CLI configuration")
|
|
340
|
-
.addHelpText("after", `
|
|
302
|
+
`);i.command("status").description("Show cache statistics (size, entry count, age)").action(()=>_o()),i.command("clear").description("Delete all locally cached API responses").action(()=>Do());let s=o.command("config").description("Manage Kaven CLI configuration").addHelpText("after",`
|
|
341
303
|
Config file: ~/.kaven/config.json
|
|
342
304
|
|
|
343
305
|
Examples:
|
|
@@ -348,31 +310,7 @@ Examples:
|
|
|
348
310
|
$ kaven config features
|
|
349
311
|
$ kaven config features --tier complete
|
|
350
312
|
$ kaven config features --list
|
|
351
|
-
`);
|
|
352
|
-
configCommand
|
|
353
|
-
.command("set <key> <value>")
|
|
354
|
-
.description("Set a configuration value")
|
|
355
|
-
.action((key, value) => (0, index_4.configSet)(key, value));
|
|
356
|
-
configCommand
|
|
357
|
-
.command("get <key>")
|
|
358
|
-
.description("Get a configuration value")
|
|
359
|
-
.option("--json", "Output as JSON")
|
|
360
|
-
.action((key, opts) => (0, index_4.configGet)(key, { json: opts.json }));
|
|
361
|
-
configCommand
|
|
362
|
-
.command("view")
|
|
363
|
-
.description("Display all configuration")
|
|
364
|
-
.option("--json", "Output as JSON")
|
|
365
|
-
.action((opts) => (0, index_4.configView)({ json: opts.json }));
|
|
366
|
-
configCommand
|
|
367
|
-
.command("reset")
|
|
368
|
-
.description("Reset configuration to defaults")
|
|
369
|
-
.action(() => (0, index_4.configReset)());
|
|
370
|
-
configCommand
|
|
371
|
-
.command("features")
|
|
372
|
-
.description("Interactive TUI to select and configure the 60 framework capabilities (feature flags)")
|
|
373
|
-
.option("--tier <tier>", "Apply a preset tier directly without prompts: starter | complete | pro | enterprise")
|
|
374
|
-
.option("--list", "List all available capabilities grouped by category, without modifying anything")
|
|
375
|
-
.addHelpText("after", `
|
|
313
|
+
`);s.command("set <key> <value>").description("Set a configuration value").action((c,l)=>Lo(c,l)),s.command("get <key>").description("Get a configuration value").option("--json","Output as JSON").action((c,l)=>Oo(c,{json:l.json})),s.command("view").description("Display all configuration").option("--json","Output as JSON").action(c=>Fo({json:c.json})),s.command("reset").description("Reset configuration to defaults").action(()=>Ko()),s.command("features").description("Interactive TUI to select and configure the 60 framework capabilities (feature flags)").option("--tier <tier>","Apply a preset tier directly without prompts: starter | complete | pro | enterprise").option("--list","List all available capabilities grouped by category, without modifying anything").addHelpText("after",`
|
|
376
314
|
Output: packages/database/prisma/seeds/capabilities.seed.ts (relative to cwd)
|
|
377
315
|
|
|
378
316
|
Examples:
|
|
@@ -383,19 +321,7 @@ Examples:
|
|
|
383
321
|
|
|
384
322
|
After generating the seed file:
|
|
385
323
|
$ pnpm prisma db seed
|
|
386
|
-
`)
|
|
387
|
-
.action((opts) => (0, features_1.configFeatures)({
|
|
388
|
-
tier: opts.tier,
|
|
389
|
-
list: opts.list ?? false,
|
|
390
|
-
}));
|
|
391
|
-
/**
|
|
392
|
-
* Init CI — Initialize CI/CD workflows
|
|
393
|
-
*/
|
|
394
|
-
program
|
|
395
|
-
.command("init-ci")
|
|
396
|
-
.description("Initialize GitHub Actions CI/CD workflows")
|
|
397
|
-
.option("--dry-run", "Show what would be created without writing files")
|
|
398
|
-
.addHelpText("after", `
|
|
324
|
+
`).action(c=>Bo({tier:c.tier,list:c.list??!1})),o.command("init-ci").description("Initialize GitHub Actions CI/CD workflows").option("--dry-run","Show what would be created without writing files").addHelpText("after",`
|
|
399
325
|
Creates:
|
|
400
326
|
- .github/workflows/test.yml Run tests on push/PR
|
|
401
327
|
- .github/workflows/publish.yml Publish modules on git tags
|
|
@@ -404,16 +330,4 @@ Creates:
|
|
|
404
330
|
Examples:
|
|
405
331
|
$ kaven init-ci Interactive setup
|
|
406
332
|
$ kaven init-ci --dry-run Show what would be created
|
|
407
|
-
`)
|
|
408
|
-
.action((opts) => (0, index_5.initCi)({ dryRun: opts.dryRun }));
|
|
409
|
-
/**
|
|
410
|
-
* AIOX Commands
|
|
411
|
-
*/
|
|
412
|
-
(0, aiox_1.registerAioxCommand)(program);
|
|
413
|
-
program.parse(process.argv);
|
|
414
|
-
};
|
|
415
|
-
exports.main = main;
|
|
416
|
-
// Execute main if this is the entry point
|
|
417
|
-
if (require.main === module) {
|
|
418
|
-
(0, exports.main)();
|
|
419
|
-
}
|
|
333
|
+
`).action(c=>Go({dryRun:c.dryRun})),Ho(o),o.parse(process.argv)},Ur=process.argv[1]&&(process.argv[1].endsWith("/kaven")||process.argv[1].endsWith("/index.ts")||process.argv[1].endsWith("/index.js"));Ur&&Nr();export{Nr as main};
|