kaven-cli 0.7.0 → 0.8.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.
Files changed (3) hide show
  1. package/README.md +36 -1
  2. package/dist/index.js +91 -89
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -25,6 +25,7 @@ Built for precision and speed, it is now a **Pure ESM** tool optimized for moder
25
25
  - [Schema Activation Engine (`module`)](#schema-activation-engine-module)
26
26
  - [Feature Flags & Capabilities (`config features`)](#feature-flags--capabilities-config-features)
27
27
  - [Marketplace Integration](#marketplace-integration)
28
+ - [Update & Upgrade](#update--upgrade)
28
29
  - [Architecture Deep Dive](#architecture-deep-dive)
29
30
  - [Schema Activation Logic](#schema-activation-logic)
30
31
  - [AIOX Squad Integration](#aiox-squad-integration)
@@ -153,6 +154,40 @@ kaven marketplace list --category auth
153
154
 
154
155
  ---
155
156
 
157
+ ### Update & Upgrade
158
+
159
+ Kaven follows the Linux `apt` convention — **update** manages software versions, **upgrade** manages your plan.
160
+
161
+ #### `kaven update` — Update CLI and modules
162
+
163
+ ```bash
164
+ kaven update # check for updates: CLI + all installed modules
165
+ kaven update --core # check and update CLI only
166
+ kaven update --module X # update a specific installed module
167
+ kaven update --all # apply all available updates
168
+ kaven update --check # check without applying (dry run)
169
+ ```
170
+
171
+ > Works offline: uses local MSW handlers when marketplace is unreachable.
172
+
173
+ #### `kaven module update` — Update a specific module (C4.1)
174
+
175
+ ```bash
176
+ kaven module update payments # update to latest
177
+ kaven module update payments@1.0.3 # update to specific version
178
+ ```
179
+
180
+ #### `kaven upgrade` — License plan upgrade only
181
+
182
+ ```bash
183
+ kaven upgrade # opens Stripe checkout to upgrade your plan tier
184
+ kaven upgrade check # check if a newer CLI version is on npm
185
+ ```
186
+
187
+ > `kaven upgrade` is **not** for updating software. It is exclusively for moving between Starter → Complete → Pro license tiers via Stripe.
188
+
189
+ ---
190
+
156
191
  ## Architecture Deep Dive
157
192
 
158
193
  ### Schema Activation Logic
@@ -227,7 +262,7 @@ git clone https://github.com/kaven-co/kaven-cli
227
262
  cd kaven-cli
228
263
  pnpm install
229
264
 
230
- # 2. Run the full test suite (318+ tests)
265
+ # 2. Run the full test suite (334 tests)
231
266
  pnpm test
232
267
 
233
268
  # 3. Run linting and type-checking
package/dist/index.js CHANGED
@@ -1,103 +1,105 @@
1
1
  #!/usr/bin/env node
2
- import{a as lo,b as uo,c as po,d as ct,e as Ge,f as de,g as V}from"./chunk-JHLQ46NG.js";import{Command as Ca}from"commander";import E from"chalk";import{execSync as go}from"child_process";import ho from"path";import dt from"fs-extra";import S from"fs-extra";import B from"path";import $n from"os";var lt=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=B.join(this.projectRoot,n);if(!await S.pathExists(a)){e.push({type:"anchor",severity:"warning",message:`File not found: ${n}`,file:n,fixable:!1});continue}(await S.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=B.join(this.projectRoot,".kaven/modules",r.name,"module.json");if(!await S.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=B.join(this.projectRoot,s.file);if(!await S.pathExists(c)){e.push({type:"marker",severity:"error",message:`Injection target not found: ${s.file}`,file:s.file,fixable:!1});continue}let l=await S.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=B.join(this.projectRoot,"package.json");if(!await S.pathExists(r))return e.push({type:"dependency",severity:"error",message:"package.json not found",fixable:!1}),e;let a=await S.readJSON(r);for(let i of n){let s=B.join(this.projectRoot,".kaven/modules",i.name,"module.json");if(await S.pathExists(s))try{let c=await this.manifestParser.parse(s);for(let l of c.dependencies.npm){let[d]=l.split("@"),m=a.dependencies?.[d],p=a.devDependencies?.[d];!m&&!p&&e.push({type:"dependency",severity:"warning",message:`Missing npm dependency: ${l}`,fixable:!0})}}catch{}}return e}async checkSchemaMerge(){let e=[],t=B.join(this.projectRoot,"packages/database/prisma/schema.base.prisma");if(!await S.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=B.dirname(t);try{let r=await S.readdir(n);for(let a of r){if(!a.endsWith(".prisma"))continue;let i=B.join(n,a);(await S.readFile(i,"utf-8")).includes("<<<<<<<")&&e.push({type:"marker",severity:"error",message:`Merge conflict detected in schema file: ${a}`,file:B.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=B.join(this.projectRoot,".env.example"),n=B.join(this.projectRoot,".env");if(!await S.pathExists(t))return e.push({type:"dependency",severity:"info",message:".env.example not found \u2014 skipping env completeness check",fixable:!1}),e;if(!await S.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 S.readFile(t,"utf-8"),a=await S.readFile(n,"utf-8"),i=d=>{let m=new Set;for(let p of d.split(`
3
- `)){let u=p.trim();if(u.startsWith("#")||!u.includes("="))continue;let g=u.split("=")[0].trim();g&&m.add(g)}return m},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=B.join($n.homedir(),".kaven","license.json");if(!await S.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 S.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=B.join(this.projectRoot,"package.json");if(!await S.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 S.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=B.join(this.projectRoot,"node_modules/@prisma/client"),n=B.join(this.projectRoot,"prisma/schema.prisma");if(!await S.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 S.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 S.stat(n),a=await S.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=B.join(this.projectRoot,"kaven.json");if(!await S.pathExists(e))return{modules:[]};try{return await S.readJSON(e)}catch{return{modules:[]}}}};function He(o){return{moduleName:o,beginMarker:`// [KAVEN_MODULE:${o} BEGIN]`,endMarker:`// [KAVEN_MODULE:${o} END]`}}var ae=class{hasModule(e,t){let n=He(t);return e.includes(n.beginMarker)&&e.includes(n.endMarker)}detectMarkers(e,t){let n=He(t),r=e.split(`
2
+ import{a as mo,b as fo,c as go,d as lt,e as He,f as pe,g as B}from"./chunk-JHLQ46NG.js";import{Command as Aa}from"commander";import E from"chalk";import{execSync as wo}from"child_process";import vo from"path";import ut from"fs-extra";import C from"fs-extra";import J from"path";import jn from"os";var dt=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=J.join(this.projectRoot,n);if(!await C.pathExists(a)){e.push({type:"anchor",severity:"warning",message:`File not found: ${n}`,file:n,fixable:!1});continue}(await C.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=J.join(this.projectRoot,".kaven/modules",r.name,"module.json");if(!await C.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=J.join(this.projectRoot,s.file);if(!await C.pathExists(c)){e.push({type:"marker",severity:"error",message:`Injection target not found: ${s.file}`,file:s.file,fixable:!1});continue}let l=await C.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=J.join(this.projectRoot,"package.json");if(!await C.pathExists(r))return e.push({type:"dependency",severity:"error",message:"package.json not found",fixable:!1}),e;let a=await C.readJSON(r);for(let i of n){let s=J.join(this.projectRoot,".kaven/modules",i.name,"module.json");if(await C.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],m=a.devDependencies?.[d];!p&&!m&&e.push({type:"dependency",severity:"warning",message:`Missing npm dependency: ${l}`,fixable:!0})}}catch{}}return e}async checkSchemaMerge(){let e=[],t=J.join(this.projectRoot,"packages/database/prisma/schema.base.prisma");if(!await C.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=J.dirname(t);try{let r=await C.readdir(n);for(let a of r){if(!a.endsWith(".prisma"))continue;let i=J.join(n,a);(await C.readFile(i,"utf-8")).includes("<<<<<<<")&&e.push({type:"marker",severity:"error",message:`Merge conflict detected in schema file: ${a}`,file:J.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=J.join(this.projectRoot,".env.example"),n=J.join(this.projectRoot,".env");if(!await C.pathExists(t))return e.push({type:"dependency",severity:"info",message:".env.example not found \u2014 skipping env completeness check",fixable:!1}),e;if(!await C.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 C.readFile(t,"utf-8"),a=await C.readFile(n,"utf-8"),i=d=>{let p=new Set;for(let m of d.split(`
3
+ `)){let u=m.trim();if(u.startsWith("#")||!u.includes("="))continue;let f=u.split("=")[0].trim();f&&p.add(f)}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=J.join(jn.homedir(),".kaven","license.json");if(!await C.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 C.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=J.join(this.projectRoot,"package.json");if(!await C.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 C.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=J.join(this.projectRoot,"node_modules/@prisma/client"),n=J.join(this.projectRoot,"prisma/schema.prisma");if(!await C.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 C.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 C.stat(n),a=await C.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=J.join(this.projectRoot,"kaven.json");if(!await C.pathExists(e))return{modules:[]};try{return await C.readJSON(e)}catch{return{modules:[]}}}};function Ge(o){return{moduleName:o,beginMarker:`// [KAVEN_MODULE:${o} BEGIN]`,endMarker:`// [KAVEN_MODULE:${o} END]`}}var se=class{hasModule(e,t){let n=Ge(t);return e.includes(n.beginMarker)&&e.includes(n.endMarker)}detectMarkers(e,t){let n=Ge(t),r=e.split(`
4
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=He(n),i=`
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=Ge(n),i=`
6
6
  ${a.beginMarker}
7
7
  ${r}
8
8
  ${a.endMarker}
9
- `;return e.replace(t,`${t}${i}`)}removeModule(e,t){let n=He(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 fo from"fs-extra";import{z as v}from"zod";var Pn=v.object({npm:v.array(v.string()).default([]),peerModules:v.array(v.string()).default([]),kavenVersion:v.string().default(">=0.1.0")}),Tt=v.object({source:v.string(),dest:v.string()}),Mn=v.object({backend:v.array(Tt).default([]),frontend:v.array(Tt).default([]),database:v.array(Tt).default([])}),An=v.object({file:v.string(),anchor:v.string(),code:v.string(),moduleName:v.string().optional()}),jn=v.object({postInstall:v.string().nullable().default(null),preRemove:v.string().nullable().default(null)}),In=v.object({key:v.string(),required:v.boolean().default(!1),example:v.string().optional()}),mo=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:Pn,files:Mn,injections:v.array(An),scripts:jn,env:v.array(In).default([])});import{ZodError as Tn}from"zod";var Te=class{async parse(e){if(!await fo.pathExists(e))throw new Error(`Manifest not found: ${e}`);let t=await fo.readFile(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error(`Failed to parse manifest JSON: ${e}`)}try{return mo.parse(n)}catch(r){throw r instanceof Tn?new Error(`Invalid manifest:
9
+ `;return e.replace(t,`${t}${i}`)}removeModule(e,t){let n=Ge(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 yo from"fs-extra";import{z as k}from"zod";var Tn=k.object({npm:k.array(k.string()).default([]),peerModules:k.array(k.string()).default([]),kavenVersion:k.string().default(">=0.1.0")}),Rt=k.object({source:k.string(),dest:k.string()}),In=k.object({backend:k.array(Rt).default([]),frontend:k.array(Rt).default([]),database:k.array(Rt).default([])}),Rn=k.object({file:k.string(),anchor:k.string(),code:k.string(),moduleName:k.string().optional()}),Dn=k.object({postInstall:k.string().nullable().default(null),preRemove:k.string().nullable().default(null)}),_n=k.object({key:k.string(),required:k.boolean().default(!1),example:k.string().optional()}),ho=k.object({name:k.string().min(1),version:k.string().regex(/^\d+\.\d+\.\d+$/),description:k.string().optional(),author:k.string().default("Kaven"),license:k.string().default("Proprietary"),dependencies:Tn,files:In,injections:k.array(Rn),scripts:Dn,env:k.array(_n).default([])});import{ZodError as Ln}from"zod";var Ie=class{async parse(e){if(!await yo.pathExists(e))throw new Error(`Manifest not found: ${e}`);let t=await yo.readFile(e,"utf-8"),n;try{n=JSON.parse(t)}catch{throw new Error(`Failed to parse manifest JSON: ${e}`)}try{return ho.parse(n)}catch(r){throw r instanceof Ln?new Error(`Invalid manifest:
10
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 Rn(o){switch(o){case"error":return E.red("[ERROR]");case"warning":return E.yellow("[WARN] ");case"info":return E.cyan("[INFO] ");default:return E.green("[OK] ")}}async function Dn(o,e){let t=o.filter(n=>n.fixable);if(t.length===0){console.log(E.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(E.blue(` Fixing: ${n.message}`));try{go("pnpm install",{cwd:e,stdio:"inherit"}),console.log(E.green(" \u2713 pnpm install completed"))}catch{console.log(E.red(" \u2717 pnpm install failed"))}continue}if(r.includes("prisma")){console.log(E.blue(` Fixing: ${n.message}`));try{go("npx prisma generate",{cwd:e,stdio:"inherit"}),console.log(E.green(" \u2713 npx prisma generate completed"))}catch{console.log(E.red(" \u2717 npx prisma generate failed"))}continue}if(r.includes("missing env vars")&&n.file===".env"){let a=ho.join(e,".env"),i=ho.join(e,".env.example");console.log(E.blue(` Fixing: ${n.message}`));try{let s=await dt.readFile(i,"utf-8"),c=await dt.pathExists(a)?await dt.readFile(a,"utf-8"):"",l=u=>{let g=new Set;for(let k of u.split(`
12
- `)){let C=k.trim();if(C.startsWith("#")||!C.includes("="))continue;let F=C.split("=")[0].trim();F&&g.add(F)}return g},d=l(s),m=l(c),p=`
11
+ `)}};function On(o){switch(o){case"error":return E.red("[ERROR]");case"warning":return E.yellow("[WARN] ");case"info":return E.cyan("[INFO] ");default:return E.green("[OK] ")}}async function Fn(o,e){let t=o.filter(n=>n.fixable);if(t.length===0){console.log(E.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(E.blue(` Fixing: ${n.message}`));try{wo("pnpm install",{cwd:e,stdio:"inherit"}),console.log(E.green(" \u2713 pnpm install completed"))}catch{console.log(E.red(" \u2717 pnpm install failed"))}continue}if(r.includes("prisma")){console.log(E.blue(` Fixing: ${n.message}`));try{wo("npx prisma generate",{cwd:e,stdio:"inherit"}),console.log(E.green(" \u2713 npx prisma generate completed"))}catch{console.log(E.red(" \u2717 npx prisma generate failed"))}continue}if(r.includes("missing env vars")&&n.file===".env"){let a=vo.join(e,".env"),i=vo.join(e,".env.example");console.log(E.blue(` Fixing: ${n.message}`));try{let s=await ut.readFile(i,"utf-8"),c=await ut.pathExists(a)?await ut.readFile(a,"utf-8"):"",l=u=>{let f=new Set;for(let w of u.split(`
12
+ `)){let S=w.trim();if(S.startsWith("#")||!S.includes("="))continue;let I=S.split("=")[0].trim();I&&f.add(I)}return f},d=l(s),p=l(c),m=`
13
13
  # Added by kaven doctor --fix
14
- `;for(let u of d)m.has(u)||(p+=`${u}=PLACEHOLDER
15
- `);await dt.appendFile(a,p),console.log(E.green(" \u2713 Placeholder env vars appended to .env"))}catch{console.log(E.red(" \u2717 Could not append env vars"))}continue}console.log(E.yellow(` Manual action required: ${n.message}`))}}async function yo(o){o.json||console.log(E.blue(`Running module doctor...
16
- `));let e=new ae,t=new Te,n=new lt(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(E.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=Rn(s.severity);console.log(`${c} ${s.message}`),s.file&&console.log(E.gray(` file: ${s.file}`)),s.fixable&&!o.fix&&console.log(E.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(E.green("[OK] All checks passed! Your project is healthy.")):(a.length>0&&console.log(E.red(`[ERROR] Found ${a.length} error(s)`)),i.length>0&&console.log(E.yellow(`[WARN] Found ${i.length} warning(s)`)),o.fix||(console.log(E.gray(`
14
+ `;for(let u of d)p.has(u)||(m+=`${u}=PLACEHOLDER
15
+ `);await ut.appendFile(a,m),console.log(E.green(" \u2713 Placeholder env vars appended to .env"))}catch{console.log(E.red(" \u2717 Could not append env vars"))}continue}console.log(E.yellow(` Manual action required: ${n.message}`))}}async function ko(o){o.json||console.log(E.blue(`Running module doctor...
16
+ `));let e=new se,t=new Ie,n=new dt(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(E.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=On(s.severity);console.log(`${c} ${s.message}`),s.file&&console.log(E.gray(` file: ${s.file}`)),s.fixable&&!o.fix&&console.log(E.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(E.green("[OK] All checks passed! Your project is healthy.")):(a.length>0&&console.log(E.red(`[ERROR] Found ${a.length} error(s)`)),i.length>0&&console.log(E.yellow(`[WARN] Found ${i.length} warning(s)`)),o.fix||(console.log(E.gray(`
17
17
  Tip: Run with --fix to attempt automatic repairs`)),console.log(E.gray("Try: kaven module doctor --fix")))),o.fix&&(console.log(),console.log(E.blue(`Applying auto-fixes...
18
- `)),await Dn(r,process.cwd()),console.log(E.green(`
19
- Auto-fix completed.`))),a.length>0&&process.exit(1),i.length>0&&process.exit(2)}import vo from"chalk";import Un from"ora";import Xe from"path";import De from"fs-extra";import oe from"fs-extra";import ne from"path";import{glob as _n}from"glob";var qe=class{constructor(e,t=".agent/backups"){this.projectRoot=e;this.backupDir=ne.join(e,t),this.backupId=`backup_${Date.now()}`}backupDir;backupId;filesToBackup=[];async backup(e){let t=ne.join(this.backupDir,this.backupId);await oe.ensureDir(t);for(let n of e){let r=ne.resolve(this.projectRoot,n);if(!await oe.pathExists(r))throw new Error(`File not found for backup: ${n}`);let a=ne.relative(this.projectRoot,r),i=ne.join(t,a);await oe.ensureDir(ne.dirname(i)),await oe.copy(r,i),this.filesToBackup.push(r)}console.log(`\u{1F4E6} Backup created: ${this.backupId}`)}async rollback(){let e=ne.join(this.backupDir,this.backupId);if(!await oe.pathExists(e))throw new Error(`Backup not found: ${this.backupId}`);let t=await _n(`${e}/**/*`,{nodir:!0});for(let n of t){let r=ne.relative(e,n),a=ne.join(this.projectRoot,r);await oe.ensureDir(ne.dirname(a)),await oe.copy(n,a,{overwrite:!0})}console.log(`\u267B\uFE0F Rollback complete: ${this.backupId}`)}async commit(){let e=ne.join(this.backupDir,this.backupId);await oe.pathExists(e)&&await oe.remove(e),console.log("\u2705 Transaction committed")}getBackupId(){return this.backupId}async cleanup(){if(!await oe.pathExists(this.backupDir))return;let e=await oe.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 oe.remove(ne.join(this.backupDir,r))}}}};import Ln from"child_process";import On from"readline";import ut from"chalk";var We=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(ut.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=ut.dim(`[${t}] `);i.stdout?.on("data",l=>{process.stdout.write(s+l.toString())}),i.stderr?.on("data",l=>{process.stderr.write(s+ut.yellow(l.toString()))});let c=setTimeout(()=>{console.warn(ut.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=On.createInterface({input:process.stdin,output:process.stdout});n.question(`
21
- ${e} [y/N] `,r=>{n.close(),t(r.toLowerCase()==="y"||r.toLowerCase()==="yes")})})}};import Re from"fs-extra";import Rt from"path";import Dt from"chalk";var ye=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 Re.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 qe(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 We;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(Dt.yellow(`
22
- \u26A0 PostInstall script failed: ${c}`)),console.warn(Dt.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 qe(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 We;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(Dt.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=Rt.join(this.projectRoot,e.file),n=await Re.readFile(t,"utf-8"),r=this.markerService.injectModule(n,e.anchor,e.moduleName||"unnamed",e.code);await Re.writeFile(t,r)}async removeCode(e,t){let n=Rt.join(this.projectRoot,e),r=await Re.readFile(n,"utf-8"),a=this.markerService.removeModule(r,t);await Re.writeFile(n,a)}async readManifest(e){try{let t=await Re.readFile(Rt.join(e,"module.json"),"utf-8");return JSON.parse(t)}catch{return null}}};import pt from"fs-extra";import wo from"path";import Fn from"os";var A=class o{static instance;logPath;buffer=[];constructor(){this.logPath=wo.join(Fn.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=wo.dirname(this.logPath);await pt.ensureDir(e);let t=this.buffer.map(n=>JSON.stringify(n)).join(`
18
+ `)),await Fn(r,process.cwd()),console.log(E.green(`
19
+ Auto-fix completed.`))),a.length>0&&process.exit(1),i.length>0&&process.exit(2)}import xo from"chalk";import Bn from"ora";import Xe from"path";import De from"fs-extra";import re from"fs-extra";import ae from"path";import{glob as Un}from"glob";var qe=class{constructor(e,t=".agent/backups"){this.projectRoot=e;this.backupDir=ae.join(e,t),this.backupId=`backup_${Date.now()}`}backupDir;backupId;filesToBackup=[];async backup(e){let t=ae.join(this.backupDir,this.backupId);await re.ensureDir(t);for(let n of e){let r=ae.resolve(this.projectRoot,n);if(!await re.pathExists(r))throw new Error(`File not found for backup: ${n}`);let a=ae.relative(this.projectRoot,r),i=ae.join(t,a);await re.ensureDir(ae.dirname(i)),await re.copy(r,i),this.filesToBackup.push(r)}console.log(`\u{1F4E6} Backup created: ${this.backupId}`)}async rollback(){let e=ae.join(this.backupDir,this.backupId);if(!await re.pathExists(e))throw new Error(`Backup not found: ${this.backupId}`);let t=await Un(`${e}/**/*`,{nodir:!0});for(let n of t){let r=ae.relative(e,n),a=ae.join(this.projectRoot,r);await re.ensureDir(ae.dirname(a)),await re.copy(n,a,{overwrite:!0})}console.log(`\u267B\uFE0F Rollback complete: ${this.backupId}`)}async commit(){let e=ae.join(this.backupDir,this.backupId);await re.pathExists(e)&&await re.remove(e),console.log("\u2705 Transaction committed")}getBackupId(){return this.backupId}async cleanup(){if(!await re.pathExists(this.backupDir))return;let e=await re.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 re.remove(ae.join(this.backupDir,r))}}}};import Nn from"child_process";import Kn from"readline";import pt from"chalk";var We=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(pt.dim(` Skipping ${t} script.`));return}return new Promise((r,a)=>{let i=Nn.spawn(e.command,e.args??[],{cwd:e.cwd,stdio:["ignore","pipe","pipe"],shell:!0}),s=pt.dim(`[${t}] `);i.stdout?.on("data",l=>{process.stdout.write(s+l.toString())}),i.stderr?.on("data",l=>{process.stderr.write(s+pt.yellow(l.toString()))});let c=setTimeout(()=>{console.warn(pt.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=Kn.createInterface({input:process.stdin,output:process.stdout});n.question(`
21
+ ${e} [y/N] `,r=>{n.close(),t(r.toLowerCase()==="y"||r.toLowerCase()==="yes")})})}};import Re from"fs-extra";import Dt from"path";import _t from"chalk";var ye=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 Re.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 qe(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 We;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(_t.yellow(`
22
+ \u26A0 PostInstall script failed: ${c}`)),console.warn(_t.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 qe(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 We;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(_t.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=Dt.join(this.projectRoot,e.file),n=await Re.readFile(t,"utf-8"),r=this.markerService.injectModule(n,e.anchor,e.moduleName||"unnamed",e.code);await Re.writeFile(t,r)}async removeCode(e,t){let n=Dt.join(this.projectRoot,e),r=await Re.readFile(n,"utf-8"),a=this.markerService.removeModule(r,t);await Re.writeFile(n,a)}async readManifest(e){try{let t=await Re.readFile(Dt.join(e,"module.json"),"utf-8");return JSON.parse(t)}catch{return null}}};import mt from"fs-extra";import bo from"path";import Vn from"os";var j=class o{static instance;logPath;buffer=[];constructor(){this.logPath=bo.join(Vn.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=bo.dirname(this.logPath);await mt.ensureDir(e);let t=this.buffer.map(n=>JSON.stringify(n)).join(`
24
24
  `)+`
25
- `;await pt.appendFile(this.logPath,t,"utf8"),this.buffer=[]}catch(e){console.debug("Erro ao gravar telemetria:",e)}}async getRecentEvents(e=20){if(!await pt.pathExists(this.logPath))return[];try{return(await pt.readFile(this.logPath,"utf8")).trim().split(`
26
- `).reverse().slice(0,e).map(n=>JSON.parse(n))}catch{return[]}}};async function ko(o,e){let t=A.getInstance(),n=Date.now();t.capture("cli.module.add.start",{manifestPath:o});let r=e||process.cwd(),a=Un("Preparando instala\xE7\xE3o do m\xF3dulo...").start();try{let i=new ae,s=new Te,c=new ye(r,i),l=Xe.isAbsolute(o)?o:Xe.join(r,o);if(!await De.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 Nn(r,d.name,d.version),a.text="Salvando cache do manifest...";let m=Xe.join(r,".kaven","modules",d.name);await De.ensureDir(m),await De.writeJson(Xe.join(m,"module.json"),d,{spaces:2}),a.succeed(vo.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(vo.red(`Falha na instala\xE7\xE3o: ${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}async function Nn(o,e,t){let n=Xe.join(o,"kaven.json"),r={modules:{}};await De.pathExists(n)&&(r=await De.readJson(n)),r.modules||(r.modules={}),r.modules[e]=t,await De.writeJson(n,r,{spaces:2})}import _t from"chalk";import Lt from"ora";import Ot from"path";import _e from"fs-extra";async function bo(o,e){let t=A.getInstance(),n=Date.now();t.capture("cli.module.remove.start",{moduleName:o});let r=e||process.cwd(),a=Lt(`Removendo m\xF3dulo ${o}...`).start();try{let i=new ae,s=new ye(r,i),c=Ot.join(r,"kaven.json");if(!await _e.pathExists(c))throw new Error("Arquivo kaven.json n\xE3o encontrado. Este \xE9 um projeto Kaven?");let l=await _e.readJson(c);if(!l.modules||!l.modules[o])throw new Error(`O m\xF3dulo ${o} n\xE3o est\xE1 instalado.`);let d=Ot.join(r,".kaven","modules",o,"module.json");if(!await _e.pathExists(d))throw new Error(`Cache do manifest para ${o} n\xE3o encontrado em ${d}. A remo\xE7\xE3o precisa do manifest original.`);let m=await _e.readJson(d);a.text=`Removendo inje\xE7\xF5es de ${o}...`,await s.uninstall(m),a.text="Atualizando configura\xE7\xE3o do projeto...",delete l.modules[o],await _e.writeJson(c,l,{spaces:2}),await _e.remove(Ot.dirname(d)),Lt().succeed(_t.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(),Lt().fail(_t.red(`Falha ao remover m\xF3dulo ${o}:`)),a.fail(_t.red(`${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}import I from"fs-extra";import U from"path";import Xn from"os";import*as Co from"tar";import*as X from"@clack/prompts";import N from"picocolors";import re from"fs-extra";import Ft from"path";import Kn from"os";function xo(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 Vn(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 P=class{configPath;constructor(){this.configPath=Ft.join(Kn.homedir(),".kaven","auth.json")}async saveTokens(e){let t=Ft.dirname(this.configPath);await re.ensureDir(t),await re.writeJson(this.configPath,e,{spaces:2}),process.platform!=="win32"&&await re.chmod(this.configPath,384)}async storeToken(e){let t=Ft.dirname(this.configPath);await re.ensureDir(t),await re.writeJson(this.configPath,{token:e},{spaces:2}),process.platform!=="win32"&&await re.chmod(this.configPath,384)}async getAuth(){if(!await re.pathExists(this.configPath))return null;try{let e=await re.readJson(this.configPath);return e.access_token?e:null}catch{return null}}async getToken(){if(!await re.pathExists(this.configPath))return null;try{let e=await re.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 re.pathExists(this.configPath)&&await re.remove(this.configPath)}async clearToken(){return this.logout()}async getUserInfo(){let e=await this.getAuth();if(!e)return null;let t=xo(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?xo(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:Vn(e.expires_at)}:null}};import{spawn as Bn}from"child_process";import*as Ye from"fs-extra";var mt=class{async performMerge(e,t,n){if(!await Ye.pathExists(t))throw new Error("Baseline cache file missing: "+t+". Cannot perform safe merge.");return await Ye.pathExists(e)?new Promise((r,a)=>{let i=Bn("git",["merge-file","-L","Your Modifications (OURS)","-L","Original Version (BASE)","-L","Kaven Update (THEIRS)",e,t,n]),s="";i.stdout.on("data",c=>{s+=c.toString()}),i.stderr.on("data",c=>{s+=c.toString()}),i.on("close",c=>{c===0?r({success:!0,conflicts:!1,output:s}):c!==null&&c>0?r({success:!0,conflicts:!0,output:s}):a(new Error("Git merge-file failed critically: "+s))})}):(await Ye.copy(n,e),{success:!0,conflicts:!1,output:"New file copied"})}};import ft from"crypto";import Jn from"fs-extra";async function zn(o){let e=await Jn.readFile(o);return ft.createHash("sha256").update(e).digest("hex")}var Gn=/^[0-9a-fA-F]+$/;function Hn(o){return Gn.test(o)&&o.length===128?Buffer.from(o,"hex"):Buffer.from(o,"base64")}function qn(o,e,t){try{let n=ft.createPublicKey({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),r=Hn(e);return ft.verify(null,Buffer.from(o),n,r)?!0:ft.verify(null,Buffer.from(o+`
27
- `),n,r)}catch{return!1}}async function gt(o){let e=await zn(o.filePath);if(e!==o.expectedChecksum)throw new Ge(`Checksum mismatch: expected ${o.expectedChecksum.substring(0,16)}..., got ${e.substring(0,16)}...`);if(!qn(o.expectedChecksum,o.signature,o.publicKeyBase64))throw new Ge("Ed25519 signature verification failed. The package may have been tampered with.")}import Le from"fs-extra";import Ut from"path";var Nt=".kaven/cache/modules";function Wn(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++)if((t[r]??0)!==(n[r]??0))return(t[r]??0)-(n[r]??0);return 0}async function ht(o,e,t,n){let r=Ut.join(n,Nt,`${o}-${e}`);await Le.ensureDir(r),await Le.copy(t,r)}async function yt(o,e){let t=Ut.join(e,Nt);if(!await Le.pathExists(t))return null;let r=(await Le.readdir(t)).filter(i=>{let s=i.lastIndexOf("-");return s>0&&i.slice(0,s)===o});if(r.length===0)return null;r.sort((i,s)=>{let c=i.slice(i.lastIndexOf("-")+1),l=s.slice(s.lastIndexOf("-")+1);return Wn(c,l)});let a=r[0];return a.slice(a.lastIndexOf("-")+1)}function Kt(o,e,t){return Ut.join(t,Nt,`${o}-${e}`)}async function Eo(o,e,t){let n=Kt(o,e,t);await Le.pathExists(n)&&await Le.remove(n)}var Yn={x:Co.x},K={intro:X.intro,outro:X.outro,spinner:X.spinner,confirm:X.confirm,select:X.select,isCancel:X.isCancel,log:X.log};function So(o){return o.filter(e=>{let t=U.normalize(e);return!t.startsWith("..")&&!U.isAbsolute(t)})}async function Zn(){let o=U.join(Xn.tmpdir(),`kaven-update-${Date.now()}`);return await I.ensureDir(o),o}async function Qn(o,e){let t=U.join(o,".kaven","conflicts.json");if(!await I.pathExists(t))return null;try{let n=await I.readJson(t);if(n.module===e)return n}catch{}return null}async function Ze(o,e,t={}){let n=A.getInstance(),r=Date.now(),a=e??process.cwd();if(K.intro(N.bold(N.cyan("kaven module update"))),!o&&(o=await tr(a),!o)){K.outro(N.yellow("Nenhum m\xF3dulo selecionado."));return}n.capture("cli.module.update.start",{slug:o});let i;try{let s=await Qn(a,o);if(s){let b=await K.confirm({message:N.yellow(`Conflitos pendentes encontrados do update ${s.fromVersion}\u2192${s.toVersion}. Deseja tentar novamente?`)});if(K.isCancel(b)||!b){K.outro(N.yellow("Update cancelado. Resolva os conflitos manualmente e rode novamente."));return}await I.remove(U.join(a,".kaven","conflicts.json"))}let c=await yt(o,a);c||(K.outro(N.red(`M\xF3dulo '${o}' n\xE3o est\xE1 instalado. Use 'kaven marketplace install ${o}' primeiro.`)),process.exit(1));let l=K.spinner();l.start(`Verificando vers\xE3o mais recente de '${o}'...`);let d=new P,m=new V(d);try{await d.getValidToken()}catch{l.stop("Autentica\xE7\xE3o necess\xE1ria."),K.outro(N.red("Execute: kaven auth login")),process.exit(1)}let p=await m.getModule(o),u=p.latestVersion??p.releases?.[0]?.version;if(u||(l.stop(),K.outro(N.red(`Nenhuma vers\xE3o publicada encontrada para '${o}'.`)),process.exit(1)),l.stop(`Vers\xE3o instalada: ${N.bold(c)} \u2014 \xDAltima vers\xE3o: ${N.bold(u)}`),c===u){K.outro(N.green(`\u2713 '${o}' j\xE1 est\xE1 na vers\xE3o mais recente (${u}).`)),n.capture("cli.module.update.already_latest",{slug:o,version:u},Date.now()-r),await n.flush();return}l.start(`Baixando '${o}@${u}'...`);let g=await m.createDownloadToken(o,u);i=await Zn();let k=U.join(i,"module.tar.gz"),C=U.join(i,"extracted");await I.ensureDir(C);let F=await m.resolveUrl(g.downloadUrl),q=await fetch(F);if(!q.ok||!q.body)throw new Error(`Download falhou: ${q.status} ${q.statusText}`);let f=I.createWriteStream(k),$=q.body.getReader();if(await new Promise((b,M)=>{(async()=>{try{let he=!0;for(;he;){let{done:Ee,value:jt}=await $.read();Ee?(f.end(),he=!1):f.write(jt)||await new Promise(It=>f.once("drain",It))}f.once("finish",b),f.once("error",M)}catch(he){M(he)}})()}),l.stop(`Download conclu\xEDdo: ${o}@${u}`),!t.skipVerify){l.start(`Verificando assinatura de ${o}@${u}...`);let b=await m.getReleaseInfo(o,u);b.checksum&&b.signature&&b.publicKey?(await gt({filePath:k,expectedChecksum:b.checksum,signature:b.signature,publicKeyBase64:b.publicKey}),l.stop(`Assinatura verificada: ${o}@${u}`)):l.stop(`Sem dados de assinatura para ${o}@${u} \u2014 verifica\xE7\xE3o ignorada`)}l.start("Extraindo arquivos..."),await Yn.x({file:k,cwd:C}),l.stop("Extra\xE7\xE3o completa.");let le=U.join(C,"module.json");if(!await I.pathExists(le))throw new Error(`module.json n\xE3o encontrado no pacote de '${o}@${u}'`);let ze=await I.readJson(le),be=So(ze.mergeable??[]),At=So(ze.copyOnly??[]);l.start(`Cacheando baseline de ${o}@${u}...`),await ht(o,u,C,a),l.stop("Baseline cacheado.");let co=Kt(o,c,a),st=new mt,xe=[];for(let b of be){let M=U.join(a,b),ge=U.join(co,b),he=U.join(C,b);if(!await I.pathExists(he))continue;l.start(`Mergeando ${b}...`),(await st.performMerge(M,ge,he)).conflicts?(xe.push(b),l.stop(N.yellow(` Conflito em ${b}`))):l.stop(N.green(` \u2713 ${b}`))}for(let b of At){let M=U.join(C,b),ge=U.join(a,b);await I.pathExists(M)&&(l.start(`Copiando ${b}...`),await I.ensureDir(U.dirname(ge)),await I.copy(M,ge,{overwrite:!0}),l.stop(N.green(` \u2713 ${b} (sobrescrito)`)))}if(xe.length>0){let b={module:o,fromVersion:c,toVersion:u,timestamp:new Date().toISOString(),conflicts:xe};await I.ensureDir(U.join(a,".kaven")),await I.writeJson(U.join(a,".kaven","conflicts.json"),b,{spaces:2}),K.outro(N.red(`Update parcial \u2014 ${xe.length} conflito(s) detectado(s):
25
+ `;await mt.appendFile(this.logPath,t,"utf8"),this.buffer=[]}catch(e){console.debug("Erro ao gravar telemetria:",e)}}async getRecentEvents(e=20){if(!await mt.pathExists(this.logPath))return[];try{return(await mt.readFile(this.logPath,"utf8")).trim().split(`
26
+ `).reverse().slice(0,e).map(n=>JSON.parse(n))}catch{return[]}}};async function Eo(o,e){let t=j.getInstance(),n=Date.now();t.capture("cli.module.add.start",{manifestPath:o});let r=e||process.cwd(),a=Bn("Preparando instala\xE7\xE3o do m\xF3dulo...").start();try{let i=new se,s=new Ie,c=new ye(r,i),l=Xe.isAbsolute(o)?o:Xe.join(r,o);if(!await De.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 Jn(r,d.name,d.version),a.text="Salvando cache do manifest...";let p=Xe.join(r,".kaven","modules",d.name);await De.ensureDir(p),await De.writeJson(Xe.join(p,"module.json"),d,{spaces:2}),a.succeed(xo.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(xo.red(`Falha na instala\xE7\xE3o: ${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}async function Jn(o,e,t){let n=Xe.join(o,"kaven.json"),r={modules:{}};await De.pathExists(n)&&(r=await De.readJson(n)),r.modules||(r.modules={}),r.modules[e]=t,await De.writeJson(n,r,{spaces:2})}import Lt from"chalk";import Ot from"ora";import Ft from"path";import _e from"fs-extra";async function Co(o,e){let t=j.getInstance(),n=Date.now();t.capture("cli.module.remove.start",{moduleName:o});let r=e||process.cwd(),a=Ot(`Removendo m\xF3dulo ${o}...`).start();try{let i=new se,s=new ye(r,i),c=Ft.join(r,"kaven.json");if(!await _e.pathExists(c))throw new Error("Arquivo kaven.json n\xE3o encontrado. Este \xE9 um projeto Kaven?");let l=await _e.readJson(c);if(!l.modules||!l.modules[o])throw new Error(`O m\xF3dulo ${o} n\xE3o est\xE1 instalado.`);let d=Ft.join(r,".kaven","modules",o,"module.json");if(!await _e.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 _e.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 _e.writeJson(c,l,{spaces:2}),await _e.remove(Ft.dirname(d)),Ot().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(),Ot().fail(Lt.red(`Falha ao remover m\xF3dulo ${o}:`)),a.fail(Lt.red(`${i instanceof Error?i.message:String(i)}`)),process.exit(1)}}import R from"fs-extra";import U from"path";import er from"os";import*as Mo from"tar";import*as Y from"@clack/prompts";import K from"picocolors";import ie from"fs-extra";import Ut from"path";import zn from"os";function So(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 Hn(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 A=class{configPath;constructor(){this.configPath=Ut.join(zn.homedir(),".kaven","auth.json")}async saveTokens(e){let t=Ut.dirname(this.configPath);await ie.ensureDir(t),await ie.writeJson(this.configPath,e,{spaces:2}),process.platform!=="win32"&&await ie.chmod(this.configPath,384)}async storeToken(e){let t=Ut.dirname(this.configPath);await ie.ensureDir(t),await ie.writeJson(this.configPath,{token:e},{spaces:2}),process.platform!=="win32"&&await ie.chmod(this.configPath,384)}async getAuth(){if(!await ie.pathExists(this.configPath))return null;try{let e=await ie.readJson(this.configPath);return e.access_token?e:null}catch{return null}}async getToken(){if(!await ie.pathExists(this.configPath))return null;try{let e=await ie.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 ie.pathExists(this.configPath)&&await ie.remove(this.configPath)}async clearToken(){return this.logout()}async getUserInfo(){let e=await this.getAuth();if(!e)return null;let t=So(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?So(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:Hn(e.expires_at)}:null}};import{spawn as Gn}from"child_process";import*as Ye from"fs-extra";var ft=class{async performMerge(e,t,n){if(!await Ye.pathExists(t))throw new Error("Baseline cache file missing: "+t+". Cannot perform safe merge.");return await Ye.pathExists(e)?new Promise((r,a)=>{let i=Gn("git",["merge-file","-L","Your Modifications (OURS)","-L","Original Version (BASE)","-L","Kaven Update (THEIRS)",e,t,n]),s="";i.stdout.on("data",c=>{s+=c.toString()}),i.stderr.on("data",c=>{s+=c.toString()}),i.on("close",c=>{c===0?r({success:!0,conflicts:!1,output:s}):c!==null&&c>0?r({success:!0,conflicts:!0,output:s}):a(new Error("Git merge-file failed critically: "+s))})}):(await Ye.copy(n,e),{success:!0,conflicts:!1,output:"New file copied"})}};import gt from"crypto";import qn from"fs-extra";async function Wn(o){let e=await qn.readFile(o);return gt.createHash("sha256").update(e).digest("hex")}var Xn=/^[0-9a-fA-F]+$/;function Yn(o){return Xn.test(o)&&o.length===128?Buffer.from(o,"hex"):Buffer.from(o,"base64")}function Zn(o,e,t){try{let n=gt.createPublicKey({key:Buffer.from(t,"base64"),type:"spki",format:"der"}),r=Yn(e);return gt.verify(null,Buffer.from(o),n,r)?!0:gt.verify(null,Buffer.from(o+`
27
+ `),n,r)}catch{return!1}}async function ht(o){let e=await Wn(o.filePath);if(e!==o.expectedChecksum)throw new He(`Checksum mismatch: expected ${o.expectedChecksum.substring(0,16)}..., got ${e.substring(0,16)}...`);if(!Zn(o.expectedChecksum,o.signature,o.publicKeyBase64))throw new He("Ed25519 signature verification failed. The package may have been tampered with.")}import Le from"fs-extra";import Nt from"path";var Kt=".kaven/cache/modules";function Qn(o,e){let t=o.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++)if((t[r]??0)!==(n[r]??0))return(t[r]??0)-(n[r]??0);return 0}async function yt(o,e,t,n){let r=Nt.join(n,Kt,`${o}-${e}`);await Le.ensureDir(r),await Le.copy(t,r)}async function wt(o,e){let t=Nt.join(e,Kt);if(!await Le.pathExists(t))return null;let r=(await Le.readdir(t)).filter(i=>{let s=i.lastIndexOf("-");return s>0&&i.slice(0,s)===o});if(r.length===0)return null;r.sort((i,s)=>{let c=i.slice(i.lastIndexOf("-")+1),l=s.slice(s.lastIndexOf("-")+1);return Qn(c,l)});let a=r[0];return a.slice(a.lastIndexOf("-")+1)}function Vt(o,e,t){return Nt.join(t,Kt,`${o}-${e}`)}async function $o(o,e,t){let n=Vt(o,e,t);await Le.pathExists(n)&&await Le.remove(n)}var tr={x:Mo.x},V={intro:Y.intro,outro:Y.outro,spinner:Y.spinner,confirm:Y.confirm,select:Y.select,isCancel:Y.isCancel,log:Y.log};function Po(o){return o.filter(e=>{let t=U.normalize(e);return!t.startsWith("..")&&!U.isAbsolute(t)})}async function or(){let o=U.join(er.tmpdir(),`kaven-update-${Date.now()}`);return await R.ensureDir(o),o}async function nr(o,e){let t=U.join(o,".kaven","conflicts.json");if(!await R.pathExists(t))return null;try{let n=await R.readJson(t);if(n.module===e)return n}catch{}return null}async function Ze(o,e,t={}){let n=j.getInstance(),r=Date.now(),a=e??process.cwd();if(V.intro(K.bold(K.cyan("kaven module update"))),!o&&(o=await ar(a),!o)){V.outro(K.yellow("Nenhum m\xF3dulo selecionado."));return}n.capture("cli.module.update.start",{slug:o});let i;try{let s=await nr(a,o);if(s){let b=await V.confirm({message:K.yellow(`Conflitos pendentes encontrados do update ${s.fromVersion}\u2192${s.toVersion}. Deseja tentar novamente?`)});if(V.isCancel(b)||!b){V.outro(K.yellow("Update cancelado. Resolva os conflitos manualmente e rode novamente."));return}await R.remove(U.join(a,".kaven","conflicts.json"))}let c=await wt(o,a);c||(V.outro(K.red(`M\xF3dulo '${o}' n\xE3o est\xE1 instalado. Use 'kaven marketplace install ${o}' primeiro.`)),process.exit(1));let l=V.spinner();l.start(`Verificando vers\xE3o mais recente de '${o}'...`);let d=new A,p=new B(d);try{await d.getValidToken()}catch{l.stop("Autentica\xE7\xE3o necess\xE1ria."),V.outro(K.red("Execute: kaven auth login")),process.exit(1)}let m=await p.getModule(o),u=m.latestVersion??m.releases?.[0]?.version;if(u||(l.stop(),V.outro(K.red(`Nenhuma vers\xE3o publicada encontrada para '${o}'.`)),process.exit(1)),l.stop(`Vers\xE3o instalada: ${K.bold(c)} \u2014 \xDAltima vers\xE3o: ${K.bold(u)}`),c===u){V.outro(K.green(`\u2713 '${o}' j\xE1 est\xE1 na vers\xE3o mais recente (${u}).`)),n.capture("cli.module.update.already_latest",{slug:o,version:u},Date.now()-r),await n.flush();return}l.start(`Baixando '${o}@${u}'...`);let f=await p.createDownloadToken(o,u);i=await or();let w=U.join(i,"module.tar.gz"),S=U.join(i,"extracted");await R.ensureDir(S);let I=await p.resolveUrl(f.downloadUrl),N=await fetch(I);if(!N.ok||!N.body)throw new Error(`Download falhou: ${N.status} ${N.statusText}`);let g=R.createWriteStream(w),P=N.body.getReader();if(await new Promise((b,M)=>{(async()=>{try{let ne=!0;for(;ne;){let{done:Ee,value:Tt}=await P.read();Ee?(g.end(),ne=!1):g.write(Tt)||await new Promise(It=>g.once("drain",It))}g.once("finish",b),g.once("error",M)}catch(ne){M(ne)}})()}),l.stop(`Download conclu\xEDdo: ${o}@${u}`),!t.skipVerify){l.start(`Verificando assinatura de ${o}@${u}...`);let b=await p.getReleaseInfo(o,u);b.checksum&&b.signature&&b.publicKey?(await ht({filePath:w,expectedChecksum:b.checksum,signature:b.signature,publicKeyBase64:b.publicKey}),l.stop(`Assinatura verificada: ${o}@${u}`)):l.stop(`Sem dados de assinatura para ${o}@${u} \u2014 verifica\xE7\xE3o ignorada`)}l.start("Extraindo arquivos..."),await tr.x({file:w,cwd:S}),l.stop("Extra\xE7\xE3o completa.");let ue=U.join(S,"module.json");if(!await R.pathExists(ue))throw new Error(`module.json n\xE3o encontrado no pacote de '${o}@${u}'`);let ze=await R.readJson(ue),be=Po(ze.mergeable??[]),jt=Po(ze.copyOnly??[]);l.start(`Cacheando baseline de ${o}@${u}...`),await yt(o,u,S,a),l.stop("Baseline cacheado.");let po=Vt(o,c,a),ct=new ft,xe=[];for(let b of be){let M=U.join(a,b),oe=U.join(po,b),ne=U.join(S,b);if(!await R.pathExists(ne))continue;l.start(`Mergeando ${b}...`),(await ct.performMerge(M,oe,ne)).conflicts?(xe.push(b),l.stop(K.yellow(` Conflito em ${b}`))):l.stop(K.green(` \u2713 ${b}`))}for(let b of jt){let M=U.join(S,b),oe=U.join(a,b);await R.pathExists(M)&&(l.start(`Copiando ${b}...`),await R.ensureDir(U.dirname(oe)),await R.copy(M,oe,{overwrite:!0}),l.stop(K.green(` \u2713 ${b} (sobrescrito)`)))}if(xe.length>0){let b={module:o,fromVersion:c,toVersion:u,timestamp:new Date().toISOString(),conflicts:xe};await R.ensureDir(U.join(a,".kaven")),await R.writeJson(U.join(a,".kaven","conflicts.json"),b,{spaces:2}),V.outro(K.red(`Update parcial \u2014 ${xe.length} conflito(s) detectado(s):
28
28
  `+xe.map(M=>` \u2022 ${M}`).join(`
29
29
  `)+`
30
30
 
31
- Resolva os conflitos (marcadores git <<<<<<< / ======= / >>>>>>>), depois rode 'kaven module update ${o}' novamente.`)),n.capture("cli.module.update.conflicts",{slug:o,fromVersion:c,toVersion:u,conflictCount:xe.length},Date.now()-r),await n.flush();return}await er(a,o,u),await Eo(o,c,a),K.outro(N.green(`\u2713 '${o}' atualizado de ${c} \u2192 ${u}`)),n.capture("cli.module.update.success",{slug:o,fromVersion:c,toVersion:u},Date.now()-r),await n.flush()}catch(s){let c=de(s);K.outro(N.red(`Falha ao atualizar '${o}': ${c.message}`)),n.capture("cli.module.update.error",{slug:o,error:c.message},Date.now()-r),await n.flush(),process.exit(1)}finally{i&&await I.remove(i).catch(()=>{})}}async function er(o,e,t){let n=U.join(o,"kaven.json"),r={};await I.pathExists(n)&&(r=await I.readJson(n)),(!r.modules||typeof r.modules!="object"||Array.isArray(r.modules))&&(r.modules={}),r.modules[e]=t,await I.writeJson(n,r,{spaces:2})}async function tr(o){let e=U.join(o,".kaven","cache","modules");if(!await I.pathExists(e)){K.log.warn("Nenhum m\xF3dulo instalado encontrado.");return}let t=await I.readdir(e);if(t.length===0){K.log.warn("Nenhum m\xF3dulo instalado encontrado.");return}let n=t.map(a=>{let i=a.lastIndexOf("-"),s=a.slice(0,i),c=a.slice(i+1);return{value:s,label:`${s} (${c})`}}),r=await K.select({message:"Selecione o m\xF3dulo para atualizar:",options:n});if(!K.isCancel(r))return r}import T from"chalk";import Oe from"ora";import wt from"path";import R from"fs-extra";import et from"crypto";import $o from"os";import{z as we}from"zod";var or=we.object({name:we.string().min(1),slug:we.string().min(1).regex(/^[a-z0-9-]+$/),version:we.string().regex(/^\d+\.\d+\.\d+$/),description:we.string().min(1),author:we.string().optional(),license:we.string().optional(),tier:we.enum(["free","starter","complete","pro"])}),Qe=wt.join($o.homedir(),".kaven","signing-key.json");async function nr(){if(await R.pathExists(Qe))try{let r=await R.readJson(Qe),a=et.createPrivateKey({key:Buffer.from(r.privateKey,"base64"),type:"pkcs8",format:"der"}),i=et.createPublicKey(a);return{privateKey:a,publicKey:i}}catch{}let{privateKey:o,publicKey:e}=et.generateKeyPairSync("ed25519"),t=o.export({type:"pkcs8",format:"der"}),n=e.export({type:"spki",format:"der"});return await R.ensureDir(wt.dirname(Qe)),await R.writeJson(Qe,{privateKey:t.toString("base64"),publicKey:n.toString("base64")},{spaces:2}),process.platform!=="win32"&&await R.chmod(Qe,384),{privateKey:o,publicKey:e}}async function rr(o){let e=await R.readFile(o);return et.createHash("sha256").update(e).digest("hex")}async function ar(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 Po(o){let e=process.cwd(),t=wt.join(e,"module.json");await R.pathExists(t)||(console.error(T.red("Error: module.json not found in current directory.")),console.error(T.gray("Try: run this command from inside a module directory")),process.exit(1));let n;try{let f=await R.readJson(t),$=or.safeParse(f);if(!$.success){console.error(T.red("Error: Invalid module.json:"));for(let le of $.error.issues)console.error(T.red(` - ${le.path.join(".")}: ${le.message}`));process.exit(1)}n=$.data}catch(f){console.error(T.red(`Error: Failed to parse module.json: ${f instanceof Error?f.message:String(f)}`)),process.exit(1)}console.log(),console.log(T.bold(`Publishing module: ${n.name} v${n.version}`)),console.log(T.gray(`Slug: ${n.slug} | Tier: ${n.tier}`)),console.log();let r=wt.join($o.tmpdir(),`kaven-${n.slug}-${n.version}.tar.gz`),a=Oe("Creating module package...").start();try{await ar(e,r);let f=await R.stat(r);a.succeed(`Package created (${(f.size/1024).toFixed(1)} KB)`)}catch(f){a.fail("Failed to create package"),console.error(T.red(f instanceof Error?f.message:String(f))),await R.remove(r).catch(()=>{}),process.exit(1)}let i=Oe("Computing SHA-256 checksum...").start(),s;try{s=await rr(r),i.succeed(`Checksum: ${s.substring(0,16)}...`)}catch{i.fail("Failed to compute checksum"),await R.remove(r).catch(()=>{}),process.exit(1);return}let c=Oe("Signing package...").start(),l,d;try{let{privateKey:f,publicKey:$}=await nr();l=et.sign(null,Buffer.from(s),f).toString("base64"),d=$.export({type:"spki",format:"der"}).toString("base64"),c.succeed(`Package signed (${l.substring(0,16)}...)`)}catch{c.fail("Failed to sign package"),await R.remove(r).catch(()=>{}),process.exit(1);return}if(o.dryRun){console.log(),console.log(T.yellow("Dry-run mode: skipping upload and release creation.")),console.log(T.green("\u2705 Package validated successfully.")),await R.remove(r).catch(()=>{});return}let m=new P;try{await m.getValidToken()}catch{console.error(T.red("Error: Not authenticated. Run 'kaven auth login' first.")),await R.remove(r).catch(()=>{}),process.exit(1);return}let p=new V(m),u=await R.stat(r),g=Oe("Getting upload URL...").start(),k,C;try{let f=await p.getUploadUrl(n.slug,n.version,u.size);k=f.uploadUrl,C=f.s3Key,g.succeed("Upload URL received")}catch(f){g.fail("Failed to get upload URL"),console.error(T.red(f instanceof Error?f.message:String(f))),await R.remove(r).catch(()=>{}),process.exit(1);return}let F=Oe(`Uploading package (${(u.size/1024).toFixed(1)} KB)...`).start();try{let f=await R.readFile(r),$=await fetch(k,{method:"PUT",headers:{"Content-Type":"application/gzip","Content-Length":String(u.size)},body:f});if(!$.ok)throw new Error(`Upload failed: ${$.status} ${$.statusText}`);F.succeed("Package uploaded successfully")}catch(f){F.fail("Upload failed"),console.error(T.red(f instanceof Error?f.message:String(f))),await R.remove(r).catch(()=>{}),process.exit(1);return}let q=Oe("Creating release record...").start();try{let f=await p.createRelease({moduleSlug:n.slug,version:n.version,s3Key:C,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(T.red(f instanceof Error?f.message:String(f))),await R.remove(r).catch(()=>{}),process.exit(1);return}await R.remove(r).catch(()=>{}),console.log(),console.log(T.green(`\u2705 Published ${n.name} v${n.version} to the Kaven Marketplace!`)),console.log(T.gray(`View your module at: https://marketplace.kaven.site/modules/${n.slug}`)),console.log(),console.log(T.bold("Next steps:")),console.log(T.gray(" 1. Share your module with the community")),console.log(T.gray(" 2. Monitor installation metrics")),console.log(T.gray(" 3. Update module with 'kaven module publish' when ready"))}import w from"chalk";import Mo from"ora";import cr from"path";import*as Ao from"@inquirer/prompts";import Vt from"fs-extra";import ir from"path";var Se=[{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"]}],tt=o=>`// [KAVEN_MODULE:${o.toUpperCase()} BEGIN]`,ot=o=>`// [KAVEN_MODULE:${o.toUpperCase()} END]`,sr=/^(\s*)\/\/\s*(.*)$/,Fe=class{schemaPath;constructor(e){this.schemaPath=ir.join(e,"packages","database","prisma","schema.extended.prisma")}async exists(){return Vt.pathExists(this.schemaPath)}get path(){return this.schemaPath}async readSchema(){return Vt.readFile(this.schemaPath,"utf-8")}async writeSchema(e){await Vt.writeFile(this.schemaPath,e,"utf-8")}validateMarkers(e,t){let n=tt(t),r=ot(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=tt(e.id),r=ot(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=tt(t),r=ot(t),a=e.split(`
31
+ Resolva os conflitos (marcadores git <<<<<<< / ======= / >>>>>>>), depois rode 'kaven module update ${o}' novamente.`)),n.capture("cli.module.update.conflicts",{slug:o,fromVersion:c,toVersion:u,conflictCount:xe.length},Date.now()-r),await n.flush();return}await rr(a,o,u),await $o(o,c,a),V.outro(K.green(`\u2713 '${o}' atualizado de ${c} \u2192 ${u}`)),n.capture("cli.module.update.success",{slug:o,fromVersion:c,toVersion:u},Date.now()-r),await n.flush()}catch(s){let c=pe(s);V.outro(K.red(`Falha ao atualizar '${o}': ${c.message}`)),n.capture("cli.module.update.error",{slug:o,error:c.message},Date.now()-r),await n.flush(),process.exit(1)}finally{i&&await R.remove(i).catch(()=>{})}}async function rr(o,e,t){let n=U.join(o,"kaven.json"),r={};await R.pathExists(n)&&(r=await R.readJson(n)),(!r.modules||typeof r.modules!="object"||Array.isArray(r.modules))&&(r.modules={}),r.modules[e]=t,await R.writeJson(n,r,{spaces:2})}async function ar(o){let e=U.join(o,".kaven","cache","modules");if(!await R.pathExists(e)){V.log.warn("Nenhum m\xF3dulo instalado encontrado.");return}let t=await R.readdir(e);if(t.length===0){V.log.warn("Nenhum m\xF3dulo instalado encontrado.");return}let n=t.map(a=>{let i=a.lastIndexOf("-"),s=a.slice(0,i),c=a.slice(i+1);return{value:s,label:`${s} (${c})`}}),r=await V.select({message:"Selecione o m\xF3dulo para atualizar:",options:n});if(!V.isCancel(r))return r}import D from"chalk";import Oe from"ora";import vt from"path";import _ from"fs-extra";import et from"crypto";import Ao from"os";import{z as we}from"zod";var ir=we.object({name:we.string().min(1),slug:we.string().min(1).regex(/^[a-z0-9-]+$/),version:we.string().regex(/^\d+\.\d+\.\d+$/),description:we.string().min(1),author:we.string().optional(),license:we.string().optional(),tier:we.enum(["free","starter","complete","pro"])}),Qe=vt.join(Ao.homedir(),".kaven","signing-key.json");async function sr(){if(await _.pathExists(Qe))try{let r=await _.readJson(Qe),a=et.createPrivateKey({key:Buffer.from(r.privateKey,"base64"),type:"pkcs8",format:"der"}),i=et.createPublicKey(a);return{privateKey:a,publicKey:i}}catch{}let{privateKey:o,publicKey:e}=et.generateKeyPairSync("ed25519"),t=o.export({type:"pkcs8",format:"der"}),n=e.export({type:"spki",format:"der"});return await _.ensureDir(vt.dirname(Qe)),await _.writeJson(Qe,{privateKey:t.toString("base64"),publicKey:n.toString("base64")},{spaces:2}),process.platform!=="win32"&&await _.chmod(Qe,384),{privateKey:o,publicKey:e}}async function cr(o){let e=await _.readFile(o);return et.createHash("sha256").update(e).digest("hex")}async function lr(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 jo(o){let e=process.cwd(),t=vt.join(e,"module.json");await _.pathExists(t)||(console.error(D.red("Error: module.json not found in current directory.")),console.error(D.gray("Try: run this command from inside a module directory")),process.exit(1));let n;try{let g=await _.readJson(t),P=ir.safeParse(g);if(!P.success){console.error(D.red("Error: Invalid module.json:"));for(let ue of P.error.issues)console.error(D.red(` - ${ue.path.join(".")}: ${ue.message}`));process.exit(1)}n=P.data}catch(g){console.error(D.red(`Error: Failed to parse module.json: ${g instanceof Error?g.message:String(g)}`)),process.exit(1)}console.log(),console.log(D.bold(`Publishing module: ${n.name} v${n.version}`)),console.log(D.gray(`Slug: ${n.slug} | Tier: ${n.tier}`)),console.log();let r=vt.join(Ao.tmpdir(),`kaven-${n.slug}-${n.version}.tar.gz`),a=Oe("Creating module package...").start();try{await lr(e,r);let g=await _.stat(r);a.succeed(`Package created (${(g.size/1024).toFixed(1)} KB)`)}catch(g){a.fail("Failed to create package"),console.error(D.red(g instanceof Error?g.message:String(g))),await _.remove(r).catch(()=>{}),process.exit(1)}let i=Oe("Computing SHA-256 checksum...").start(),s;try{s=await cr(r),i.succeed(`Checksum: ${s.substring(0,16)}...`)}catch{i.fail("Failed to compute checksum"),await _.remove(r).catch(()=>{}),process.exit(1);return}let c=Oe("Signing package...").start(),l,d;try{let{privateKey:g,publicKey:P}=await sr();l=et.sign(null,Buffer.from(s),g).toString("base64"),d=P.export({type:"spki",format:"der"}).toString("base64"),c.succeed(`Package signed (${l.substring(0,16)}...)`)}catch{c.fail("Failed to sign package"),await _.remove(r).catch(()=>{}),process.exit(1);return}if(o.dryRun){console.log(),console.log(D.yellow("Dry-run mode: skipping upload and release creation.")),console.log(D.green("\u2705 Package validated successfully.")),await _.remove(r).catch(()=>{});return}let p=new A;try{await p.getValidToken()}catch{console.error(D.red("Error: Not authenticated. Run 'kaven auth login' first.")),await _.remove(r).catch(()=>{}),process.exit(1);return}let m=new B(p),u=await _.stat(r),f=Oe("Getting upload URL...").start(),w,S;try{let g=await m.getUploadUrl(n.slug,n.version,u.size);w=g.uploadUrl,S=g.s3Key,f.succeed("Upload URL received")}catch(g){f.fail("Failed to get upload URL"),console.error(D.red(g instanceof Error?g.message:String(g))),await _.remove(r).catch(()=>{}),process.exit(1);return}let I=Oe(`Uploading package (${(u.size/1024).toFixed(1)} KB)...`).start();try{let g=await _.readFile(r),P=await fetch(w,{method:"PUT",headers:{"Content-Type":"application/gzip","Content-Length":String(u.size)},body:g});if(!P.ok)throw new Error(`Upload failed: ${P.status} ${P.statusText}`);I.succeed("Package uploaded successfully")}catch(g){I.fail("Upload failed"),console.error(D.red(g instanceof Error?g.message:String(g))),await _.remove(r).catch(()=>{}),process.exit(1);return}let N=Oe("Creating release record...").start();try{let g=await m.createRelease({moduleSlug:n.slug,version:n.version,s3Key:S,checksum:s,signature:l,publicKey:d,changelog:o.changelog});N.succeed(`Release created: ${n.slug}@${g.version} (ID: ${g.id})`)}catch(g){N.fail("Failed to create release"),console.error(D.red(g instanceof Error?g.message:String(g))),await _.remove(r).catch(()=>{}),process.exit(1);return}await _.remove(r).catch(()=>{}),console.log(),console.log(D.green(`\u2705 Published ${n.name} v${n.version} to the Kaven Marketplace!`)),console.log(D.gray(`View your module at: https://marketplace.kaven.site/modules/${n.slug}`)),console.log(),console.log(D.bold("Next steps:")),console.log(D.gray(" 1. Share your module with the community")),console.log(D.gray(" 2. Monitor installation metrics")),console.log(D.gray(" 3. Update module with 'kaven module publish' when ready"))}import v from"chalk";import To from"ora";import pr from"path";import*as Io from"@inquirer/prompts";import Bt from"fs-extra";import dr from"path";var Ce=[{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"]}],tt=o=>`// [KAVEN_MODULE:${o.toUpperCase()} BEGIN]`,ot=o=>`// [KAVEN_MODULE:${o.toUpperCase()} END]`,ur=/^(\s*)\/\/\s*(.*)$/,Fe=class{schemaPath;constructor(e){this.schemaPath=dr.join(e,"packages","database","prisma","schema.extended.prisma")}async exists(){return Bt.pathExists(this.schemaPath)}get path(){return this.schemaPath}async readSchema(){return Bt.readFile(this.schemaPath,"utf-8")}async writeSchema(e){await Bt.writeFile(this.schemaPath,e,"utf-8")}validateMarkers(e,t){let n=tt(t),r=ot(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=tt(e.id),r=ot(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=tt(t),r=ot(t),a=e.split(`
32
32
  `),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(`
33
33
  `)}isBlockActive(e){return e.split(`
34
34
  `).some(t=>{let n=t.trim();return n.length>0&&!n.startsWith("//")&&!n.startsWith("/*")&&!n.startsWith("*")})}isModelActive(e,t){let n=e.split(`
35
35
  `);for(let r of n)if(r.trim().startsWith(`model ${t}`)&&!r.trimStart().startsWith("//"))return!0;return!1}commentBlock(e,t){let n=tt(t),r=ot(t),a=e.split(`
36
36
  `),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(`
37
37
  `)}uncommentBlock(e,t){let n=tt(t),r=ot(t),a=e.split(`
38
- `),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(sr);l?s.push(l[1]+l[2]):s.push(c)}else s.push(c)}return s.join(`
39
- `)}};var lr={confirm:Ao.confirm};function Bt(o){return Se.find(e=>e.id===o.toLowerCase())}function jo(o,e){if(!o){let t=cr.join(e,"packages","database","prisma","schema.extended.prisma");console.error(w.red(`
40
- 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 Jt(o,e,t={}){let n=A.getInstance(),r=Date.now();n.capture("cli.module.activate.start",{moduleName:o});let a=e??process.cwd(),i=new Fe(a),s=Mo(`Activating module ${o}...`).start();try{let c=await i.exists();s.stop(),jo(c,a);let l=Bt(o);if(l||(console.error(w.red(`
41
- Unknown module: "${o}".`)),console.error(w.gray(`Available modules: ${Se.map(m=>m.id).join(", ")}`)),process.exit(1)),l.dependsOn.length>0){s.start("Checking dependencies...");let m=[];for(let u of l.dependsOn){let g=Bt(u);if(!g)continue;let k=await i.getModuleStatus(g);m.push(k)}let p=m.filter(u=>!u.active);if(p.length>0)if(s.stop(),t.withDeps)for(let u of p)await Jt(u.id,e,{...t,withDeps:!0});else console.error(w.red(`
42
- Inactive dependencies for "${o}": ${p.map(u=>u.id).join(", ")}`)),console.error(w.gray(`Activate them first:
43
- ${p.map(u=>` kaven module activate ${u.id}`).join(`
44
- `)}`)),console.log(w.gray(`
45
- Or use --with-deps to activate them automatically.`)),process.exit(1);s.stop()}if((await i.getModuleStatus(l)).active){console.log(w.yellow(`
46
- Module "${l.label}" is already active.`));return}if(!t.yes&&!await lr.confirm({message:`Activate module "${l.label}"? This will uncomment ${l.models.length} model(s) in the schema.`,default:!0})){console.log(w.gray(`
47
- Activation aborted.`));return}if(t.dryRun){console.log(w.bold(`
48
- --- 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(`
49
- 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=de(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 Io(o,e,t={}){let n=A.getInstance(),r=Date.now();n.capture("cli.module.deactivate.start",{moduleName:o});let a=e??process.cwd(),i=new Fe(a),s=Mo(`Deactivating module ${o}...`).start();try{let c=await i.exists();s.stop(),jo(c,a);let l=Bt(o);l||(console.error(w.red(`
50
- Unknown module: "${o}".`)),console.error(w.gray(`Available modules: ${Se.map(p=>p.id).join(", ")}`)),process.exit(1)),s.start("Checking reverse dependencies...");let d=[];for(let p of Se){if(p.id===l.id||!p.dependsOn.includes(l.id))continue;(await i.getModuleStatus(p)).active&&d.push(p.id)}if(d.length>0&&(s.stop(),console.error(w.red(`
51
- Cannot deactivate "${o}": the following active modules depend on it:`)),console.error(w.gray(` ${d.join(", ")}`)),console.error(w.gray(`Deactivate them first:
52
- ${d.map(p=>` kaven module deactivate ${p}`).join(`
53
- `)}`)),process.exit(1)),!(await i.getModuleStatus(l)).active){s.stop(),console.log(w.yellow(`
54
- Module "${l.label}" is already inactive.`));return}if(t.dryRun){s.stop(),console.log(w.bold(`
55
- --- 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(`
56
- 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=de(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 Fe(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
57
- `)),console.log(a),console.log(w.gray(i)),!n){for(let s of Se){let c=s.id.padEnd(r.module),l=w.gray("unknown".padEnd(r.status)),d=s.models.join(", ").padEnd(r.models),m=s.dependsOn.length>0?s.dependsOn.join(", "):"\u2014";console.log(`${c}${l}${d}${m}`)}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 Se){let c=await t.getModuleStatus(s),l=s.id.padEnd(r.module),d=c.active?"active":"inactive",m=c.active?w.green(d.padEnd(r.status)):w.gray(d.padEnd(r.status)),p=s.models.join(", ").padEnd(r.models),u=s.dependsOn.length>0?s.dependsOn.join(", "):"\u2014";console.log(`${l}${m}${p}${u}`)}console.log(),console.log(w.gray("To activate: kaven module activate <name> | To deactivate: kaven module deactivate <name>"))}import Q from"chalk";import Ro from"ora";import dr from"open";function ur(o){return new Promise(e=>setTimeout(e,o))}async function pr(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),m=String(l%60).padStart(2,"0");r.text=`Waiting for authorization... (expires in ${d}:${m})`,await ur(c*1e3);try{let p=await o.pollDeviceToken(e);if(p.status==="success"&&p.tokens)return p.tokens;switch(p.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(p){if(p.message.includes("denied")||p.message.includes("expired"))throw p;let u=p;throw u.code==="ECONNREFUSED"||u.code==="ENOTFOUND"?new Error("Network error. Check your connection and try again."):p}}throw new Error("Device code expired. Run 'kaven auth login' again.")}async function Do(){let o=A.getInstance(),e=Date.now();o.capture("cli.auth.login.start");let t=new V,n=new P;console.log(Q.blue(`\u{1F510} Starting authentication flow...
58
- `));let r=Ro("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(Q.yellow(`To complete login, follow these steps:
59
- `)),console.log(Q.bold(` Your verification code: ${Q.cyan(i)}
60
- `));try{await dr(s),console.log(Q.dim(" \u2713 Browser opened automatically"))}catch{console.log(Q.yellow(" Open this URL in your browser:")),console.log(Q.underline(` ${s}
61
- `))}let d=Ro("Waiting for authorization...").start(),m=await pr(t,a,c,l,d);await n.saveTokens(m),d.succeed(Q.green(`Logged in as ${Q.bold(m.user.email)}`)),console.log(Q.dim(` Tier: ${m.user.tier}`)),console.log(Q.gray(`
38
+ `),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(ur);l?s.push(l[1]+l[2]):s.push(c)}else s.push(c)}return s.join(`
39
+ `)}};var mr={confirm:Io.confirm};function Jt(o){return Ce.find(e=>e.id===o.toLowerCase())}function Ro(o,e){if(!o){let t=pr.join(e,"packages","database","prisma","schema.extended.prisma");console.error(v.red(`
40
+ Error: Schema not found at: ${t}`)),console.error(v.gray("Make sure you are in the root of a valid Kaven project.")),process.exit(1)}}async function zt(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 Fe(a),s=To(`Activating module ${o}...`).start();try{let c=await i.exists();s.stop(),Ro(c,a);let l=Jt(o);if(l||(console.error(v.red(`
41
+ Unknown module: "${o}".`)),console.error(v.gray(`Available modules: ${Ce.map(p=>p.id).join(", ")}`)),process.exit(1)),l.dependsOn.length>0){s.start("Checking dependencies...");let p=[];for(let u of l.dependsOn){let f=Jt(u);if(!f)continue;let w=await i.getModuleStatus(f);p.push(w)}let m=p.filter(u=>!u.active);if(m.length>0)if(s.stop(),t.withDeps)for(let u of m)await zt(u.id,e,{...t,withDeps:!0});else console.error(v.red(`
42
+ Inactive dependencies for "${o}": ${m.map(u=>u.id).join(", ")}`)),console.error(v.gray(`Activate them first:
43
+ ${m.map(u=>` kaven module activate ${u.id}`).join(`
44
+ `)}`)),console.log(v.gray(`
45
+ Or use --with-deps to activate them automatically.`)),process.exit(1);s.stop()}if((await i.getModuleStatus(l)).active){console.log(v.yellow(`
46
+ Module "${l.label}" is already active.`));return}if(!t.yes&&!await mr.confirm({message:`Activate module "${l.label}"? This will uncomment ${l.models.length} model(s) in the schema.`,default:!0})){console.log(v.gray(`
47
+ Activation aborted.`));return}if(t.dryRun){console.log(v.bold(`
48
+ --- 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(v.green(`
49
+ Module ${l.label} activated. ${l.models.length} models added: ${l.models.join(", ")}`)),t.skipMigrate||console.log(v.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=pe(c);s.fail(v.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 Do(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 Fe(a),s=To(`Deactivating module ${o}...`).start();try{let c=await i.exists();s.stop(),Ro(c,a);let l=Jt(o);l||(console.error(v.red(`
50
+ Unknown module: "${o}".`)),console.error(v.gray(`Available modules: ${Ce.map(m=>m.id).join(", ")}`)),process.exit(1)),s.start("Checking reverse dependencies...");let d=[];for(let m of Ce){if(m.id===l.id||!m.dependsOn.includes(l.id))continue;(await i.getModuleStatus(m)).active&&d.push(m.id)}if(d.length>0&&(s.stop(),console.error(v.red(`
51
+ Cannot deactivate "${o}": the following active modules depend on it:`)),console.error(v.gray(` ${d.join(", ")}`)),console.error(v.gray(`Deactivate them first:
52
+ ${d.map(m=>` kaven module deactivate ${m}`).join(`
53
+ `)}`)),process.exit(1)),!(await i.getModuleStatus(l)).active){s.stop(),console.log(v.yellow(`
54
+ Module "${l.label}" is already inactive.`));return}if(t.dryRun){s.stop(),console.log(v.bold(`
55
+ --- 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(v.green(`
56
+ Module ${l.label} deactivated successfully.`)),t.skipMigrate||console.log(v.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=pe(c);s.fail(v.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 _o(o){let e=o??process.cwd(),t=new Fe(e),n=await t.exists(),r={module:18,status:10,models:44,deps:20},a=v.bold("Module".padEnd(r.module))+v.bold("Status".padEnd(r.status))+v.bold("Models".padEnd(r.models))+v.bold("Depends on"),i="\u2500".repeat(r.module+r.status+r.models+r.deps);if(console.log(),console.log(v.blue(`Kaven Schema Modules
57
+ `)),console.log(a),console.log(v.gray(i)),!n){for(let s of Ce){let c=s.id.padEnd(r.module),l=v.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(v.yellow("Warning: schema.extended.prisma not found. Status cannot be determined.")),console.log(v.gray("Run this command in the root of a Kaven project to see real status."));return}for(let s of Ce){let c=await t.getModuleStatus(s),l=s.id.padEnd(r.module),d=c.active?"active":"inactive",p=c.active?v.green(d.padEnd(r.status)):v.gray(d.padEnd(r.status)),m=s.models.join(", ").padEnd(r.models),u=s.dependsOn.length>0?s.dependsOn.join(", "):"\u2014";console.log(`${l}${p}${m}${u}`)}console.log(),console.log(v.gray("To activate: kaven module activate <name> | To deactivate: kaven module deactivate <name>"))}import ee from"chalk";import Lo from"ora";import fr from"open";function gr(o){return new Promise(e=>setTimeout(e,o))}async function hr(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 gr(c*1e3);try{let m=await o.pollDeviceToken(e);if(m.status==="success"&&m.tokens)return m.tokens;switch(m.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(m){if(m.message.includes("denied")||m.message.includes("expired"))throw m;let u=m;throw u.code==="ECONNREFUSED"||u.code==="ENOTFOUND"?new Error("Network error. Check your connection and try again."):m}}throw new Error("Device code expired. Run 'kaven auth login' again.")}async function Oo(){let o=j.getInstance(),e=Date.now();o.capture("cli.auth.login.start");let t=new B,n=new A;console.log(ee.blue(`\u{1F510} Starting authentication flow...
58
+ `));let r=Lo("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(ee.yellow(`To complete login, follow these steps:
59
+ `)),console.log(ee.bold(` Your verification code: ${ee.cyan(i)}
60
+ `));try{await fr(s),console.log(ee.dim(" \u2713 Browser opened automatically"))}catch{console.log(ee.yellow(" Open this URL in your browser:")),console.log(ee.underline(` ${s}
61
+ `))}let d=Lo("Waiting for authorization...").start(),p=await hr(t,a,c,l,d);await n.saveTokens(p),d.succeed(ee.green(`Logged in as ${ee.bold(p.user.email)}`)),console.log(ee.dim(` Tier: ${p.user.tier}`)),console.log(ee.gray(`
62
62
  Your credentials were saved securely in ~/.kaven/auth.json
63
- `)),o.capture("cli.auth.login.success",{tier:m.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(Q.red("Authentication failed")),console.error(Q.red(`
63
+ `)),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(ee.red("Authentication failed")),console.error(ee.red(`
64
64
  Error: ${a.message}
65
- `)),process.exit(1)}}import zt from"chalk";async function _o(){let o=new P;try{if(!await o.isAuthenticated()){console.log(zt.yellow("You are not authenticated."));return}await o.logout(),console.log(zt.green("Logged out successfully."))}catch{console.error(zt.red("Error during logout.")),process.exit(1)}}import Ce from"chalk";async function Lo(){let o=A.getInstance();o.capture("cli.auth.whoami.start");let e=new P;try{let t=await e.getWhoamiInfo();if(!t){console.log(Ce.yellow("You are not authenticated.")),console.log(Ce.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(` ${Ce.bold("Email:")} ${t.email}`),console.log(` ${Ce.bold("GitHub:")} ${t.githubId}`),console.log(` ${Ce.bold("Tier:")} ${t.tier}`),console.log(` ${Ce.bold("Session:")} ${t.sessionExpiry}`),console.log()}catch{console.error(Ce.red("Error checking authentication status.")),process.exit(1)}await o.flush()}import D from"chalk";import mr from"ora";import fr from"cli-table3";function gr(o){switch(o.toLowerCase()){case"starter":return D.green(o.toLowerCase());case"complete":return D.yellow(o.toLowerCase());case"pro":return D.magenta(o.toLowerCase());case"enterprise":return D.blue(o.toLowerCase());default:return o}}async function Oo(o={}){let e=A.getInstance(),t=Date.now();e.capture("cli.marketplace.list.start");let n=new P,r=new V(n),a=o.page??1,i=Math.min(o.limit??20,100),s=o.sort??"newest";await n.isAuthenticated()||console.log(D.yellow("Warning: Not authenticated. Only public modules will be shown. Run: kaven auth login"));let l=mr("Fetching modules from Marketplace...").start();try{let d=await r.listModules({category:o.category,page:a,pageSize:i,q:void 0});l.stop();let m=d.data,p=d.meta,u=d.total??p?.total??m.length;if(o.json){console.log(JSON.stringify(d,null,2)),e.capture("cli.marketplace.list.success",{count:m.length,json:!0},Date.now()-t),await e.flush();return}if(m.length===0){console.log(D.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 fr({head:[D.white.bold("Slug"),D.white.bold("Name"),D.white.bold("Version"),D.white.bold("Tier"),D.white.bold("Installs")],style:{head:[],border:["gray"]}}),k=[...m];s==="popular"?k.sort((f,$)=>$.installCount-f.installCount):s==="name"&&k.sort((f,$)=>f.name.localeCompare($.name));for(let f of k)g.push([D.cyan(f.slug),D.white(f.name),D.green(f.latestVersion??"\u2014"),gr(f.requiredTier??f.tier??""),D.gray(String(f.installCount))]);console.log(D.blue.bold(`
65
+ `)),process.exit(1)}}import Ht from"chalk";async function Fo(){let o=new A;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 Se from"chalk";async function Uo(){let o=j.getInstance();o.capture("cli.auth.whoami.start");let e=new A;try{let t=await e.getWhoamiInfo();if(!t){console.log(Se.yellow("You are not authenticated.")),console.log(Se.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(` ${Se.bold("Email:")} ${t.email}`),console.log(` ${Se.bold("GitHub:")} ${t.githubId}`),console.log(` ${Se.bold("Tier:")} ${t.tier}`),console.log(` ${Se.bold("Session:")} ${t.sessionExpiry}`),console.log()}catch{console.error(Se.red("Error checking authentication status.")),process.exit(1)}await o.flush()}import L from"chalk";import yr from"ora";import wr from"cli-table3";function vr(o){switch(o.toLowerCase()){case"starter":return L.green(o.toLowerCase());case"complete":return L.yellow(o.toLowerCase());case"pro":return L.magenta(o.toLowerCase());case"enterprise":return L.blue(o.toLowerCase());default:return o}}async function No(o={}){let e=j.getInstance(),t=Date.now();e.capture("cli.marketplace.list.start");let n=new A,r=new B(n),a=o.page??1,i=Math.min(o.limit??20,100),s=o.sort??"newest";await n.isAuthenticated()||console.log(L.yellow("Warning: Not authenticated. Only public modules will be shown. Run: kaven auth login"));let l=yr("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,m=d.meta,u=d.total??m?.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(L.yellow("No modules found matching your criteria.")),e.capture("cli.marketplace.list.success",{count:0},Date.now()-t),await e.flush();return}let f=new wr({head:[L.white.bold("Slug"),L.white.bold("Name"),L.white.bold("Version"),L.white.bold("Tier"),L.white.bold("Installs")],style:{head:[],border:["gray"]}}),w=[...p];s==="popular"?w.sort((g,P)=>P.installCount-g.installCount):s==="name"&&w.sort((g,P)=>g.name.localeCompare(P.name));for(let g of w)f.push([L.cyan(g.slug),L.white(g.name),L.green(g.latestVersion??"\u2014"),vr(g.requiredTier??g.tier??""),L.gray(String(g.installCount))]);console.log(L.blue.bold(`
66
66
  Available Marketplace Modules:
67
- `)),console.log(g.toString());let C=Math.ceil(u/i),F=(a-1)*i+1,q=Math.min(a*i,u);console.log(D.gray(`
68
- Showing ${F}-${q} of ${u} modules (page ${a}/${C})`)),console.log(D.gray("Use 'kaven marketplace install <slug>' to install a module.")),e.capture("cli.marketplace.list.success",{count:m.length,total:u},Date.now()-t),await e.flush()}catch(d){l.stop(),d instanceof ct&&(console.error(D.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(D.red("Error fetching modules from Marketplace.")),console.error(d),process.exit(1)}}import ee from"chalk";import hr from"ora";import $e from"fs-extra";import vt from"path";import wr from"os";import*as Fo from"tar";var yr={ora:hr},vr={x:Fo.x};async function kr(){let o=vt.join(wr.tmpdir(),"kaven-install-");return $e.mkdtemp(o)}function br(o){return o<1024?`${o} B`:o<1024*1024?`${Math.round(o/1024)} KB`:`${(o/(1024*1024)).toFixed(1)} MB`}async function kt(o,e={}){let t=A.getInstance(),n=Date.now();t.capture("cli.marketplace.install.start",{slug:o});let r=new P,a=new V(r),i=process.cwd(),s;try{s=await r.getValidToken()}catch{console.error(ee.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=yr.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(M){if(M instanceof po){c.fail(ee.red(`Module '${o}' not found in Marketplace.`)),process.exit(1);return}throw M}let m=d.latestVersion??d.releases?.[0]?.version,p=e.version??m;if(!p){c.fail(ee.red(`No published version found for '${o}'.`)),process.exit(1);return}let u=new ae,g=new ye(i,u);if(await g.isModuleInstalled(o)&&!e.force){c.stop(),console.log(ee.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}@${p}'...`;let C=await a.createDownloadToken(o,p);l=await kr();let F=vt.join(l,"module.tar.gz"),q=vt.join(l,"extracted");await $e.ensureDir(q),c.text=`Downloading ${o} v${p}...`;let f=await a.resolveUrl(C.downloadUrl),$=await fetch(f);if(!$.ok)throw new Error(`Download failed: ${$.status} ${$.statusText}`);let le=$.headers.get("content-length"),ze=le?` (${br(parseInt(le,10))})`:"";if(c.text=`Downloading ${o} v${p}${ze}...`,!$.body)throw new Error("No response body received for download");let be=$e.createWriteStream(F),At=$.body.getReader();if(await new Promise((M,ge)=>{(async()=>{try{let Ee=!0;for(;Ee;){let{done:jt,value:It}=await At.read();jt?(be.end(),Ee=!1):be.write(It)||await new Promise(Cn=>be.once("drain",Cn))}be.once("finish",M),be.once("error",ge)}catch(Ee){ge(Ee)}})()}),(await $e.stat(F)).size===0)throw new Error("Downloaded file is empty");if(!e.skipVerify){c.text=`Verifying signature for ${o} v${p}...`;let M=await a.getReleaseInfo(o,p);M.checksum&&M.signature&&M.publicKey?(await gt({filePath:F,expectedChecksum:M.checksum,signature:M.signature,publicKeyBase64:M.publicKey}),c.text=`Signature verified for ${o} v${p}`):c.text=`No signature data for ${o} v${p} \u2014 skipping verification`}c.text=`Extracting ${o} v${p}...`,await vr.x({file:F,cwd:q});let st=vt.join(q,"module.json");if(!await $e.pathExists(st))throw new Error(`module.json not found in extracted archive for '${o}'`);let b=await $e.readJson(st);c.text=`Caching baseline for ${o} v${p}...`,await ht(o,p,q,i),c.text=`Installing ${o} v${p}...`,await g.install(b),c.succeed(ee.green(`Module '${o}@${p}' installed successfully.`)),console.log(ee.gray("Use 'kaven module doctor' to verify the installation.")),t.capture("cli.marketplace.install.success",{slug:o,version:p},Date.now()-n),await t.flush()}catch(d){let m=de(d);if(c.stop(),m instanceof Ge){console.error(ee.red(`Signature verification failed for '${o}': ${m.message}`)),console.error(ee.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(m instanceof uo){console.error(ee.red(`License required: '${o}' requires a '${m.requiredTier}' license.`)),console.error(ee.yellow(`Run: kaven upgrade ${m.requiredTier}`)),t.capture("cli.marketplace.install.error",{slug:o,error:"license_required",tier:m.requiredTier},Date.now()-n),await t.flush(),process.exit(1);return}if(m instanceof lo||m.message.includes("Not authenticated")){console.error(ee.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(m instanceof ct){console.error(ee.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:m.message},Date.now()-n),await t.flush(),c.fail(ee.red(`Failed to install module '${o}'.`)),console.error(m),process.exit(1)}finally{l&&await $e.remove(l).catch(()=>{})}}import{select as Gt,spinner as Cr,outro as $r,isCancel as Pr,cancel as Mr}from"@clack/prompts";import _ from"picocolors";import{createInstance as xr}from"i18next";var Er={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 ---"}}},Sr={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 ---"}}},ie=class o{static instance;i18n=xr();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:Er},"pt-BR":{translation:Sr}}})}t(e,t){return this.i18n.t(e,t)}async setLanguage(e){await this.i18n.changeLanguage(e)}getI18n(){return this.i18n}};var Uo=10;function No(o){switch(o.toUpperCase()){case"FREE":return _.dim("[FREE]");case"STARTER":return _.green("[STARTER]");case"COMPLETE":return _.yellow("[COMPLETE]");case"PRO":return _.magenta("[PRO]");case"ENTERPRISE":return _.cyan("[ENTERPRISE]");default:return _.dim(`[${o}]`)}}function Ht(o){Pr(o)&&(Mr("Cancelled."),process.exit(0))}async function Ko(){let o=await ie.getInstance(),e=new P,t=new V(e),n=Cr(),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(_.yellow(o.t("marketplace.browse.categoryLoadFailed")))}let i=[{label:o.t("marketplace.browse.allModules"),value:"__all__"},...a.map(c=>({label:c,value:c})),{label:_.dim(o.t("common.exit")),value:"__exit__"}],s=await Gt({message:o.t("marketplace.browse.browseByCategory"),options:i});if(Ht(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 p=await t.listModules({category:r.category||void 0,page:r.page,pageSize:Uo});a=p.data,i=Math.ceil(p.total/Uo)||1,n.stop()}catch(p){n.stop(_.red(o.t("marketplace.browse.errorLoadingModules",{error:p instanceof Error?p.message:String(p)}))),r.screen="categories";continue}if(a.length===0){console.log(_.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(p=>({label:`${p.name} ${No(p.requiredTier??p.tier??"")}`,hint:p.description,value:p.slug})),...r.page<i?[{label:_.cyan(o.t("marketplace.browse.nextPage")),value:"__next__"}]:[],...r.page>1?[{label:_.cyan(o.t("marketplace.browse.prevPage")),value:"__prev__"}]:[],{label:_.dim(o.t("marketplace.browse.backToCategories")),value:"__back__"},{label:_.dim(o.t("common.exit")),value:"__exit__"}],d=await Gt({message:`Modules${s}${c}:`,options:l});if(Ht(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 m=a.find(p=>p.slug===d);m&&(r.selectedModule=m,r.screen="detail");continue}if(r.screen==="detail"&&r.selectedModule){let a=r.selectedModule;console.log(),console.log(_.bold(a.name),No(a.requiredTier??a.tier??"")),console.log(_.dim(`Version: ${a.latestVersion||"latest"}`)),a.installCount!==void 0&&console.log(_.dim(`Installs: ${a.installCount.toLocaleString()}`)),a.description&&(console.log(),console.log(a.description)),console.log();let i=await Gt({message:o.t("marketplace.browse.whatToDo"),options:[{label:o.t("marketplace.browse.install",{name:a.name}),value:"install"},{label:_.dim(o.t("marketplace.browse.backToList")),value:"back"},{label:_.dim(o.t("common.exit")),value:"exit"}]});if(Ht(i),i==="exit"){r.screen="exit";break}if(i==="back"){r.selectedModule=null,r.screen="list";continue}if(i==="install"){console.log(),await kt(a.slug,{force:!1,skipEnv:!1}),r.screen="exit";break}}}$r(_.dim(o.t("marketplace.browse.sessionEnded")))}import ue from"chalk";async function Vo(o=10){let t=await A.getInstance().getRecentEvents(o);if(t.length===0){console.log(ue.yellow(`
67
+ `)),console.log(f.toString());let S=Math.ceil(u/i),I=(a-1)*i+1,N=Math.min(a*i,u);console.log(L.gray(`
68
+ Showing ${I}-${N} of ${u} modules (page ${a}/${S})`)),console.log(L.gray("Use 'kaven marketplace install <slug>' to install a module.")),e.capture("cli.marketplace.list.success",{count:p.length,total:u},Date.now()-t),await e.flush()}catch(d){l.stop(),d instanceof lt&&(console.error(L.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(L.red("Error fetching modules from Marketplace.")),console.error(d),process.exit(1)}}import z from"chalk";import kr from"ora";import $e from"fs-extra";import kt from"path";import xr from"os";import*as Vo from"tar";var Ko=["starter","complete","pro","enterprise"];function Gt(o){return(o??"starter").toLowerCase()}function nt(o,e){let t=Gt(o),n=Gt(e),r=Ko.indexOf(t),a=Ko.indexOf(n),i=r>=0?r:0,s=a>=0?a:0;return i>=s}function qt(o){let e=Gt(o);return{starter:"Starter",complete:"Complete",pro:"Pro",enterprise:"Enterprise"}[e]??o??"Starter"}var br={ora:kr},Er={x:Vo.x};async function Cr(){let o=kt.join(xr.tmpdir(),"kaven-install-");return $e.mkdtemp(o)}function Sr(o){return o<1024?`${o} B`:o<1024*1024?`${Math.round(o/1024)} KB`:`${(o/(1024*1024)).toFixed(1)} MB`}async function bt(o,e={}){let t=j.getInstance(),n=Date.now();t.capture("cli.marketplace.install.start",{slug:o});let r=new A,a=new B(r),i=process.cwd(),s;try{s=await r.getValidToken()}catch{console.error(z.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=br.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(M){if(M instanceof go){c.fail(z.red(`Module '${o}' not found in Marketplace.`)),process.exit(1);return}throw M}let p=d.latestVersion??d.releases?.[0]?.version,m=e.version??p;if(!m){c.fail(z.red(`No published version found for '${o}'.`)),process.exit(1);return}if(!e.skipTierCheck){let oe=(await r.getAuth())?.user?.tier??"starter",ne=d.requiredTier??d.tier;if(!nt(oe,ne)){c.stop(),console.error(z.red(`
69
+ \u2717 This module requires a ${qt(ne)} plan or higher.`)),console.error(z.yellow(` Your current plan: ${qt(oe)}`)),console.error(z.dim(` Upgrade: https://kaven.site/pricing
70
+ `)),t.capture("cli.marketplace.install.error",{slug:o,error:"tier_insufficient",userTier:oe,moduleTier:ne},Date.now()-n),await t.flush(),process.exit(1);return}}let u=new se,f=new ye(i,u);if(await f.isModuleInstalled(o)&&!e.force){c.stop(),console.log(z.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}@${m}'...`;let S=await a.createDownloadToken(o,m);l=await Cr();let I=kt.join(l,"module.tar.gz"),N=kt.join(l,"extracted");await $e.ensureDir(N),c.text=`Downloading ${o} v${m}...`;let g=await a.resolveUrl(S.downloadUrl),P=await fetch(g);if(!P.ok)throw new Error(`Download failed: ${P.status} ${P.statusText}`);let ue=P.headers.get("content-length"),ze=ue?` (${Sr(parseInt(ue,10))})`:"";if(c.text=`Downloading ${o} v${m}${ze}...`,!P.body)throw new Error("No response body received for download");let be=$e.createWriteStream(I),jt=P.body.getReader();if(await new Promise((M,oe)=>{(async()=>{try{let Ee=!0;for(;Ee;){let{done:Tt,value:It}=await jt.read();Tt?(be.end(),Ee=!1):be.write(It)||await new Promise(An=>be.once("drain",An))}be.once("finish",M),be.once("error",oe)}catch(Ee){oe(Ee)}})()}),(await $e.stat(I)).size===0)throw new Error("Downloaded file is empty");if(!e.skipVerify){c.text=`Verifying signature for ${o} v${m}...`;let M=await a.getReleaseInfo(o,m);M.checksum&&M.signature&&M.publicKey?(await ht({filePath:I,expectedChecksum:M.checksum,signature:M.signature,publicKeyBase64:M.publicKey}),c.text=`Signature verified for ${o} v${m}`):c.text=`No signature data for ${o} v${m} \u2014 skipping verification`}c.text=`Extracting ${o} v${m}...`,await Er.x({file:I,cwd:N});let ct=kt.join(N,"module.json");if(!await $e.pathExists(ct))throw new Error(`module.json not found in extracted archive for '${o}'`);let b=await $e.readJson(ct);c.text=`Caching baseline for ${o} v${m}...`,await yt(o,m,N,i),c.text=`Installing ${o} v${m}...`,await f.install(b),c.succeed(z.green(`Module '${o}@${m}' installed successfully.`)),console.log(z.gray("Use 'kaven module doctor' to verify the installation.")),t.capture("cli.marketplace.install.success",{slug:o,version:m},Date.now()-n),await t.flush()}catch(d){let p=pe(d);if(c.stop(),p instanceof He){console.error(z.red(`Signature verification failed for '${o}': ${p.message}`)),console.error(z.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 fo){console.error(z.red(`License required: '${o}' requires a '${p.requiredTier}' license.`)),console.error(z.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 mo||p.message.includes("Not authenticated")){console.error(z.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 lt){console.error(z.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(z.red(`Failed to install module '${o}'.`)),console.error(p),process.exit(1)}finally{l&&await $e.remove(l).catch(()=>{})}}import{select as Wt,spinner as Ar,outro as jr,isCancel as Tr,cancel as Ir}from"@clack/prompts";import $ from"picocolors";import{createInstance as $r}from"i18next";var Pr={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 ---"}}},Mr={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 ---"}}},ce=class o{static instance;i18n=$r();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:Pr},"pt-BR":{translation:Mr}}})}t(e,t){return this.i18n.t(e,t)}async setLanguage(e){await this.i18n.changeLanguage(e)}getI18n(){return this.i18n}};var Bo=10;function Jo(o){switch(o.toUpperCase()){case"FREE":return $.dim("[FREE]");case"STARTER":return $.green("[STARTER]");case"COMPLETE":return $.yellow("[COMPLETE]");case"PRO":return $.magenta("[PRO]");case"ENTERPRISE":return $.cyan("[ENTERPRISE]");default:return $.dim(`[${o}]`)}}function Xt(o){Tr(o)&&(Ir("Cancelled."),process.exit(0))}async function zo(){let o=await ce.getInstance(),e=new A,t=new B(e),n=Ar(),a=(await e.getAuth())?.user?.tier??"starter",i={category:null,page:1,selectedModule:null,screen:"categories"};for(;i.screen!=="exit";){if(i.screen==="categories"){n.start(o.t("marketplace.browse.loadingCategories"));let s=[];try{s=await t.getCategories(),n.stop()}catch{n.stop($.yellow(o.t("marketplace.browse.categoryLoadFailed")))}let c=[{label:o.t("marketplace.browse.allModules"),value:"__all__"},...s.map(d=>({label:d,value:d})),{label:$.dim(o.t("common.exit")),value:"__exit__"}],l=await Wt({message:o.t("marketplace.browse.browseByCategory"),options:c});if(Xt(l),l==="__exit__"){i.screen="exit";break}i.category=l==="__all__"?null:l,i.page=1,i.screen="list";continue}if(i.screen==="list"){n.start(o.t("marketplace.browse.loadingModules"));let s=[],c=1;try{let f=await t.listModules({category:i.category||void 0,page:i.page,pageSize:Bo});s=f.data,c=Math.ceil(f.total/Bo)||1,n.stop()}catch(f){n.stop($.red(o.t("marketplace.browse.errorLoadingModules",{error:f instanceof Error?f.message:String(f)}))),i.screen="categories";continue}if(s.length===0){console.log($.yellow(o.t("marketplace.browse.noModulesFound"))),i.screen="categories";continue}let l=i.category?` [${i.category}]`:"",d=c>1?` (${i.page}/${c})`:"",p=[...s.map(f=>{let w=f.requiredTier??f.tier??"",S=w&&!nt(a,w),I=Jo(w),N=S?$.red(" \u{1F512}"):"";return{label:`${f.name} ${I}${N}`,hint:f.description,value:f.slug}}),...i.page<c?[{label:$.cyan(o.t("marketplace.browse.nextPage")),value:"__next__"}]:[],...i.page>1?[{label:$.cyan(o.t("marketplace.browse.prevPage")),value:"__prev__"}]:[],{label:$.dim(o.t("marketplace.browse.backToCategories")),value:"__back__"},{label:$.dim(o.t("common.exit")),value:"__exit__"}],m=await Wt({message:`Modules${l}${d}:`,options:p});if(Xt(m),m==="__exit__"){i.screen="exit";break}if(m==="__back__"){i.screen="categories";continue}if(m==="__next__"){i.page++;continue}if(m==="__prev__"){i.page=Math.max(1,i.page-1);continue}let u=s.find(f=>f.slug===m);u&&(i.selectedModule=u,i.screen="detail");continue}if(i.screen==="detail"&&i.selectedModule){let s=i.selectedModule,c=s.requiredTier??s.tier??"",l=c&&!nt(a,c);console.log(),console.log($.bold(s.name),Jo(c),l?$.red("\u{1F512}"):""),console.log($.dim(`Version: ${s.latestVersion||"latest"}`)),s.installCount!==void 0&&console.log($.dim(`Installs: ${s.installCount.toLocaleString()}`)),s.description&&(console.log(),console.log(s.description)),l&&(console.log(),console.log($.yellow("Requires a higher plan. Upgrade: https://kaven.site/pricing"))),console.log();let d=await Wt({message:o.t("marketplace.browse.whatToDo"),options:[{label:o.t("marketplace.browse.install",{name:s.name}),value:"install"},{label:$.dim(o.t("marketplace.browse.backToList")),value:"back"},{label:$.dim(o.t("common.exit")),value:"exit"}]});if(Xt(d),d==="exit"){i.screen="exit";break}if(d==="back"){i.selectedModule=null,i.screen="list";continue}if(d==="install"){console.log(),await bt(s.slug,{force:!1,skipEnv:!1}),i.screen="exit";break}}}jr($.dim(o.t("marketplace.browse.sessionEnded")))}import me from"chalk";async function Ho(o=10){let t=await j.getInstance().getRecentEvents(o);if(t.length===0){console.log(me.yellow(`
69
71
  Nenhum evento de telemetria encontrado localmente.
70
- `));return}console.log(ue.blue.bold(`
72
+ `));return}console.log(me.blue.bold(`
71
73
  \u{1F4CA} \xDAltimos ${t.length} eventos de telemetria:
72
- `)),t.forEach(n=>{let r=ue.gray(`[${new Date(n.timestamp).toLocaleTimeString()}]`),a=n.event.includes("error")?ue.red("\u2716"):ue.green("\u2714"),i=n.duration?ue.yellow(` (${n.duration}ms)`):"";console.log(`${r} ${a} ${ue.cyan(n.event)}${i}`),n.metadata&&Object.keys(n.metadata).length>0&&console.log(ue.gray(` > ${JSON.stringify(n.metadata)}`))}),console.log(ue.gray(`
74
+ `)),t.forEach(n=>{let r=me.gray(`[${new Date(n.timestamp).toLocaleTimeString()}]`),a=n.event.includes("error")?me.red("\u2716"):me.green("\u2714"),i=n.duration?me.yellow(` (${n.duration}ms)`):"";console.log(`${r} ${a} ${me.cyan(n.event)}${i}`),n.metadata&&Object.keys(n.metadata).length>0&&console.log(me.gray(` > ${JSON.stringify(n.metadata)}`))}),console.log(me.gray(`
73
75
  Log local: ~/.kaven/telemetry.log
74
- `))}import{Command as Ir}from"commander";import{Command as jr}from"commander";import se from"chalk";import qt from"fs/promises";import Jo from"path";import zo from"os";var Bo=Jo.join(zo.homedir(),".kaven","cache","licenses.json"),Ar=3600*1e3,bt=class{cacheDir=Jo.join(zo.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 qt.readFile(Bo,"utf-8");return JSON.parse(e)}catch{return{}}}async writeCache(e){await qt.mkdir(this.cacheDir,{recursive:!0}),await qt.writeFile(Bo,JSON.stringify(e,null,2),"utf-8")}isCacheValid(e){return Date.now()-e.validatedAt<Ar}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 Go(){return new jr("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 bt,t=o??process.env.KAVEN_LICENSE_KEY;t||(console.error(se.red("\u2717 No license key provided. Pass as argument or set KAVEN_LICENSE_KEY.")),process.exit(1));try{console.log(se.dim("Checking license status..."));let n=await e.getLicenseStatus(t);if(console.log(`
75
- `+se.bold("License Status")+`
76
- `),console.log(` Key: ${se.dim(n.key.substring(0,16)+"...")}`),console.log(` Tier: ${se.magenta(n.tier)}`),n.expiresAt){let r=n.daysUntilExpiry,a=r!==null&&r<30?se.red:se.green;console.log(` Expires: ${a(n.expiresAt)}${r!==null?se.dim(` (${r} days)`):""}`)}else console.log(` Expires: ${se.green("Never")}`);console.log()}catch(n){let r=n instanceof Error?n.message:"Failed to check license status";console.error(se.red("\u2717 "+r)),process.exit(1)}})}function Ho(){let o=new Ir("license").description("Manage Kaven licenses");return o.addCommand(Go()),o}import nt from"path";import rt from"fs-extra";import{fileURLToPath as Kr}from"url";import{intro as Vr,outro as Br,text as $t,select as Qo,confirm as Jr,spinner as zr,note as Gr,isCancel as Hr,cancel as Zt}from"@clack/prompts";import W from"picocolors";import J from"fs-extra";import ve from"path";import{spawn as Tr}from"child_process";var Rr="https://github.com/kaven-co/kaven-template.git",Dr="https://github.com/bychrisr/kaven-squad";function Pe(o,e,t,n){return new Promise((r,a)=>{let i=Tr(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 xt=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||Rr;if(console.log(`[INIT] Clone Source: ${n}`),console.log(`[INIT] Target Dir: ${e}`),await J.pathExists(n)&&(n.startsWith("/")||n.startsWith("./")||n.startsWith("../"))){console.log("[INIT] Local Path Detected. Copying..."),await J.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 Pe("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=ve.join(e,".git");await J.pathExists(t)&&await J.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=ve.join(e,i);if(!await J.pathExists(s))continue;let c=await J.readFile(s,"utf-8");for(let[l,d]of Object.entries(n))c=c.split(l).join(d);await J.writeFile(s,c,"utf-8")}let a=ve.join(e,"package.json");if(await J.pathExists(a)){let i=await J.readJson(a);i.name!==t.projectName&&(i.name=t.projectName,await J.writeJson(a,i,{spaces:2}))}}async runInstall(e){let t=await Pe("pnpm",["install"],e);if(t!==0)throw new Error(`pnpm install failed with exit code ${t}`)}async initGit(e){await Pe("git",["init"],e),await Pe("git",["add","."],e),await Pe("git",["commit","-m","chore: initial kaven setup"],e)}async installSquad(e){let t=ve.join(e,"squads"),n=ve.join(t,"kaven-squad");if(await J.pathExists(n))return{installed:!1,reason:"already-exists"};await J.ensureDir(t);let r=await Pe("git",["clone","--depth","1",Dr,n],process.cwd());if(r!==0)return{installed:!1,reason:`git clone exited with code ${r}`};let a=ve.join(n,".git");return await J.pathExists(a)&&await J.remove(a),{installed:!0}}async installAIOXCore(e){let t=await Pe("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 J.pathExists(ve.join(e,a))||t.push(`Missing required file: ${a}`);return await J.pathExists(ve.join(e,"node_modules"))||t.push("Dependencies not installed. Run: pnpm install"),{healthy:t.length===0,issues:t}}};import Me from"path";import pe from"fs-extra";import _r from"os";import qo from"js-yaml";import{z as j}from"zod";var Et=Me.join(_r.homedir(),".kaven"),Wt=Me.join(Et,"config.json"),Wo="kaven-config.yaml",Xo=j.object({registry:j.string().url().default("https://marketplace.kaven.site"),telemetry:j.boolean().default(!0),theme:j.enum(["light","dark"]).default("dark"),language:j.enum(["en","pt-BR"]).default("en"),customRegistry:j.string().url().optional(),projectId:j.string().uuid().optional(),activeModules:j.array(j.string()).default([]),capabilities:j.record(j.string(),j.union([j.string(),j.boolean(),j.number()])).default({}),lastLogin:j.string().datetime().optional(),projectDefaults:j.object({dbUrl:j.string().optional(),emailProvider:j.enum(["postmark","resend","ses","smtp"]).optional(),locale:j.string().optional(),currency:j.string().optional()}).optional()}),Xt=class{globalConfig={};projectConfig={};currentConfig;constructor(){this.currentConfig=Xo.parse({})}async initialize(){if(await pe.ensureDir(Et),await pe.pathExists(Wt))try{this.globalConfig=await pe.readJson(Wt)}catch{this.globalConfig={}}let e=this.findProjectRoot();if(e){let t=Me.join(e,Wo);if(await pe.pathExists(t))try{let n=await pe.readFile(t,"utf-8");this.projectConfig=qo.load(n)}catch{this.projectConfig={}}}this.resolve()}resolve(){this.currentConfig=Xo.parse({...this.globalConfig,...this.projectConfig})}findProjectRoot(){let e=process.cwd();for(;e!==Me.parse(e).root;){if(pe.existsSync(Me.join(e,"package.json")))return e;e=Me.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 pe.ensureDir(Et),await pe.writeJson(Wt,this.globalConfig,{spaces:2})}async persistProject(){let e=this.findProjectRoot();if(!e)return;let t=Me.join(e,Wo),n=qo.dump(this.projectConfig,{lineWidth:120,noRefs:!0});await pe.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 Et}},z=new Xt;import ke from"picocolors";var Lr=`
76
+ `))}import{Command as _r}from"commander";import{Command as Dr}from"commander";import le from"chalk";import Yt from"fs/promises";import qo from"path";import Wo from"os";var Go=qo.join(Wo.homedir(),".kaven","cache","licenses.json"),Rr=3600*1e3,xt=class{cacheDir=qo.join(Wo.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 Yt.readFile(Go,"utf-8");return JSON.parse(e)}catch{return{}}}async writeCache(e){await Yt.mkdir(this.cacheDir,{recursive:!0}),await Yt.writeFile(Go,JSON.stringify(e,null,2),"utf-8")}isCacheValid(e){return Date.now()-e.validatedAt<Rr}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 Xo(){return new Dr("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 xt,t=o??process.env.KAVEN_LICENSE_KEY;t||(console.error(le.red("\u2717 No license key provided. Pass as argument or set KAVEN_LICENSE_KEY.")),process.exit(1));try{console.log(le.dim("Checking license status..."));let n=await e.getLicenseStatus(t);if(console.log(`
77
+ `+le.bold("License Status")+`
78
+ `),console.log(` Key: ${le.dim(n.key.substring(0,16)+"...")}`),console.log(` Tier: ${le.magenta(n.tier)}`),n.expiresAt){let r=n.daysUntilExpiry,a=r!==null&&r<30?le.red:le.green;console.log(` Expires: ${a(n.expiresAt)}${r!==null?le.dim(` (${r} days)`):""}`)}else console.log(` Expires: ${le.green("Never")}`);console.log()}catch(n){let r=n instanceof Error?n.message:"Failed to check license status";console.error(le.red("\u2717 "+r)),process.exit(1)}})}function Yo(){let o=new _r("license").description("Manage Kaven licenses");return o.addCommand(Xo()),o}import rt from"path";import at from"fs-extra";import{fileURLToPath as zr}from"url";import{intro as Hr,outro as Gr,text as Pt,select as nn,confirm as qr,spinner as Wr,note as Xr,isCancel as Yr,cancel as to}from"@clack/prompts";import X from"picocolors";import H from"fs-extra";import ve from"path";import{spawn as Lr}from"child_process";var Or="https://github.com/kaven-co/kaven-template.git",Fr="https://github.com/bychrisr/kaven-squad";function Pe(o,e,t,n){return new Promise((r,a)=>{let i=Lr(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||Or;if(console.log(`[INIT] Clone Source: ${n}`),console.log(`[INIT] Target Dir: ${e}`),await H.pathExists(n)&&(n.startsWith("/")||n.startsWith("./")||n.startsWith("../"))){console.log("[INIT] Local Path Detected. Copying..."),await H.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 Pe("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=ve.join(e,".git");await H.pathExists(t)&&await H.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=ve.join(e,i);if(!await H.pathExists(s))continue;let c=await H.readFile(s,"utf-8");for(let[l,d]of Object.entries(n))c=c.split(l).join(d);await H.writeFile(s,c,"utf-8")}let a=ve.join(e,"package.json");if(await H.pathExists(a)){let i=await H.readJson(a);i.name!==t.projectName&&(i.name=t.projectName,await H.writeJson(a,i,{spaces:2}))}}async runInstall(e){let t=await Pe("pnpm",["install"],e);if(t!==0)throw new Error(`pnpm install failed with exit code ${t}`)}async initGit(e){await Pe("git",["init"],e),await Pe("git",["add","."],e),await Pe("git",["commit","-m","chore: initial kaven setup"],e)}async installSquad(e){let t=ve.join(e,"squads"),n=ve.join(t,"kaven-squad");if(await H.pathExists(n))return{installed:!1,reason:"already-exists"};await H.ensureDir(t);let r=await Pe("git",["clone","--depth","1",Fr,n],process.cwd());if(r!==0)return{installed:!1,reason:`git clone exited with code ${r}`};let a=ve.join(n,".git");return await H.pathExists(a)&&await H.remove(a),{installed:!0}}async installAIOXCore(e){let t=await Pe("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 H.pathExists(ve.join(e,a))||t.push(`Missing required file: ${a}`);return await H.pathExists(ve.join(e,"node_modules"))||t.push("Dependencies not installed. Run: pnpm install"),{healthy:t.length===0,issues:t}}};import Me from"path";import fe from"fs-extra";import Ur from"os";import Zo from"js-yaml";import{z as T}from"zod";var Ct=Me.join(Ur.homedir(),".kaven"),Zt=Me.join(Ct,"config.json"),Qo="kaven-config.yaml",en=T.object({registry:T.string().url().default("https://marketplace.kaven.site"),telemetry:T.boolean().default(!0),theme:T.enum(["light","dark"]).default("dark"),language:T.enum(["en","pt-BR"]).default("en"),customRegistry:T.string().url().optional(),projectId:T.string().uuid().optional(),activeModules:T.array(T.string()).default([]),capabilities:T.record(T.string(),T.union([T.string(),T.boolean(),T.number()])).default({}),lastLogin:T.string().datetime().optional(),projectDefaults:T.object({dbUrl:T.string().optional(),emailProvider:T.enum(["postmark","resend","ses","smtp"]).optional(),locale:T.string().optional(),currency:T.string().optional()}).optional()}),Qt=class{globalConfig={};projectConfig={};currentConfig;constructor(){this.currentConfig=en.parse({})}async initialize(){if(await fe.ensureDir(Ct),await fe.pathExists(Zt))try{this.globalConfig=await fe.readJson(Zt)}catch{this.globalConfig={}}let e=this.findProjectRoot();if(e){let t=Me.join(e,Qo);if(await fe.pathExists(t))try{let n=await fe.readFile(t,"utf-8");this.projectConfig=Zo.load(n)}catch{this.projectConfig={}}}this.resolve()}resolve(){this.currentConfig=en.parse({...this.globalConfig,...this.projectConfig})}findProjectRoot(){let e=process.cwd();for(;e!==Me.parse(e).root;){if(fe.existsSync(Me.join(e,"package.json")))return e;e=Me.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 fe.ensureDir(Ct),await fe.writeJson(Zt,this.globalConfig,{spaces:2})}async persistProject(){let e=this.findProjectRoot();if(!e)return;let t=Me.join(e,Qo),n=Zo.dump(this.projectConfig,{lineWidth:120,noRefs:!0});await fe.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 Ct}},G=new Qt;import ke from"picocolors";var Nr=`
77
79
  \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
78
80
  \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
79
81
  \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
80
82
  \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
81
83
  \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
82
84
  \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
83
- `;function Yo(){return`
84
- ${Lr.split(`
85
+ `;function tn(){return`
86
+ ${Nr.split(`
85
87
  `).map(t=>ke.cyan(t)).join(`
86
88
  `)}
87
89
  ${ke.dim(" The Premium Framework Orchestrator for SaaS")}
88
- `}var kl={primary:ke.cyan,secondary:ke.magenta,success:ke.green,warning:ke.yellow,error:ke.red,dim:ke.dim};import*as Or from"child_process";import Yt from"fs-extra";import*as St from"path";import Ur from"ora";import Zo from"chalk";var Fr={...Or},Nr={ora:Ur};async function Ct(o,e={}){if(e.skipAiox)return;let t=St.join(o,".aiox-core");if(!Yt.existsSync(t)&&!Yt.existsSync(St.join(o,".aiox")))return;let n=Nr.ora("Bootstrapping AIOX environment...").start();try{let r=Yt.existsSync(St.join(o,".aiox-core/bin/aiox.js"))?".aiox-core/bin/aiox.js":".aiox/bin/aiox.js";Fr.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(Zo.yellow(" \u26A0 Run manually inside the project: kaven aiox bootstrap")),process.env.KAVEN_DEBUG&&console.error(Zo.gray(` Error: ${r.message}`))}}function Ae(o){Hr(o)&&(Zt("Operation cancelled."),process.exit(0))}async function en(o,e){let t=await ie.getInstance(),n=new xt,r=await Qo({message:"\u{1F310} Select Language / Selecione o Idioma:",options:[{label:"English",value:"en"},{label:"Portugu\xEAs (Brasil)",value:"pt-BR"}],initialValue:"en"});Ae(r),await t.setLanguage(r),await z.initialize(),await z.set("language",r,"global"),console.log(Yo()),Vr(W.cyan(t.t("init.intro")));let a=o;a||(e.defaults?a="my-kaven-app":(a=await $t({message:t.t("init.projectName"),placeholder:"my-kaven-app",validate:l=>{let d=n.validateName(l||"");return d.valid?void 0:d.reason}}),Ae(a)));let i=nt.resolve(process.cwd(),a);await rt.pathExists(i)&&!e.force&&(Zt(W.red(`Error: Directory "${a}" already exists. Use --force to overwrite.`)),process.exit(1));let s;if(e.defaults){let l=z.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=z.getAll().projectDefaults||{},d=await $t({message:"Database URL (PostgreSQL):",initialValue:l.dbUrl||`postgresql://user:password@localhost:5432/${a}`});Ae(d);let m=await Qo({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"});Ae(m);let p=await $t({message:"Default locale:",initialValue:l.locale||"en-US"});Ae(p);let u=await $t({message:"Default currency:",initialValue:l.currency||"USD"});Ae(u);let g=await Jr({message:t.t("init.withSquad"),initialValue:!0});Ae(g),e.withSquad=g,s={dbUrl:d,emailProvider:m,locale:p,currency:u}}let c=zr();c.start("Cloning kaven-template...");try{await n.cloneTemplate(i,e.template),c.stop(W.green("Template cloned"))}catch(l){let d=l instanceof Error?l:new Error(String(l));c.stop(W.red("Clone failed")),Zt(d.message),process.exit(1)}c.start("Configuring project..."),await n.removeGitDir(i),await n.replacePlaceholders(i,{...s,projectName:a});try{let l=nt.join(i,".claude","CLAUDE.md");await rt.ensureDir(nt.dirname(l));let d=Kr(import.meta.url),m=nt.dirname(d),p=nt.resolve(m,"../../core/templates/CLAUDE.md.hbs");if(await rt.pathExists(p)){let g=(await rt.readFile(p,"utf-8")).replace("${new Date().toLocaleDateString()}",new Date().toLocaleDateString());await rt.writeFile(l,g,"utf-8")}}catch(l){console.warn(W.dim(`[init] CLAUDE.md injection skipped: ${l instanceof Error?l.message:String(l)}`))}if(c.stop(W.green("Project configured")),!e.skipInstall){c.start(t.t("init.installing"));try{await n.runInstall(i),c.stop(W.green("Dependencies installed"))}catch{c.stop(W.yellow("pnpm install failed (skip)"))}}if(!e.skipGit){c.start("Initializing git...");try{await n.initGit(i),c.stop(W.green("Git initialized"))}catch{c.stop(W.yellow("Git init failed (skip)"))}}e.withSquad&&(c.start("Infecting AIOX intelligence..."),(await n.installSquad(i)).installed?(await n.installAIOXCore(i),c.stop(W.green("Kaven Squad online \u{1F916}"))):c.stop(W.yellow("AIOX bootstrap skipped or failed"))),await Ct(i,{skipAiox:e.skipAiox}),Gr(`cd ${W.cyan(a)}
90
+ `}var Ml={primary:ke.cyan,secondary:ke.magenta,success:ke.green,warning:ke.yellow,error:ke.red,dim:ke.dim};import*as Kr from"child_process";import eo from"fs-extra";import*as St from"path";import Br from"ora";import on from"chalk";var Vr={...Kr},Jr={ora:Br};async function $t(o,e={}){if(e.skipAiox)return;let t=St.join(o,".aiox-core");if(!eo.existsSync(t)&&!eo.existsSync(St.join(o,".aiox")))return;let n=Jr.ora("Bootstrapping AIOX environment...").start();try{let r=eo.existsSync(St.join(o,".aiox-core/bin/aiox.js"))?".aiox-core/bin/aiox.js":".aiox/bin/aiox.js";Vr.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(on.yellow(" \u26A0 Run manually inside the project: kaven aiox bootstrap")),process.env.KAVEN_DEBUG&&console.error(on.gray(` Error: ${r.message}`))}}function Ae(o){Yr(o)&&(to("Operation cancelled."),process.exit(0))}async function rn(o,e){let t=await ce.getInstance(),n=new Et,r=await nn({message:"\u{1F310} Select Language / Selecione o Idioma:",options:[{label:"English",value:"en"},{label:"Portugu\xEAs (Brasil)",value:"pt-BR"}],initialValue:"en"});Ae(r),await t.setLanguage(r),await G.initialize(),await G.set("language",r,"global"),console.log(tn()),Hr(X.cyan(t.t("init.intro")));let a=o;a||(e.defaults?a="my-kaven-app":(a=await Pt({message:t.t("init.projectName"),placeholder:"my-kaven-app",validate:l=>{let d=n.validateName(l||"");return d.valid?void 0:d.reason}}),Ae(a)));let i=rt.resolve(process.cwd(),a);await at.pathExists(i)&&!e.force&&(to(X.red(`Error: Directory "${a}" already exists. Use --force to overwrite.`)),process.exit(1));let s;if(e.defaults){let l=G.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=G.getAll().projectDefaults||{},d=await Pt({message:"Database URL (PostgreSQL):",initialValue:l.dbUrl||`postgresql://user:password@localhost:5432/${a}`});Ae(d);let p=await nn({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"});Ae(p);let m=await Pt({message:"Default locale:",initialValue:l.locale||"en-US"});Ae(m);let u=await Pt({message:"Default currency:",initialValue:l.currency||"USD"});Ae(u);let f=await qr({message:t.t("init.withSquad"),initialValue:!0});Ae(f),e.withSquad=f,s={dbUrl:d,emailProvider:p,locale:m,currency:u}}let c=Wr();c.start("Cloning kaven-template...");try{await n.cloneTemplate(i,e.template),c.stop(X.green("Template cloned"))}catch(l){let d=l instanceof Error?l:new Error(String(l));c.stop(X.red("Clone failed")),to(d.message),process.exit(1)}c.start("Configuring project..."),await n.removeGitDir(i),await n.replacePlaceholders(i,{...s,projectName:a});try{let l=rt.join(i,".claude","CLAUDE.md");await at.ensureDir(rt.dirname(l));let d=zr(import.meta.url),p=rt.dirname(d),m=rt.resolve(p,"../../core/templates/CLAUDE.md.hbs");if(await at.pathExists(m)){let f=(await at.readFile(m,"utf-8")).replace("${new Date().toLocaleDateString()}",new Date().toLocaleDateString());await at.writeFile(l,f,"utf-8")}}catch(l){console.warn(X.dim(`[init] CLAUDE.md injection skipped: ${l instanceof Error?l.message:String(l)}`))}if(c.stop(X.green("Project configured")),!e.skipInstall){c.start(t.t("init.installing"));try{await n.runInstall(i),c.stop(X.green("Dependencies installed"))}catch{c.stop(X.yellow("pnpm install failed (skip)"))}}if(!e.skipGit){c.start("Initializing git...");try{await n.initGit(i),c.stop(X.green("Git initialized"))}catch{c.stop(X.yellow("Git init failed (skip)"))}}e.withSquad&&(c.start("Infecting AIOX intelligence..."),(await n.installSquad(i)).installed?(await n.installAIOXCore(i),c.stop(X.green("Kaven Squad online \u{1F916}"))):c.stop(X.yellow("AIOX bootstrap skipped or failed"))),await $t(i,{skipAiox:e.skipAiox}),Xr(`cd ${X.cyan(a)}
89
91
  cp .env.example .env
90
92
  npx prisma migrate dev
91
- pnpm dev`,"Next Steps"),Br(W.cyan(t.t("init.outro")));try{await z.set("projectDefaults",{dbUrl:s.dbUrl,emailProvider:s.emailProvider,locale:s.locale,currency:s.currency},"global")}catch(l){console.warn(W.dim(`[init] Config save skipped: ${l instanceof Error?l.message:String(l)}`))}}import L from"chalk";import oo from"ora";import ea from"open";import sn from"path";import Ne from"fs-extra";import ta from"os";import G from"chalk";import Qt from"ora";import Pt from"path";import{fileURLToPath as qr}from"url";import{spawn as Wr}from"child_process";import tn from"fs";var Xr=qr(import.meta.url),on=Pt.dirname(Xr);function Yr(){let o=[Pt.join(on,"../../package.json"),Pt.join(on,"../../../package.json"),Pt.join(process.cwd(),"package.json")];for(let e of o)if(tn.existsSync(e))try{return JSON.parse(tn.readFileSync(e,"utf8"))}catch{continue}return{version:"0.4.2-alpha.0"}}var Zr=Yr(),Ue=Zr.version,je="kaven-cli";async function eo(){let o=Qt("Checking for updates...").start();try{let e=await fetch(`https://registry.npmjs.org/${je}`);if(!e.ok){o.fail("Could not check for updates");return}let r=(await e.json())["dist-tags"]?.latest||Ue;if(o.stop(),console.log(),console.log(G.bold("Version Check:")),console.log(` Current: ${G.cyan(Ue)}`),console.log(` Latest: ${G.cyan(r)}`),console.log(),r===Ue){console.log(G.green("\u2705 You're on the latest version!"));return}let a=nn(Ue),i=nn(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(G.yellow(`\u26A0 Update available: ${r}`)),console.log(),console.log(G.bold("To upgrade, run:")),console.log(G.cyan(` npm install -g ${je}@latest`)),console.log(G.cyan(" or")),console.log(G.cyan(` pnpm add -g ${je}@latest`)),console.log(),console.log(G.gray("Release notes: https://github.com/kaven-co/kaven-cli/releases"))):console.log(G.green("\u2705 You're on the latest version!"))}catch(e){o.fail(`Check failed: ${e instanceof Error?e.message:String(e)}`),console.log(G.gray("You can manually check at: https://www.npmjs.com/package/kaven-cli"))}}async function to(){console.log();let o=Qt("Fetching latest version...").start();try{let e=await fetch(`https://registry.npmjs.org/${je}`);if(!e.ok)throw new Error("Failed to fetch package info");let r=(await e.json())["dist-tags"]?.latest||Ue;if(r===Ue){o.succeed("Already on latest version");return}o.text=`Installing ${je}@${r}...`;let a=process.env.npm_config_user_agent?.includes("pnpm")?"pnpm":"npm",i=await rn(a,["install","-g",`${je}@${r}`]);if(i!==0){o.fail(`Installation failed with exit code ${i}`),console.error(G.gray(`Try: ${a} install -g ${je}@latest`)),process.exit(1);return}o.succeed(`Updated to ${r}`);let s=Qt("Running health check...").start(),c=await Qr();c.ok?(s.succeed("Installation verified"),console.log(),console.log(G.green("\u2705 CLI upgraded successfully!")),console.log(G.gray("Try: kaven --version"))):(s.warn("Installation verification failed"),console.log(G.yellow(c.errors.join(`
92
- `))))}catch(e){o.fail(`Installation failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}async function Qr(){let o=[];try{await rn("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 rn(o,e,t){return new Promise((n,r)=>{let a=Wr(o,e,t||{stdio:"inherit"});a.on("error",r),a.on("close",i=>n(i??0))})}function nn(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 Ke=sn.join(ta.homedir(),".kaven","license.json"),oa=["starter","complete","pro","enterprise"],at={starter:"Starter",complete:"Complete",pro:"Pro",enterprise:"Enterprise"},na=5e3,an=120;async function ra(){if(!await Ne.pathExists(Ke))return null;try{return(await Ne.readJson(Ke)).key||null}catch{return null}}async function aa(o){let e={};if(await Ne.pathExists(Ke))try{e=await Ne.readJson(Ke)}catch{}await Ne.ensureDir(sn.dirname(Ke)),await Ne.writeJson(Ke,{...e,tier:o},{spaces:2})}function ia(o){return new Promise(e=>setTimeout(e,o))}async function cn(o){let e=new P;try{await e.getValidToken()}catch{console.error(L.red("Error: Not authenticated. Run 'kaven auth login' first.")),process.exit(1);return}let t=await ra();if(!t){console.error(L.red("Error: No license found. Add your license key first with 'kaven license status'.")),process.exit(1);return}let n=new V(e),r=oo("Loading your current license...").start(),a;try{a=(await n.getLicenseStatus(t)).tier.toLowerCase(),r.succeed(`Current tier: ${L.bold(at[a]||a)}`)}catch{r.fail("Could not load license status"),console.error(L.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=oa.filter(g=>g!==a&&g!=="enterprise");if(c.length===0){console.log(L.yellow(`You're already on the highest available tier (${at[a]||a}).`)),console.log(L.gray("For Enterprise plans, contact: enterprise@kaven.site"));return}let l=await s({message:"Select target tier:",choices:c.map(g=>({name:at[g],value:g}))});if(l===a){console.log(L.yellow(`Already on ${at[a]||a}.`));return}let d=oo("Creating checkout session...").start(),m,p;try{let g=await n.createCheckoutSession(l,t);m=g.sessionUrl,p=g.sessionId,d.succeed("Checkout session created")}catch(g){d.fail("Failed to create checkout session"),console.error(L.red(g instanceof Error?g.message:String(g))),process.exit(1);return}if(o.browser!==!1){console.log(L.cyan("Opening checkout in your browser...")),console.log(L.gray(`URL: ${m}`));try{await ea(m)}catch{console.log(L.yellow("Could not open browser automatically. Open this URL manually:")),console.log(L.cyan(m))}}else console.log(L.cyan("Open this URL to complete checkout:")),console.log(L.bold(m));console.log();let u=oo("Waiting for payment confirmation (checking every 5s, max 10 min)...").start();for(let g=0;g<an;g++){await ia(na);let k=an-g-1;u.text=`Waiting for payment confirmation... (${k*5}s remaining)`;try{let C=await n.getCheckoutStatus(p);if(C.status==="confirmed"){u.succeed("Payment confirmed!");let F=C.tier||l;await aa(F),console.log(),console.log(L.green(`\u2705 Successfully upgraded to ${at[F]||F}!`)),console.log(L.gray("Your new features are now unlocked."));return}if(C.status==="cancelled"){u.fail("Checkout was cancelled."),console.log(L.gray("No changes were made to your subscription."));return}if(C.status==="failed"){u.fail("Payment failed."),console.log(L.gray("Please try again or contact support@kaven.site")),process.exit(1);return}}catch{}}u.warn("Timed out waiting for payment confirmation."),console.log(),console.log(L.yellow("If you completed payment, your upgrade may take a few minutes to activate.")),console.log(L.gray("Check your upgrade status at: https://dashboard.kaven.site/billing"))}import Ve from"path";import Mt from"fs-extra";import*as te from"@clack/prompts";import x from"picocolors";var O={intro:te.intro,outro:te.outro,spinner:te.spinner,log:{info:te.log.info,warn:te.log.warn,success:te.log.success,error:te.log.error,step:te.log.step,message:te.log.message}},sa="kaven-cli";function ca(o){let e=[Ve.join(o,"package.json"),Ve.join(Ve.dirname(new URL(import.meta.url).pathname),"../../../package.json"),Ve.join(Ve.dirname(new URL(import.meta.url).pathname),"../../package.json")];for(let t of e)try{if(Mt.existsSync(t)){let n=JSON.parse(Mt.readFileSync(t,"utf8"));if(n.version)return n.version}}catch{}return"0.4.2-alpha.0"}async function la(){try{let o=await fetch(`https://registry.npmjs.org/${sa}`);return o.ok?(await o.json())["dist-tags"]?.latest??null:null}catch{return null}}function ln(o,e){let t=a=>a.replace(/^v/,"").split("-")[0].split(".").map(Number),n=t(o),r=t(e);for(let a=0;a<3;a++)if((n[a]??0)!==(r[a]??0))return(n[a]??0)-(r[a]??0);return 0}async function da(o){let e=Ve.join(o,".kaven","cache","modules");if(!await Mt.pathExists(e))return[];let t=await Mt.readdir(e),n=new Set;for(let r of t){let a=r.lastIndexOf("-");a>0&&n.add(r.slice(0,a))}return[...n]}async function ua(o,e){let t=ca(o),n=null,r=!1;e&&(n=await la(),n&&ln(n,t)>0&&(r=!0));let a=await da(o),i=[];if(a.length>0){let s=null;try{let c=new P;await c.getValidToken(),s=new V(c)}catch{}for(let c of a){let l=await yt(c,o);if(!l)continue;let d=null,m;if(s)try{d=(await s.getModule(c)).latestVersion??null}catch(u){m=de(u).message}else m="marketplace offline or not authenticated";let p=!!(d&&ln(d,l)>0);i.push({slug:c,installed:l,latest:d,outdated:p,error:m})}}return{cliCurrent:t,cliLatest:n,cliOutdated:r,modules:i}}function pa(o,e){if(e&&(o.cliLatest===null?O.log.warn(x.yellow(`kaven-cli: ${x.bold(o.cliCurrent)} (could not reach npm)`)):o.cliOutdated?O.log.warn(x.yellow(`kaven-cli: ${x.bold(o.cliCurrent)} \u2192 ${x.bold(o.cliLatest)} available`)+x.dim(`
93
- npm install -g kaven-cli@latest`)):O.log.success(x.green(`kaven-cli: ${x.bold(o.cliCurrent)} \u2713 up to date`))),o.modules.length===0){O.log.info(x.dim("No modules installed in this project."));return}for(let t of o.modules)t.error?O.log.warn(x.yellow(`${t.slug}: ${x.bold(t.installed)} (${t.error})`)):t.outdated?O.log.warn(x.yellow(`${t.slug}: ${x.bold(t.installed)} \u2192 ${x.bold(t.latest)} available`)):O.log.success(x.green(`${t.slug}: ${x.bold(t.installed)} \u2713`))}async function dn(o={},e){let t=e??process.cwd(),{core:n,module:r,all:a,check:i,skipVerify:s}=o;if(r){await Ze(r,t,{skipVerify:s});return}let c=!!(n||a||!n&&!r);O.intro(x.bold(x.cyan("kaven update")));let l=O.spinner();l.start("Verificando atualiza\xE7\xF5es dispon\xEDveis...");let d=await ua(t,c);if(l.stop("Status de atualiza\xE7\xF5es:"),pa(d,c),!(d.cliOutdated||d.modules.some(p=>p.outdated))){O.outro(x.green("\u2713 Tudo atualizado."));return}if(i){O.outro(x.yellow("Atualiza\xE7\xF5es dispon\xEDveis. Rode sem --check para aplicar."));return}if((a||n)&&d.cliOutdated&&d.cliLatest&&(O.log.info(x.cyan(`Atualizando kaven-cli ${d.cliCurrent} \u2192 ${d.cliLatest}...`)),O.log.info(x.dim(" Execute: npm install -g kaven-cli@latest"))),a){let p=d.modules.filter(u=>u.outdated);for(let u of p)O.log.info(x.cyan(`
94
- Atualizando m\xF3dulo ${u.slug} ${u.installed} \u2192 ${u.latest}...`)),await Ze(u.slug,t,{skipVerify:s});O.outro(x.green("\u2713 Todos os m\xF3dulos atualizados."));return}if(!n){let p=d.modules.filter(u=>u.outdated);if(p.length>0){O.log.info(x.dim(`
95
- Para atualizar m\xF3dulos:`));for(let u of p)O.log.info(x.dim(` kaven update --module ${u.slug}`));O.log.info(x.dim(`
96
- Para atualizar tudo: kaven update --all`))}O.outro("")}}import me from"chalk";import ce from"fs-extra";import Be from"path";import ma from"os";var ro=class{cacheDir;maxSizeBytes;indexPath;constructor(e,t){this.cacheDir=e??Be.join(ma.homedir(),".kaven","cache"),this.maxSizeBytes=t??50*1024*1024,this.indexPath=Be.join(this.cacheDir,"_index.json")}async ensureDir(){await ce.ensureDir(this.cacheDir)}keyToFileName(e){return e.replace(/[^a-zA-Z0-9-_:.]/g,"_")+".json"}async readIndex(){try{if(await ce.pathExists(this.indexPath))return await ce.readJson(this.indexPath)}catch{}return{}}async writeIndex(e){await this.ensureDir(),await ce.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=Be.join(this.cacheDir,n.file);return(await ce.readJson(r)).data}catch{return null}}async getStale(e){let n=(await this.readIndex())[e];if(!n)return null;try{let r=Be.join(this.cacheDir,n.file);return(await ce.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=Be.join(this.cacheDir,c),d={data:t,expiresAt:s,size:a,createdAt:i};await ce.writeJson(l,d,{spaces:2});let m=await this.readIndex();m[e]={file:c,expiresAt:s,size:a,createdAt:i},await this.writeIndex(m),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=Be.join(this.cacheDir,i.file);await ce.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 ce.pathExists(this.cacheDir)&&await ce.remove(this.cacheDir)}},no=null;function ao(){return no||(no=new ro),no}function un(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 pn(){let o=ao(),e=await o.stats();console.log(me.bold(`
93
+ pnpm dev`,"Next Steps"),Gr(X.cyan(t.t("init.outro")));try{await G.set("projectDefaults",{dbUrl:s.dbUrl,emailProvider:s.emailProvider,locale:s.locale,currency:s.currency},"global")}catch(l){console.warn(X.dim(`[init] Config save skipped: ${l instanceof Error?l.message:String(l)}`))}}import O from"chalk";import ao from"ora";import ra from"open";import un from"path";import Ne from"fs-extra";import aa from"os";import q from"chalk";import oo from"ora";import Mt from"path";import{fileURLToPath as Zr}from"url";import{spawn as Qr}from"child_process";import an from"fs";var ea=Zr(import.meta.url),sn=Mt.dirname(ea);function ta(){let o=[Mt.join(sn,"../../package.json"),Mt.join(sn,"../../../package.json"),Mt.join(process.cwd(),"package.json")];for(let e of o)if(an.existsSync(e))try{return JSON.parse(an.readFileSync(e,"utf8"))}catch{continue}return{version:"0.4.2-alpha.0"}}var oa=ta(),Ue=oa.version,je="kaven-cli";async function no(){let o=oo("Checking for updates...").start();try{let e=await fetch(`https://registry.npmjs.org/${je}`);if(!e.ok){o.fail("Could not check for updates");return}let r=(await e.json())["dist-tags"]?.latest||Ue;if(o.stop(),console.log(),console.log(q.bold("Version Check:")),console.log(` Current: ${q.cyan(Ue)}`),console.log(` Latest: ${q.cyan(r)}`),console.log(),r===Ue){console.log(q.green("\u2705 You're on the latest version!"));return}let a=cn(Ue),i=cn(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(q.yellow(`\u26A0 Update available: ${r}`)),console.log(),console.log(q.bold("To upgrade, run:")),console.log(q.cyan(` npm install -g ${je}@latest`)),console.log(q.cyan(" or")),console.log(q.cyan(` pnpm add -g ${je}@latest`)),console.log(),console.log(q.gray("Release notes: https://github.com/kaven-co/kaven-cli/releases"))):console.log(q.green("\u2705 You're on the latest version!"))}catch(e){o.fail(`Check failed: ${e instanceof Error?e.message:String(e)}`),console.log(q.gray("You can manually check at: https://www.npmjs.com/package/kaven-cli"))}}async function ro(){console.log();let o=oo("Fetching latest version...").start();try{let e=await fetch(`https://registry.npmjs.org/${je}`);if(!e.ok)throw new Error("Failed to fetch package info");let r=(await e.json())["dist-tags"]?.latest||Ue;if(r===Ue){o.succeed("Already on latest version");return}o.text=`Installing ${je}@${r}...`;let a=process.env.npm_config_user_agent?.includes("pnpm")?"pnpm":"npm",i=await ln(a,["install","-g",`${je}@${r}`]);if(i!==0){o.fail(`Installation failed with exit code ${i}`),console.error(q.gray(`Try: ${a} install -g ${je}@latest`)),process.exit(1);return}o.succeed(`Updated to ${r}`);let s=oo("Running health check...").start(),c=await na();c.ok?(s.succeed("Installation verified"),console.log(),console.log(q.green("\u2705 CLI upgraded successfully!")),console.log(q.gray("Try: kaven --version"))):(s.warn("Installation verification failed"),console.log(q.yellow(c.errors.join(`
94
+ `))))}catch(e){o.fail(`Installation failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}async function na(){let o=[];try{await ln("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 ln(o,e,t){return new Promise((n,r)=>{let a=Qr(o,e,t||{stdio:"inherit"});a.on("error",r),a.on("close",i=>n(i??0))})}function cn(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 Ke=un.join(aa.homedir(),".kaven","license.json"),ia=["starter","complete","pro","enterprise"],it={starter:"Starter",complete:"Complete",pro:"Pro",enterprise:"Enterprise"},sa=5e3,dn=120;async function ca(){if(!await Ne.pathExists(Ke))return null;try{return(await Ne.readJson(Ke)).key||null}catch{return null}}async function la(o){let e={};if(await Ne.pathExists(Ke))try{e=await Ne.readJson(Ke)}catch{}await Ne.ensureDir(un.dirname(Ke)),await Ne.writeJson(Ke,{...e,tier:o},{spaces:2})}function da(o){return new Promise(e=>setTimeout(e,o))}async function pn(o){let e=new A;try{await e.getValidToken()}catch{console.error(O.red("Error: Not authenticated. Run 'kaven auth login' first.")),process.exit(1);return}let t=await ca();if(!t){console.error(O.red("Error: No license found. Add your license key first with 'kaven license status'.")),process.exit(1);return}let n=new B(e),r=ao("Loading your current license...").start(),a;try{a=(await n.getLicenseStatus(t)).tier.toLowerCase(),r.succeed(`Current tier: ${O.bold(it[a]||a)}`)}catch{r.fail("Could not load license status"),console.error(O.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=ia.filter(f=>f!==a&&f!=="enterprise");if(c.length===0){console.log(O.yellow(`You're already on the highest available tier (${it[a]||a}).`)),console.log(O.gray("For Enterprise plans, contact: enterprise@kaven.site"));return}let l=await s({message:"Select target tier:",choices:c.map(f=>({name:it[f],value:f}))});if(l===a){console.log(O.yellow(`Already on ${it[a]||a}.`));return}let d=ao("Creating checkout session...").start(),p,m;try{let f=await n.createCheckoutSession(l,t);p=f.sessionUrl,m=f.sessionId,d.succeed("Checkout session created")}catch(f){d.fail("Failed to create checkout session"),console.error(O.red(f instanceof Error?f.message:String(f))),process.exit(1);return}if(o.browser!==!1){console.log(O.cyan("Opening checkout in your browser...")),console.log(O.gray(`URL: ${p}`));try{await ra(p)}catch{console.log(O.yellow("Could not open browser automatically. Open this URL manually:")),console.log(O.cyan(p))}}else console.log(O.cyan("Open this URL to complete checkout:")),console.log(O.bold(p));console.log();let u=ao("Waiting for payment confirmation (checking every 5s, max 10 min)...").start();for(let f=0;f<dn;f++){await da(sa);let w=dn-f-1;u.text=`Waiting for payment confirmation... (${w*5}s remaining)`;try{let S=await n.getCheckoutStatus(m);if(S.status==="confirmed"){u.succeed("Payment confirmed!");let I=S.tier||l;await la(I),console.log(),console.log(O.green(`\u2705 Successfully upgraded to ${it[I]||I}!`)),console.log(O.gray("Your new features are now unlocked."));return}if(S.status==="cancelled"){u.fail("Checkout was cancelled."),console.log(O.gray("No changes were made to your subscription."));return}if(S.status==="failed"){u.fail("Payment failed."),console.log(O.gray("Please try again or contact support@kaven.site")),process.exit(1);return}}catch{}}u.warn("Timed out waiting for payment confirmation."),console.log(),console.log(O.yellow("If you completed payment, your upgrade may take a few minutes to activate.")),console.log(O.gray("Check your upgrade status at: https://dashboard.kaven.site/billing"))}import Ve from"path";import At from"fs-extra";import*as te from"@clack/prompts";import x from"picocolors";var F={intro:te.intro,outro:te.outro,spinner:te.spinner,log:{info:te.log.info,warn:te.log.warn,success:te.log.success,error:te.log.error,step:te.log.step,message:te.log.message}},ua="kaven-cli";function pa(o){let e=[Ve.join(o,"package.json"),Ve.join(Ve.dirname(new URL(import.meta.url).pathname),"../../../package.json"),Ve.join(Ve.dirname(new URL(import.meta.url).pathname),"../../package.json")];for(let t of e)try{if(At.existsSync(t)){let n=JSON.parse(At.readFileSync(t,"utf8"));if(n.version)return n.version}}catch{}return"0.4.2-alpha.0"}async function ma(){try{let o=await fetch(`https://registry.npmjs.org/${ua}`);return o.ok?(await o.json())["dist-tags"]?.latest??null:null}catch{return null}}function mn(o,e){let t=a=>a.replace(/^v/,"").split("-")[0].split(".").map(Number),n=t(o),r=t(e);for(let a=0;a<3;a++)if((n[a]??0)!==(r[a]??0))return(n[a]??0)-(r[a]??0);return 0}async function fa(o){let e=Ve.join(o,".kaven","cache","modules");if(!await At.pathExists(e))return[];let t=await At.readdir(e),n=new Set;for(let r of t){let a=r.lastIndexOf("-");a>0&&n.add(r.slice(0,a))}return[...n]}async function ga(o,e){let t=pa(o),n=null,r=!1;e&&(n=await ma(),n&&mn(n,t)>0&&(r=!0));let a=await fa(o),i=[];if(a.length>0){let s=null;try{let c=new A;await c.getValidToken(),s=new B(c)}catch{}for(let c of a){let l=await wt(c,o);if(!l)continue;let d=null,p;if(s)try{d=(await s.getModule(c)).latestVersion??null}catch(u){p=pe(u).message}else p="marketplace offline or not authenticated";let m=!!(d&&mn(d,l)>0);i.push({slug:c,installed:l,latest:d,outdated:m,error:p})}}return{cliCurrent:t,cliLatest:n,cliOutdated:r,modules:i}}function ha(o,e){if(e&&(o.cliLatest===null?F.log.warn(x.yellow(`kaven-cli: ${x.bold(o.cliCurrent)} (could not reach npm)`)):o.cliOutdated?F.log.warn(x.yellow(`kaven-cli: ${x.bold(o.cliCurrent)} \u2192 ${x.bold(o.cliLatest)} available`)+x.dim(`
95
+ npm install -g kaven-cli@latest`)):F.log.success(x.green(`kaven-cli: ${x.bold(o.cliCurrent)} \u2713 up to date`))),o.modules.length===0){F.log.info(x.dim("No modules installed in this project."));return}for(let t of o.modules)t.error?F.log.warn(x.yellow(`${t.slug}: ${x.bold(t.installed)} (${t.error})`)):t.outdated?F.log.warn(x.yellow(`${t.slug}: ${x.bold(t.installed)} \u2192 ${x.bold(t.latest)} available`)):F.log.success(x.green(`${t.slug}: ${x.bold(t.installed)} \u2713`))}async function fn(o={},e){let t=e??process.cwd(),{core:n,module:r,all:a,check:i,skipVerify:s}=o;if(r){await Ze(r,t,{skipVerify:s});return}let c=!!(n||a||!n&&!r);F.intro(x.bold(x.cyan("kaven update")));let l=F.spinner();l.start("Verificando atualiza\xE7\xF5es dispon\xEDveis...");let d=await ga(t,c);if(l.stop("Status de atualiza\xE7\xF5es:"),ha(d,c),!(d.cliOutdated||d.modules.some(m=>m.outdated))){F.outro(x.green("\u2713 Tudo atualizado."));return}if(i){F.outro(x.yellow("Atualiza\xE7\xF5es dispon\xEDveis. Rode sem --check para aplicar."));return}if((a||n)&&d.cliOutdated&&d.cliLatest&&(F.log.info(x.cyan(`Atualizando kaven-cli ${d.cliCurrent} \u2192 ${d.cliLatest}...`)),F.log.info(x.dim(" Execute: npm install -g kaven-cli@latest"))),a){let m=d.modules.filter(u=>u.outdated);for(let u of m)F.log.info(x.cyan(`
96
+ Atualizando m\xF3dulo ${u.slug} ${u.installed} \u2192 ${u.latest}...`)),await Ze(u.slug,t,{skipVerify:s});F.outro(x.green("\u2713 Todos os m\xF3dulos atualizados."));return}if(!n){let m=d.modules.filter(u=>u.outdated);if(m.length>0){F.log.info(x.dim(`
97
+ Para atualizar m\xF3dulos:`));for(let u of m)F.log.info(x.dim(` kaven update --module ${u.slug}`));F.log.info(x.dim(`
98
+ Para atualizar tudo: kaven update --all`))}F.outro("")}}import ge from"chalk";import de from"fs-extra";import Be from"path";import ya from"os";var so=class{cacheDir;maxSizeBytes;indexPath;constructor(e,t){this.cacheDir=e??Be.join(ya.homedir(),".kaven","cache"),this.maxSizeBytes=t??50*1024*1024,this.indexPath=Be.join(this.cacheDir,"_index.json")}async ensureDir(){await de.ensureDir(this.cacheDir)}keyToFileName(e){return e.replace(/[^a-zA-Z0-9-_:.]/g,"_")+".json"}async readIndex(){try{if(await de.pathExists(this.indexPath))return await de.readJson(this.indexPath)}catch{}return{}}async writeIndex(e){await this.ensureDir(),await de.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=Be.join(this.cacheDir,n.file);return(await de.readJson(r)).data}catch{return null}}async getStale(e){let n=(await this.readIndex())[e];if(!n)return null;try{let r=Be.join(this.cacheDir,n.file);return(await de.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=Be.join(this.cacheDir,c),d={data:t,expiresAt:s,size:a,createdAt:i};await de.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=Be.join(this.cacheDir,i.file);await de.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 de.pathExists(this.cacheDir)&&await de.remove(this.cacheDir)}},io=null;function co(){return io||(io=new so),io}function gn(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 hn(){let o=co(),e=await o.stats();console.log(ge.bold(`
97
99
  Kaven CLI Cache Status
98
- `)),console.log(` Cache directory: ${me.cyan(o.cacheDir)}`),console.log(` Total size: ${me.cyan(un(e.totalSize))}`),console.log(` Cached entries: ${me.cyan(e.entries.toString())}`),e.oldest&&console.log(` Oldest entry: ${me.gray(e.oldest.toLocaleString())}`),e.newest&&console.log(` Newest entry: ${me.gray(e.newest.toLocaleString())}`),console.log(),console.log(me.gray("Run 'kaven cache clear' to remove all cached data."))}async function mn(){let o=ao(),e=await o.stats();if(e.entries===0){console.log(me.gray("Cache is already empty."));return}await o.clear(),console.log(me.green(`Cache cleared: ${e.entries} entries (${un(e.totalSize)}) removed.`))}import Y from"chalk";async function fn(o,e){(!o||!e)&&(console.error(Y.red("Error: Both key and value are required")),console.error(Y.gray("Usage: kaven config set KEY VALUE")),process.exit(1)),await z.initialize();try{await z.set(o,e),console.log(Y.green(`\u2705 Set ${Y.bold(o)} = ${Y.bold(e)}`))}catch(t){console.error(Y.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function gn(o,e){o||(console.error(Y.red("Error: Key is required")),console.error(Y.gray("Usage: kaven config get KEY")),process.exit(1)),await z.initialize();try{let t=z.get(o);e.json?console.log(JSON.stringify({[o]:t},null,2)):console.log(t)}catch(t){console.error(Y.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function hn(o){await z.initialize();let e=z.getAll();if(o.json)console.log(JSON.stringify(e,null,2));else{console.log(Y.bold("Kaven Configuration:")),console.log(Y.gray(`Location: ${z.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,`
99
- `+" ".repeat(n+3)):a;console.log(` ${r}${i} ${Y.cyan(s)}`)}}}async function yn(){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(Y.yellow("Cancelled."));return}await z.initialize(),await z.reset(),console.log(Y.green("\u2705 Config reset to defaults"))}import{select as fa,confirm as wn,text as ga,multiselect as ha,isCancel as ya,cancel as wa}from"@clack/prompts";import H from"picocolors";import so from"fs-extra";import vn from"path";var fe=[{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"}],io={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 it(o){ya(o)&&(wa("Cancelled."),process.exit(0))}async function kn(o){let e=o.outputPath??vn.join(process.cwd(),"packages","database","prisma","seeds","capabilities.seed.ts");if(o.list){let t=await ie.getInstance();va(t);return}if(o.tier){await bn(o.tier,e,o);return}await ka(e,o)}function va(o){console.log(),console.log(H.bold(H.underline(o.t("config.features.catalogHeader")))),console.log(H.dim(o.t("config.features.capabilitiesTotal",{count:fe.length})+`
100
- `));let e=[...new Set(fe.map(t=>t.category))];for(let t of e){let n=fe.filter(r=>r.category===t);console.log(H.bold(H.cyan(` ${t} (${n.length})`)));for(let r of n)console.log(` ${H.white(r.key.padEnd(30))} ${H.dim(`[${r.type}]`)}`),console.log(` ${H.dim(r.description)}`);console.log()}console.log(H.bold(o.t("config.features.tierPresets")));for(let t of["starter","complete","pro","enterprise"])console.log(` ${H.white(t.padEnd(12))}`);console.log()}async function bn(o,e,t){let n=io[o]||{},r={};for(let a of fe)o==="enterprise"?r[a.key]=a.type==="boolean"?!0:"-1":r[a.key]=n[a.key]??(a.type==="boolean"?!1:a.defaultValue);await xn(r,e,t,o)}async function ka(o,e){let t=await ie.getInstance();console.log(),console.log(H.bold(H.underline(t.t("config.features.tuiHeader"))));let n=await fa({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:H.dim(t.t("common.cancel")),value:"cancel"}]});if(it(n),n==="cancel")return;let r=n,a=io[r]||{},i={},s=await wn({message:t.t("config.features.customize"),initialValue:!1});if(it(s),!s)return bn(r,o,e);let c=[...new Set(fe.map(l=>l.category))];for(let l of c){let d=fe.filter(u=>u.category===l),m=d.filter(u=>u.type==="boolean"),p=d.filter(u=>u.type==="numeric");if(m.length>0){let u=m.filter(k=>r==="enterprise"||a[k.key]===!0).map(k=>k.key),g=await ha({message:`${l} features:`,options:m.map(k=>({label:`${k.key.padEnd(30)} \u2014 ${k.description}`,value:k.key})),initialValues:u,required:!1});it(g);for(let k of m)i[k.key]=g.includes(k.key)}for(let u of p){let g=r==="enterprise"?"-1":a[u.key]||u.defaultValue,k=await ga({message:`${u.key} (${u.description}):`,placeholder:g,defaultValue:g});it(k),i[u.key]=k}}await xn(i,o,e,r)}async function xn(o,e,t,n){let r=await ie.getInstance(),a=fe.map(s=>{let c=o[s.key];return` { key: "${s.key}", type: "${s.type}", defaultValue: "${c}", description: "${s.description}" },`}).join(`
100
+ `)),console.log(` Cache directory: ${ge.cyan(o.cacheDir)}`),console.log(` Total size: ${ge.cyan(gn(e.totalSize))}`),console.log(` Cached entries: ${ge.cyan(e.entries.toString())}`),e.oldest&&console.log(` Oldest entry: ${ge.gray(e.oldest.toLocaleString())}`),e.newest&&console.log(` Newest entry: ${ge.gray(e.newest.toLocaleString())}`),console.log(),console.log(ge.gray("Run 'kaven cache clear' to remove all cached data."))}async function yn(){let o=co(),e=await o.stats();if(e.entries===0){console.log(ge.gray("Cache is already empty."));return}await o.clear(),console.log(ge.green(`Cache cleared: ${e.entries} entries (${gn(e.totalSize)}) removed.`))}import Z from"chalk";async function wn(o,e){(!o||!e)&&(console.error(Z.red("Error: Both key and value are required")),console.error(Z.gray("Usage: kaven config set KEY VALUE")),process.exit(1)),await G.initialize();try{await G.set(o,e),console.log(Z.green(`\u2705 Set ${Z.bold(o)} = ${Z.bold(e)}`))}catch(t){console.error(Z.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function vn(o,e){o||(console.error(Z.red("Error: Key is required")),console.error(Z.gray("Usage: kaven config get KEY")),process.exit(1)),await G.initialize();try{let t=G.get(o);e.json?console.log(JSON.stringify({[o]:t},null,2)):console.log(t)}catch(t){console.error(Z.red(`Error: ${t instanceof Error?t.message:String(t)}`)),process.exit(1)}}async function kn(o){await G.initialize();let e=G.getAll();if(o.json)console.log(JSON.stringify(e,null,2));else{console.log(Z.bold("Kaven Configuration:")),console.log(Z.gray(`Location: ${G.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,`
101
+ `+" ".repeat(n+3)):a;console.log(` ${r}${i} ${Z.cyan(s)}`)}}}async function bn(){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(Z.yellow("Cancelled."));return}await G.initialize(),await G.reset(),console.log(Z.green("\u2705 Config reset to defaults"))}import{select as wa,confirm as xn,text as va,multiselect as ka,isCancel as ba,cancel as xa}from"@clack/prompts";import W from"picocolors";import uo from"fs-extra";import En from"path";var he=[{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"}],lo={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 st(o){ba(o)&&(xa("Cancelled."),process.exit(0))}async function Cn(o){let e=o.outputPath??En.join(process.cwd(),"packages","database","prisma","seeds","capabilities.seed.ts");if(o.list){let t=await ce.getInstance();Ea(t);return}if(o.tier){await Sn(o.tier,e,o);return}await Ca(e,o)}function Ea(o){console.log(),console.log(W.bold(W.underline(o.t("config.features.catalogHeader")))),console.log(W.dim(o.t("config.features.capabilitiesTotal",{count:he.length})+`
102
+ `));let e=[...new Set(he.map(t=>t.category))];for(let t of e){let n=he.filter(r=>r.category===t);console.log(W.bold(W.cyan(` ${t} (${n.length})`)));for(let r of n)console.log(` ${W.white(r.key.padEnd(30))} ${W.dim(`[${r.type}]`)}`),console.log(` ${W.dim(r.description)}`);console.log()}console.log(W.bold(o.t("config.features.tierPresets")));for(let t of["starter","complete","pro","enterprise"])console.log(` ${W.white(t.padEnd(12))}`);console.log()}async function Sn(o,e,t){let n=lo[o]||{},r={};for(let a of he)o==="enterprise"?r[a.key]=a.type==="boolean"?!0:"-1":r[a.key]=n[a.key]??(a.type==="boolean"?!1:a.defaultValue);await $n(r,e,t,o)}async function Ca(o,e){let t=await ce.getInstance();console.log(),console.log(W.bold(W.underline(t.t("config.features.tuiHeader"))));let n=await wa({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:W.dim(t.t("common.cancel")),value:"cancel"}]});if(st(n),n==="cancel")return;let r=n,a=lo[r]||{},i={},s=await xn({message:t.t("config.features.customize"),initialValue:!1});if(st(s),!s)return Sn(r,o,e);let c=[...new Set(he.map(l=>l.category))];for(let l of c){let d=he.filter(u=>u.category===l),p=d.filter(u=>u.type==="boolean"),m=d.filter(u=>u.type==="numeric");if(p.length>0){let u=p.filter(w=>r==="enterprise"||a[w.key]===!0).map(w=>w.key),f=await ka({message:`${l} features:`,options:p.map(w=>({label:`${w.key.padEnd(30)} \u2014 ${w.description}`,value:w.key})),initialValues:u,required:!1});st(f);for(let w of p)i[w.key]=f.includes(w.key)}for(let u of m){let f=r==="enterprise"?"-1":a[u.key]||u.defaultValue,w=await va({message:`${u.key} (${u.description}):`,placeholder:f,defaultValue:f});st(w),i[u.key]=w}}await $n(i,o,e,r)}async function $n(o,e,t,n){let r=await ce.getInstance(),a=he.map(s=>{let c=o[s.key];return` { key: "${s.key}", type: "${s.type}", defaultValue: "${c}", description: "${s.description}" },`}).join(`
101
103
  `),i=`// packages/database/prisma/seeds/capabilities.seed.ts
102
104
  // Generated by kaven config features \u2014 ${new Date().toISOString()}
103
105
  // Tier: ${n}
@@ -109,7 +111,7 @@ export async function seedCapabilities(prisma: PrismaClient) {
109
111
  ${a}
110
112
  ];
111
113
 
112
- console.log("\u{1F510} Seeding ${fe.length} Capabilities...");
114
+ console.log("\u{1F510} Seeding ${he.length} Capabilities...");
113
115
 
114
116
  for (const cap of capabilities) {
115
117
  await prisma.capability.upsert({
@@ -119,9 +121,9 @@ ${a}
119
121
  });
120
122
  }
121
123
  }
122
- `;if(t.dryRun){console.log(H.bold(`
123
- `+r.t("config.features.dryRunHeader"))),console.log(i);return}if(so.existsSync(e)&&!t.force){let s=await wn({message:r.t("config.features.confirmOverwrite"),initialValue:!1});if(it(s),!s)return}await so.ensureDir(vn.dirname(e)),await so.writeFile(e,i,"utf-8"),console.log(H.green(`
124
- \u2705 ${r.t("config.features.seedWritten",{path:e})}`)),console.log(H.dim(r.t("config.features.runSeed")))}import Z from"chalk";import ba from"ora";import Je from"path";import Ie from"fs-extra";var xa=`name: Tests
124
+ `;if(t.dryRun){console.log(W.bold(`
125
+ `+r.t("config.features.dryRunHeader"))),console.log(i);return}if(uo.existsSync(e)&&!t.force){let s=await xn({message:r.t("config.features.confirmOverwrite"),initialValue:!1});if(st(s),!s)return}await uo.ensureDir(En.dirname(e)),await uo.writeFile(e,i,"utf-8"),console.log(W.green(`
126
+ \u2705 ${r.t("config.features.seedWritten",{path:e})}`)),console.log(W.dim(r.t("config.features.runSeed")))}import Q from"chalk";import Sa from"ora";import Je from"path";import Te from"fs-extra";var $a=`name: Tests
125
127
  on:
126
128
  push:
127
129
  branches: [main, develop]
@@ -157,7 +159,7 @@ jobs:
157
159
  - run: pnpm lint
158
160
  - run: pnpm test
159
161
  - run: pnpm build
160
- `,Ea=`name: Publish Module
162
+ `,Pa=`name: Publish Module
161
163
  on:
162
164
  push:
163
165
  tags:
@@ -181,7 +183,7 @@ jobs:
181
183
  env:
182
184
  KAVEN_LICENSE_KEY: \${{ secrets.KAVEN_LICENSE_KEY }}
183
185
  run: kaven module publish
184
- `,Sa=`#!/bin/bash
186
+ `,Ma=`#!/bin/bash
185
187
  # Pre-commit hook for Kaven projects
186
188
  set -e
187
189
 
@@ -202,7 +204,7 @@ if command -v pnpm format &> /dev/null; then
202
204
  fi
203
205
 
204
206
  echo "\u2705 All pre-commit checks passed"
205
- `;async function En(o){let e=process.cwd(),t=Je.join(e,"package.json");await Ie.pathExists(t)||(console.error(Z.red("Error: package.json not found. Run this in a Kaven project root.")),process.exit(1));let n=ba("Setting up CI/CD configuration...").start();try{let r=Je.join(e,".github","workflows");await Ie.ensureDir(r);let a=Je.join(r,"test.yml");o.dryRun||await Ie.writeFile(a,xa),n.text=`Creating ${Z.cyan(".github/workflows/test.yml")}...`;let i=Je.join(r,"publish.yml");o.dryRun||await Ie.writeFile(i,Ea),n.text=`Creating ${Z.cyan(".github/workflows/publish.yml")}...`;let s=Je.join(e,".husky");await Ie.ensureDir(s);let c=Je.join(s,"pre-commit");o.dryRun||(await Ie.writeFile(c,Sa),await Ie.chmod(c,493)),n.text=`Creating ${Z.cyan(".husky/pre-commit")}...`,n.succeed("CI/CD configuration created"),console.log(),console.log(Z.bold("Files created:")),console.log(` ${Z.cyan(".github/workflows/test.yml")} - Run tests on push/PR`),console.log(` ${Z.cyan(".github/workflows/publish.yml")} - Publish on git tags`),console.log(` ${Z.cyan(".husky/pre-commit")} - Local pre-commit validation`),console.log(),console.log(Z.bold("Next steps:")),console.log(Z.gray(" 1. Install husky: pnpm husky install")),console.log(Z.gray(" 2. Add GitHub secrets: KAVEN_LICENSE_KEY")),console.log(Z.gray(" 3. Push to GitHub and watch workflows run")),o.dryRun&&(console.log(),console.log(Z.yellow("(Dry-run: No files were actually created)")))}catch(r){n.fail("Failed to create CI/CD configuration"),console.error(Z.red(r instanceof Error?r.message:String(r))),process.exit(1)}}function Sn(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 Ct(n,t)})}var $a=()=>{let o=new Ca;o.name("kaven").description("The official CLI for the Kaven SaaS boilerplate ecosystem").version("0.4.2-alpha.0").addHelpText("after",`
207
+ `;async function Pn(o){let e=process.cwd(),t=Je.join(e,"package.json");await Te.pathExists(t)||(console.error(Q.red("Error: package.json not found. Run this in a Kaven project root.")),process.exit(1));let n=Sa("Setting up CI/CD configuration...").start();try{let r=Je.join(e,".github","workflows");await Te.ensureDir(r);let a=Je.join(r,"test.yml");o.dryRun||await Te.writeFile(a,$a),n.text=`Creating ${Q.cyan(".github/workflows/test.yml")}...`;let i=Je.join(r,"publish.yml");o.dryRun||await Te.writeFile(i,Pa),n.text=`Creating ${Q.cyan(".github/workflows/publish.yml")}...`;let s=Je.join(e,".husky");await Te.ensureDir(s);let c=Je.join(s,"pre-commit");o.dryRun||(await Te.writeFile(c,Ma),await Te.chmod(c,493)),n.text=`Creating ${Q.cyan(".husky/pre-commit")}...`,n.succeed("CI/CD configuration created"),console.log(),console.log(Q.bold("Files created:")),console.log(` ${Q.cyan(".github/workflows/test.yml")} - Run tests on push/PR`),console.log(` ${Q.cyan(".github/workflows/publish.yml")} - Publish on git tags`),console.log(` ${Q.cyan(".husky/pre-commit")} - Local pre-commit validation`),console.log(),console.log(Q.bold("Next steps:")),console.log(Q.gray(" 1. Install husky: pnpm husky install")),console.log(Q.gray(" 2. Add GitHub secrets: KAVEN_LICENSE_KEY")),console.log(Q.gray(" 3. Push to GitHub and watch workflows run")),o.dryRun&&(console.log(),console.log(Q.yellow("(Dry-run: No files were actually created)")))}catch(r){n.fail("Failed to create CI/CD configuration"),console.error(Q.red(r instanceof Error?r.message:String(r))),process.exit(1)}}function Mn(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 $t(n,t)})}var ja=()=>{let o=new Aa;o.name("kaven").description("The official CLI for the Kaven SaaS boilerplate ecosystem").version("0.4.2-alpha.0").addHelpText("after",`
206
208
  Examples:
207
209
  $ kaven init my-saas-app Bootstrap a new Kaven project
208
210
  $ kaven auth login Authenticate with Kaven Marketplace
@@ -219,7 +221,7 @@ Examples:
219
221
  $ kaven init my-app --defaults Use defaults (no prompts)
220
222
  $ kaven init my-app --skip-git Skip git initialization
221
223
  $ kaven init my-app --with-squad Install kaven-squad for AIOX integration
222
- `).action((c,l)=>en(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",`
224
+ `).action((c,l)=>rn(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",`
223
225
  Examples:
224
226
  $ kaven module doctor Check module integrity
225
227
  $ kaven module doctor --fix Auto-fix detected issues
@@ -239,15 +241,15 @@ Examples:
239
241
  $ kaven module doctor
240
242
  $ kaven module doctor --fix
241
243
  $ kaven module doctor --json
242
- `).action(c=>yo({fix:c.fix,json:c.json})),e.command("add <path>").description("Install a module from a local manifest file").addHelpText("after",`
244
+ `).action(c=>ko({fix:c.fix,json:c.json})),e.command("add <path>").description("Install a module from a local manifest file").addHelpText("after",`
243
245
  Examples:
244
246
  $ kaven module add ./modules/payments/module.json
245
247
  $ kaven module add /absolute/path/to/module.json
246
- `).action(c=>ko(c)),e.command("remove <name>").description("Remove an installed module and clean up injected code").addHelpText("after",`
248
+ `).action(c=>Eo(c)),e.command("remove <name>").description("Remove an installed module and clean up injected code").addHelpText("after",`
247
249
  Examples:
248
250
  $ kaven module remove payments
249
251
  $ kaven module remove notifications
250
- `).action(c=>bo(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",`
252
+ `).action(c=>Co(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",`
251
253
  Requirements:
252
254
  - module.json must exist in the current directory
253
255
  - Must be authenticated: run 'kaven auth login' first
@@ -256,7 +258,7 @@ Examples:
256
258
  $ kaven module publish
257
259
  $ kaven module publish --dry-run
258
260
  $ kaven module publish --changelog "Added dark mode support"
259
- `).action(c=>Po({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",`
261
+ `).action(c=>jo({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",`
260
262
  Modules: billing, projects, notifications
261
263
 
262
264
  Examples:
@@ -264,18 +266,18 @@ Examples:
264
266
  $ kaven module activate projects
265
267
  $ kaven module activate projects ./my-app
266
268
  $ kaven module activate billing --with-deps
267
- `).action((c,l,d)=>Jt(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",`
269
+ `).action((c,l,d)=>zt(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",`
268
270
  Modules: billing, projects, notifications
269
271
 
270
272
  Examples:
271
273
  $ kaven module deactivate billing
272
274
  $ kaven module deactivate projects
273
275
  $ kaven module deactivate projects ./my-app
274
- `).action((c,l,d)=>Io(c,l,d)),e.command("list [root]").description("List available Kaven schema modules with their status, models, and dependencies").addHelpText("after",`
276
+ `).action((c,l,d)=>Do(c,l,d)),e.command("list [root]").description("List available Kaven schema modules with their status, models, and dependencies").addHelpText("after",`
275
277
  Examples:
276
278
  $ kaven module list
277
279
  $ kaven module list ./my-app
278
- `).action(c=>To(c)),e.command("update [slug]").description("Update an installed marketplace module to the latest version").option("--skip-verify","Skip Ed25519 signature verification (dev only)").addHelpText("after",`
280
+ `).action(c=>_o(c)),e.command("update [slug]").description("Update an installed marketplace module to the latest version").option("--skip-verify","Skip Ed25519 signature verification (dev only)").addHelpText("after",`
279
281
  Examples:
280
282
  $ kaven module update payments Update the payments module
281
283
  $ kaven module update Interactive: select module to update
@@ -285,43 +287,43 @@ Examples:
285
287
  $ kaven auth login Start device code authentication flow
286
288
  $ kaven auth whoami Show current user info
287
289
  $ kaven auth logout End the local session
288
- `);t.command("login").description("Start the interactive device code authentication flow (RFC 8628)").action(()=>Do()),t.command("logout").description("Clear the local authentication session").action(()=>_o()),t.command("whoami").description("Display information about the currently authenticated user").action(()=>Lo());let n=o.command("marketplace").alias("mkt").alias("market").description("Explore, browse, and install modules from the Kaven Marketplace").addHelpText("after",`
290
+ `);t.command("login").description("Start the interactive device code authentication flow (RFC 8628)").action(()=>Oo()),t.command("logout").description("Clear the local authentication session").action(()=>Fo()),t.command("whoami").description("Display information about the currently authenticated user").action(()=>Uo());let n=o.command("marketplace").alias("mkt").alias("market").description("Explore, browse, and install modules from the Kaven Marketplace").addHelpText("after",`
289
291
  Examples:
290
292
  $ kaven marketplace list
291
293
  $ kaven marketplace list --category auth --sort popular
292
294
  $ kaven marketplace install payments
293
295
  $ kaven marketplace browse
294
- `);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=>Oo({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",`
296
+ `);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=>No({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",`
295
297
  Examples:
296
298
  $ kaven marketplace install payments
297
299
  $ kaven marketplace install payments --version 1.2.0
298
300
  $ kaven marketplace install auth --skip-env
299
301
  $ kaven marketplace install my-module --skip-verify
300
- `).action((c,l)=>kt(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",`
302
+ `).action((c,l)=>bt(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",`
301
303
  Navigate with arrow keys, press Enter to select.
302
304
  Supports category filtering and pagination.
303
- `).action(()=>Ko()),o.command("update").description("Check and apply updates for CLI and installed modules").option("--core","Update only the CLI itself").option("--module <slug>","Update a specific installed module").option("--all","Apply all available updates (CLI + modules)").option("--check","Check for updates without applying").option("--skip-verify","Skip Ed25519 signature verification (dev only)").addHelpText("after",`
305
+ `).action(()=>zo()),o.command("update").description("Check and apply updates for CLI and installed modules").option("--core","Update only the CLI itself").option("--module <slug>","Update a specific installed module").option("--all","Apply all available updates (CLI + modules)").option("--check","Check for updates without applying").option("--skip-verify","Skip Ed25519 signature verification (dev only)").addHelpText("after",`
304
306
  Examples:
305
307
  $ kaven update Check all updates (CLI + modules)
306
308
  $ kaven update --core Check/apply CLI update only
307
309
  $ kaven update --module payments Update the payments module
308
310
  $ kaven update --all Apply all updates
309
311
  $ kaven update --check List updates without applying
310
- `).action(c=>dn({core:c.core,module:c.module,all:c.all,check:c.check,skipVerify:c.skipVerify}));let r=o.command("upgrade").description("Upgrade your Kaven license plan").addHelpText("after",`
312
+ `).action(c=>fn({core:c.core,module:c.module,all:c.all,check:c.check,skipVerify:c.skipVerify}));let r=o.command("upgrade").description("Upgrade your Kaven license plan").addHelpText("after",`
311
313
  Examples:
312
314
  $ kaven upgrade Upgrade license tier (interactive)
313
315
  $ kaven upgrade check Check current license status
314
316
  $ kaven upgrade install Force install latest CLI (manual)
315
317
 
316
318
  Note: To update the CLI or modules, use \`kaven update\` instead.
317
- `);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=>cn({browser:c.browser!==!1})),r.command("check").description("Check current license status").action(()=>eo()),r.command("install").description("Force install the latest Kaven CLI version globally").action(()=>to()),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=>Vo(parseInt(c.limit))),o.addCommand(Ho());let i=o.command("cache").description("Manage the local API response cache").addHelpText("after",`
319
+ `);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=>pn({browser:c.browser!==!1})),r.command("check").description("Check current license status").action(()=>no()),r.command("install").description("Force install the latest Kaven CLI version globally").action(()=>ro()),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=>Ho(parseInt(c.limit))),o.addCommand(Yo());let i=o.command("cache").description("Manage the local API response cache").addHelpText("after",`
318
320
  Cache directory: ~/.kaven/cache (max 50 MB)
319
321
  Cached data: module listings (24h TTL), manifests (7d), license status (1h)
320
322
 
321
323
  Examples:
322
324
  $ kaven cache status
323
325
  $ kaven cache clear
324
- `);i.command("status").description("Show cache statistics (size, entry count, age)").action(()=>pn()),i.command("clear").description("Delete all locally cached API responses").action(()=>mn());let s=o.command("config").description("Manage Kaven CLI configuration").addHelpText("after",`
326
+ `);i.command("status").description("Show cache statistics (size, entry count, age)").action(()=>hn()),i.command("clear").description("Delete all locally cached API responses").action(()=>yn());let s=o.command("config").description("Manage Kaven CLI configuration").addHelpText("after",`
325
327
  Config file: ~/.kaven/config.json
326
328
 
327
329
  Examples:
@@ -332,7 +334,7 @@ Examples:
332
334
  $ kaven config features
333
335
  $ kaven config features --tier complete
334
336
  $ kaven config features --list
335
- `);s.command("set <key> <value>").description("Set a configuration value").action((c,l)=>fn(c,l)),s.command("get <key>").description("Get a configuration value").option("--json","Output as JSON").action((c,l)=>gn(c,{json:l.json})),s.command("view").description("Display all configuration").option("--json","Output as JSON").action(c=>hn({json:c.json})),s.command("reset").description("Reset configuration to defaults").action(()=>yn()),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",`
337
+ `);s.command("set <key> <value>").description("Set a configuration value").action((c,l)=>wn(c,l)),s.command("get <key>").description("Get a configuration value").option("--json","Output as JSON").action((c,l)=>vn(c,{json:l.json})),s.command("view").description("Display all configuration").option("--json","Output as JSON").action(c=>kn({json:c.json})),s.command("reset").description("Reset configuration to defaults").action(()=>bn()),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",`
336
338
  Output: packages/database/prisma/seeds/capabilities.seed.ts (relative to cwd)
337
339
 
338
340
  Examples:
@@ -343,7 +345,7 @@ Examples:
343
345
 
344
346
  After generating the seed file:
345
347
  $ pnpm prisma db seed
346
- `).action(c=>kn({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",`
348
+ `).action(c=>Cn({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",`
347
349
  Creates:
348
350
  - .github/workflows/test.yml Run tests on push/PR
349
351
  - .github/workflows/publish.yml Publish modules on git tags
@@ -352,4 +354,4 @@ Creates:
352
354
  Examples:
353
355
  $ kaven init-ci Interactive setup
354
356
  $ kaven init-ci --dry-run Show what would be created
355
- `).action(c=>En({dryRun:c.dryRun})),Sn(o),o.parse(process.argv)},Pa=process.argv[1]&&(process.argv[1].endsWith("/kaven")||process.argv[1].endsWith("/index.ts")||process.argv[1].endsWith("/index.js"));Pa&&$a();export{$a as main};
357
+ `).action(c=>Pn({dryRun:c.dryRun})),Mn(o),o.parse(process.argv)},Ta=process.argv[1]&&(process.argv[1].endsWith("/kaven")||process.argv[1].endsWith("/index.ts")||process.argv[1].endsWith("/index.js"));Ta&&ja();export{ja as main};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaven-cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Kaven CLI - The official command line tool for Kaven",
6
6
  "main": "dist/index.js",