kaven-cli 0.1.0-alpha.1 → 0.3.5

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 (50) hide show
  1. package/README.md +284 -45
  2. package/README.pt-BR.md +334 -0
  3. package/dist/commands/auth/login.js +97 -19
  4. package/dist/commands/auth/logout.js +4 -6
  5. package/dist/commands/auth/whoami.js +12 -11
  6. package/dist/commands/cache/index.js +43 -0
  7. package/dist/commands/config/index.js +128 -0
  8. package/dist/commands/init/index.js +209 -0
  9. package/dist/commands/init-ci/index.js +153 -0
  10. package/dist/commands/license/index.js +10 -0
  11. package/dist/commands/license/status.js +44 -0
  12. package/dist/commands/license/tier-table.js +46 -0
  13. package/dist/commands/marketplace/browse.js +219 -0
  14. package/dist/commands/marketplace/install.js +233 -29
  15. package/dist/commands/marketplace/list.js +94 -16
  16. package/dist/commands/module/doctor.js +143 -38
  17. package/dist/commands/module/publish.js +291 -0
  18. package/dist/commands/upgrade/check.js +162 -0
  19. package/dist/commands/upgrade/index.js +218 -0
  20. package/dist/core/AuthService.js +207 -14
  21. package/dist/core/CacheManager.js +151 -0
  22. package/dist/core/ConfigManager.js +165 -0
  23. package/dist/core/EnvManager.js +196 -0
  24. package/dist/core/ErrorRecovery.js +191 -0
  25. package/dist/core/LicenseService.js +118 -0
  26. package/dist/core/ModuleDoctor.js +290 -4
  27. package/dist/core/ModuleInstaller.js +136 -2
  28. package/dist/core/ProjectInitializer.js +154 -0
  29. package/dist/core/RegistryResolver.js +94 -0
  30. package/dist/core/ScriptRunner.js +72 -0
  31. package/dist/core/SignatureVerifier.js +75 -0
  32. package/dist/index.js +265 -20
  33. package/dist/infrastructure/MarketplaceClient.js +388 -64
  34. package/dist/infrastructure/errors.js +61 -0
  35. package/dist/types/auth.js +2 -0
  36. package/dist/types/marketplace.js +2 -0
  37. package/package.json +23 -4
  38. package/dist/commands/modules/add.js +0 -53
  39. package/dist/commands/modules/list.js +0 -40
  40. package/dist/commands/modules/remove.js +0 -54
  41. package/dist/core/api/KavenApiClient.js +0 -61
  42. package/dist/core/auth/AuthManager.js +0 -91
  43. package/dist/core/modules/Injector.js +0 -86
  44. package/dist/core/modules/ModuleInstaller.js +0 -63
  45. package/dist/core/modules/ModuleManager.js +0 -59
  46. package/dist/core/modules/ModuleRemover.js +0 -60
  47. package/dist/lib/config.js +0 -66
  48. package/dist/lib/errors.js +0 -32
  49. package/dist/lib/logger.js +0 -70
  50. package/dist/types/module.js +0 -49
@@ -0,0 +1,291 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.moduleJsonSchema = void 0;
40
+ exports.modulePublish = modulePublish;
41
+ const chalk_1 = __importDefault(require("chalk"));
42
+ const ora_1 = __importDefault(require("ora"));
43
+ const path_1 = __importDefault(require("path"));
44
+ const fs_extra_1 = __importDefault(require("fs-extra"));
45
+ const crypto_1 = __importDefault(require("crypto"));
46
+ const os_1 = __importDefault(require("os"));
47
+ const zod_1 = require("zod");
48
+ const AuthService_1 = require("../../core/AuthService");
49
+ const MarketplaceClient_1 = require("../../infrastructure/MarketplaceClient");
50
+ // Zod schema for module.json
51
+ exports.moduleJsonSchema = zod_1.z.object({
52
+ name: zod_1.z.string().min(1),
53
+ slug: zod_1.z.string().min(1).regex(/^[a-z0-9-]+$/),
54
+ version: zod_1.z.string().regex(/^\d+\.\d+\.\d+$/),
55
+ description: zod_1.z.string().min(1),
56
+ author: zod_1.z.string().optional(),
57
+ license: zod_1.z.string().optional(),
58
+ tier: zod_1.z.enum(["free", "starter", "complete", "pro"]),
59
+ });
60
+ const SIGNING_KEY_PATH = path_1.default.join(os_1.default.homedir(), ".kaven", "signing-key.json");
61
+ /** Load or generate Ed25519 signing key pair. */
62
+ async function getSigningKey() {
63
+ if (await fs_extra_1.default.pathExists(SIGNING_KEY_PATH)) {
64
+ try {
65
+ const stored = await fs_extra_1.default.readJson(SIGNING_KEY_PATH);
66
+ const privateKey = crypto_1.default.createPrivateKey({
67
+ key: Buffer.from(stored.privateKey, "base64"),
68
+ type: "pkcs8",
69
+ format: "der",
70
+ });
71
+ const publicKey = crypto_1.default.createPublicKey(privateKey);
72
+ return { privateKey, publicKey };
73
+ }
74
+ catch {
75
+ // Fall through to generate new key
76
+ }
77
+ }
78
+ const { privateKey, publicKey } = crypto_1.default.generateKeyPairSync("ed25519");
79
+ const privateKeyDer = privateKey.export({ type: "pkcs8", format: "der" });
80
+ const publicKeyDer = publicKey.export({ type: "spki", format: "der" });
81
+ await fs_extra_1.default.ensureDir(path_1.default.dirname(SIGNING_KEY_PATH));
82
+ await fs_extra_1.default.writeJson(SIGNING_KEY_PATH, {
83
+ privateKey: privateKeyDer.toString("base64"),
84
+ publicKey: publicKeyDer.toString("base64"),
85
+ }, { spaces: 2 });
86
+ if (process.platform !== "win32") {
87
+ await fs_extra_1.default.chmod(SIGNING_KEY_PATH, 0o600);
88
+ }
89
+ return { privateKey, publicKey };
90
+ }
91
+ /** Generate SHA-256 checksum of a file. */
92
+ async function sha256File(filePath) {
93
+ const data = await fs_extra_1.default.readFile(filePath);
94
+ return crypto_1.default.createHash("sha256").update(data).digest("hex");
95
+ }
96
+ /** Create tar.gz archive of current directory, excluding common noise. */
97
+ async function createTarball(sourceDir, outputPath) {
98
+ const tar = await Promise.resolve().then(() => __importStar(require("tar")));
99
+ await tar.create({
100
+ gzip: true,
101
+ file: outputPath,
102
+ cwd: sourceDir,
103
+ filter: (filePath) => {
104
+ const normalized = filePath.replace(/\\/g, "/");
105
+ const excluded = [
106
+ "node_modules",
107
+ ".git",
108
+ "dist",
109
+ ".env",
110
+ ];
111
+ for (const exc of excluded) {
112
+ if (normalized.startsWith(exc + "/") ||
113
+ normalized === exc ||
114
+ normalized.endsWith(".log")) {
115
+ return false;
116
+ }
117
+ }
118
+ return true;
119
+ },
120
+ }, ["."]);
121
+ }
122
+ async function modulePublish(options) {
123
+ const cwd = process.cwd();
124
+ // 1. Read and validate module.json
125
+ const moduleJsonPath = path_1.default.join(cwd, "module.json");
126
+ if (!(await fs_extra_1.default.pathExists(moduleJsonPath))) {
127
+ console.error(chalk_1.default.red("Error: module.json not found in current directory."));
128
+ console.error(chalk_1.default.gray("Try: run this command from inside a module directory"));
129
+ process.exit(1);
130
+ }
131
+ let moduleJson;
132
+ try {
133
+ const raw = await fs_extra_1.default.readJson(moduleJsonPath);
134
+ const result = exports.moduleJsonSchema.safeParse(raw);
135
+ if (!result.success) {
136
+ console.error(chalk_1.default.red("Error: Invalid module.json:"));
137
+ for (const issue of result.error.issues) {
138
+ console.error(chalk_1.default.red(` - ${issue.path.join(".")}: ${issue.message}`));
139
+ }
140
+ process.exit(1);
141
+ }
142
+ moduleJson = result.data;
143
+ }
144
+ catch (error) {
145
+ console.error(chalk_1.default.red(`Error: Failed to parse module.json: ${error instanceof Error ? error.message : String(error)}`));
146
+ process.exit(1);
147
+ }
148
+ console.log();
149
+ console.log(chalk_1.default.bold(`Publishing module: ${moduleJson.name} v${moduleJson.version}`));
150
+ console.log(chalk_1.default.gray(`Slug: ${moduleJson.slug} | Tier: ${moduleJson.tier}`));
151
+ console.log();
152
+ // 2. Create tar.gz
153
+ const tarballPath = path_1.default.join(os_1.default.tmpdir(), `kaven-${moduleJson.slug}-${moduleJson.version}.tar.gz`);
154
+ const packageSpinner = (0, ora_1.default)("Creating module package...").start();
155
+ try {
156
+ await createTarball(cwd, tarballPath);
157
+ const stats = await fs_extra_1.default.stat(tarballPath);
158
+ packageSpinner.succeed(`Package created (${(stats.size / 1024).toFixed(1)} KB)`);
159
+ }
160
+ catch (error) {
161
+ packageSpinner.fail("Failed to create package");
162
+ console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
163
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
164
+ process.exit(1);
165
+ }
166
+ // 3. Generate checksum
167
+ const checksumSpinner = (0, ora_1.default)("Computing SHA-256 checksum...").start();
168
+ let checksum;
169
+ try {
170
+ checksum = await sha256File(tarballPath);
171
+ checksumSpinner.succeed(`Checksum: ${checksum.substring(0, 16)}...`);
172
+ }
173
+ catch {
174
+ checksumSpinner.fail("Failed to compute checksum");
175
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
176
+ process.exit(1);
177
+ return;
178
+ }
179
+ // 4. Sign the checksum
180
+ const signSpinner = (0, ora_1.default)("Signing package...").start();
181
+ let signatureBase64;
182
+ let publicKeyBase64;
183
+ try {
184
+ const { privateKey, publicKey } = await getSigningKey();
185
+ const signature = crypto_1.default.sign(null, Buffer.from(checksum), privateKey);
186
+ signatureBase64 = signature.toString("base64");
187
+ const publicKeyDer = publicKey.export({
188
+ type: "spki", format: "der",
189
+ });
190
+ publicKeyBase64 = publicKeyDer.toString("base64");
191
+ signSpinner.succeed(`Package signed (${signatureBase64.substring(0, 16)}...)`);
192
+ }
193
+ catch {
194
+ signSpinner.fail("Failed to sign package");
195
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
196
+ process.exit(1);
197
+ return;
198
+ }
199
+ if (options.dryRun) {
200
+ console.log();
201
+ console.log(chalk_1.default.yellow("Dry-run mode: skipping upload and release creation."));
202
+ console.log(chalk_1.default.green("✅ Package validated successfully."));
203
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
204
+ return;
205
+ }
206
+ // 5. Get presigned upload URL
207
+ const authService = new AuthService_1.AuthService();
208
+ try {
209
+ await authService.getValidToken();
210
+ }
211
+ catch {
212
+ console.error(chalk_1.default.red("Error: Not authenticated. Run 'kaven auth login' first."));
213
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
214
+ process.exit(1);
215
+ return;
216
+ }
217
+ const client = new MarketplaceClient_1.MarketplaceClient(authService);
218
+ const stats = await fs_extra_1.default.stat(tarballPath);
219
+ const urlSpinner = (0, ora_1.default)("Getting upload URL...").start();
220
+ let uploadUrl;
221
+ let s3Key;
222
+ try {
223
+ const uploadUrlResult = await client.getUploadUrl(moduleJson.slug, moduleJson.version, stats.size);
224
+ uploadUrl = uploadUrlResult.uploadUrl;
225
+ s3Key = uploadUrlResult.s3Key;
226
+ urlSpinner.succeed("Upload URL received");
227
+ }
228
+ catch (error) {
229
+ urlSpinner.fail("Failed to get upload URL");
230
+ console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
231
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
232
+ process.exit(1);
233
+ return;
234
+ }
235
+ // 6. Upload tar.gz to presigned URL
236
+ const uploadSpinner = (0, ora_1.default)(`Uploading package (${(stats.size / 1024).toFixed(1)} KB)...`).start();
237
+ try {
238
+ const fileBuffer = await fs_extra_1.default.readFile(tarballPath);
239
+ const response = await fetch(uploadUrl, {
240
+ method: "PUT",
241
+ headers: {
242
+ "Content-Type": "application/gzip",
243
+ "Content-Length": String(stats.size),
244
+ },
245
+ body: fileBuffer,
246
+ });
247
+ if (!response.ok) {
248
+ throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
249
+ }
250
+ uploadSpinner.succeed("Package uploaded successfully");
251
+ }
252
+ catch (error) {
253
+ uploadSpinner.fail("Upload failed");
254
+ console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
255
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
256
+ process.exit(1);
257
+ return;
258
+ }
259
+ // 7. Create release record
260
+ const releaseSpinner = (0, ora_1.default)("Creating release record...").start();
261
+ try {
262
+ const release = await client.createRelease({
263
+ moduleSlug: moduleJson.slug,
264
+ version: moduleJson.version,
265
+ s3Key,
266
+ checksum,
267
+ signature: signatureBase64,
268
+ publicKey: publicKeyBase64,
269
+ changelog: options.changelog,
270
+ });
271
+ releaseSpinner.succeed(`Release created: ${moduleJson.slug}@${release.version} (ID: ${release.id})`);
272
+ }
273
+ catch (error) {
274
+ releaseSpinner.fail("Failed to create release");
275
+ console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
276
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
277
+ process.exit(1);
278
+ return;
279
+ }
280
+ // Cleanup temp file
281
+ await fs_extra_1.default.remove(tarballPath).catch(() => { });
282
+ console.log();
283
+ console.log(chalk_1.default.green(`✅ Published ${moduleJson.name} v${moduleJson.version} to the Kaven Marketplace!`));
284
+ console.log(chalk_1.default.gray(`View your module at: https://marketplace.kaven.sh/modules/${moduleJson.slug}`));
285
+ // Show next steps
286
+ console.log();
287
+ console.log(chalk_1.default.bold("Next steps:"));
288
+ console.log(chalk_1.default.gray(" 1. Share your module with the community"));
289
+ console.log(chalk_1.default.gray(" 2. Monitor installation metrics"));
290
+ console.log(chalk_1.default.gray(" 3. Update module with 'kaven module publish' when ready"));
291
+ }
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.upgradeCheck = upgradeCheck;
7
+ exports.upgradeInstall = upgradeInstall;
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const ora_1 = __importDefault(require("ora"));
10
+ const path_1 = __importDefault(require("path"));
11
+ const child_process_1 = require("child_process");
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const packageJsonPath = path_1.default.join(__dirname, "../../..", "package.json");
14
+ const PACKAGE_JSON = JSON.parse(fs_1.default.readFileSync(packageJsonPath, "utf8"));
15
+ const CURRENT_VERSION = PACKAGE_JSON.version;
16
+ const CLI_NAME = "kaven-cli";
17
+ /**
18
+ * C2.3: Check for CLI updates
19
+ */
20
+ async function upgradeCheck() {
21
+ const spinner = (0, ora_1.default)("Checking for updates...").start();
22
+ try {
23
+ // Fetch latest version from npm registry
24
+ const response = await fetch(`https://registry.npmjs.org/${CLI_NAME}`);
25
+ if (!response.ok) {
26
+ spinner.fail("Could not check for updates");
27
+ return;
28
+ }
29
+ const data = (await response.json());
30
+ const distTags = data["dist-tags"];
31
+ const latestVersion = distTags?.latest || CURRENT_VERSION;
32
+ spinner.stop();
33
+ console.log();
34
+ console.log(chalk_1.default.bold("Version Check:"));
35
+ console.log(` Current: ${chalk_1.default.cyan(CURRENT_VERSION)}`);
36
+ console.log(` Latest: ${chalk_1.default.cyan(latestVersion)}`);
37
+ console.log();
38
+ if (latestVersion === CURRENT_VERSION) {
39
+ console.log(chalk_1.default.green("✅ You're on the latest version!"));
40
+ return;
41
+ }
42
+ // Check if update available
43
+ const current = parseVersion(CURRENT_VERSION);
44
+ const latest = parseVersion(latestVersion);
45
+ if (latest.major > current.major ||
46
+ (latest.major === current.major && latest.minor > current.minor) ||
47
+ (latest.major === current.major &&
48
+ latest.minor === current.minor &&
49
+ latest.patch > current.patch)) {
50
+ console.log(chalk_1.default.yellow(`⚠ Update available: ${latestVersion}`));
51
+ console.log();
52
+ console.log(chalk_1.default.bold("To upgrade, run:"));
53
+ console.log(chalk_1.default.cyan(` npm install -g ${CLI_NAME}@latest`));
54
+ console.log(chalk_1.default.cyan(` or`));
55
+ console.log(chalk_1.default.cyan(` pnpm add -g ${CLI_NAME}@latest`));
56
+ console.log();
57
+ console.log(chalk_1.default.gray("Release notes: https://github.com/kaven-co/kaven-cli/releases"));
58
+ }
59
+ else {
60
+ console.log(chalk_1.default.green("✅ You're on the latest version!"));
61
+ }
62
+ }
63
+ catch (error) {
64
+ spinner.fail(`Check failed: ${error instanceof Error ? error.message : String(error)}`);
65
+ console.log(chalk_1.default.gray("You can manually check at: https://www.npmjs.com/package/kaven-cli"));
66
+ }
67
+ }
68
+ /**
69
+ * C2.3: Install latest CLI version
70
+ */
71
+ async function upgradeInstall() {
72
+ console.log();
73
+ const spinner = (0, ora_1.default)("Fetching latest version...").start();
74
+ try {
75
+ // Get latest version
76
+ const response = await fetch(`https://registry.npmjs.org/${CLI_NAME}`);
77
+ if (!response.ok) {
78
+ throw new Error("Failed to fetch package info");
79
+ }
80
+ const data = (await response.json());
81
+ const distTags = data["dist-tags"];
82
+ const latestVersion = distTags?.latest || CURRENT_VERSION;
83
+ if (latestVersion === CURRENT_VERSION) {
84
+ spinner.succeed("Already on latest version");
85
+ return;
86
+ }
87
+ spinner.text = `Installing ${CLI_NAME}@${latestVersion}...`;
88
+ // Determine package manager
89
+ const packageManager = process.env.npm_config_user_agent?.includes("pnpm")
90
+ ? "pnpm"
91
+ : "npm";
92
+ // Install with appropriate package manager
93
+ const exitCode = await runCommand(packageManager, [
94
+ "install",
95
+ "-g",
96
+ `${CLI_NAME}@${latestVersion}`,
97
+ ]);
98
+ if (exitCode !== 0) {
99
+ spinner.fail(`Installation failed with exit code ${exitCode}`);
100
+ console.error(chalk_1.default.gray(`Try: ${packageManager} install -g ${CLI_NAME}@latest`));
101
+ process.exit(1);
102
+ return;
103
+ }
104
+ spinner.succeed(`Updated to ${latestVersion}`);
105
+ // Health check after install
106
+ const healthSpinner = (0, ora_1.default)("Running health check...").start();
107
+ const health = await verifyInstallation();
108
+ if (health.ok) {
109
+ healthSpinner.succeed("Installation verified");
110
+ console.log();
111
+ console.log(chalk_1.default.green("✅ CLI upgraded successfully!"));
112
+ console.log(chalk_1.default.gray("Try: kaven --version"));
113
+ }
114
+ else {
115
+ healthSpinner.warn("Installation verification failed");
116
+ console.log(chalk_1.default.yellow(health.errors.join("\n")));
117
+ }
118
+ }
119
+ catch (error) {
120
+ spinner.fail(`Installation failed: ${error instanceof Error ? error.message : String(error)}`);
121
+ process.exit(1);
122
+ }
123
+ }
124
+ /**
125
+ * Verify CLI installation is working
126
+ */
127
+ async function verifyInstallation() {
128
+ const errors = [];
129
+ try {
130
+ // Check if kaven command is available
131
+ const code = await runCommand("kaven", ["--version"], { stdio: "pipe" });
132
+ if (code !== 0) {
133
+ errors.push("kaven command not available in PATH");
134
+ }
135
+ }
136
+ catch {
137
+ errors.push("Could not execute kaven command");
138
+ }
139
+ return { ok: errors.length === 0, errors };
140
+ }
141
+ /**
142
+ * Run shell command
143
+ */
144
+ function runCommand(cmd, args, options) {
145
+ return new Promise((resolve, reject) => {
146
+ const proc = (0, child_process_1.spawn)(cmd, args, options || { stdio: "inherit" });
147
+ proc.on("error", reject);
148
+ proc.on("close", (code) => resolve(code ?? 0));
149
+ });
150
+ }
151
+ /**
152
+ * Parse semver version
153
+ */
154
+ function parseVersion(version) {
155
+ const cleaned = version.replace(/^v/, "").split("-")[0];
156
+ const [major, minor, patch] = cleaned.split(".").map(Number);
157
+ return {
158
+ major: major || 0,
159
+ minor: minor || 0,
160
+ patch: patch || 0,
161
+ };
162
+ }
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.upgradeInstall = exports.upgradeCheck = void 0;
40
+ exports.upgradeCommand = upgradeCommand;
41
+ const chalk_1 = __importDefault(require("chalk"));
42
+ const ora_1 = __importDefault(require("ora"));
43
+ const open_1 = __importDefault(require("open"));
44
+ const path_1 = __importDefault(require("path"));
45
+ const fs_extra_1 = __importDefault(require("fs-extra"));
46
+ const os_1 = __importDefault(require("os"));
47
+ const AuthService_1 = require("../../core/AuthService");
48
+ const MarketplaceClient_1 = require("../../infrastructure/MarketplaceClient");
49
+ const check_1 = require("./check");
50
+ Object.defineProperty(exports, "upgradeCheck", { enumerable: true, get: function () { return check_1.upgradeCheck; } });
51
+ Object.defineProperty(exports, "upgradeInstall", { enumerable: true, get: function () { return check_1.upgradeInstall; } });
52
+ const LICENSE_PATH = path_1.default.join(os_1.default.homedir(), ".kaven", "license.json");
53
+ const TIERS = ["starter", "complete", "pro", "enterprise"];
54
+ const TIER_LABELS = {
55
+ starter: "Starter",
56
+ complete: "Complete",
57
+ pro: "Pro",
58
+ enterprise: "Enterprise",
59
+ };
60
+ const POLL_INTERVAL_MS = 5000;
61
+ const MAX_POLLS = 120; // 10 minutes
62
+ async function loadLicenseKey() {
63
+ if (!(await fs_extra_1.default.pathExists(LICENSE_PATH)))
64
+ return null;
65
+ try {
66
+ const data = await fs_extra_1.default.readJson(LICENSE_PATH);
67
+ return data.key || null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ async function saveLicenseTier(tier) {
74
+ let existing = {};
75
+ if (await fs_extra_1.default.pathExists(LICENSE_PATH)) {
76
+ try {
77
+ existing = await fs_extra_1.default.readJson(LICENSE_PATH);
78
+ }
79
+ catch {
80
+ // ignore
81
+ }
82
+ }
83
+ await fs_extra_1.default.ensureDir(path_1.default.dirname(LICENSE_PATH));
84
+ await fs_extra_1.default.writeJson(LICENSE_PATH, { ...existing, tier }, { spaces: 2 });
85
+ }
86
+ function sleep(ms) {
87
+ return new Promise((resolve) => setTimeout(resolve, ms));
88
+ }
89
+ async function upgradeCommand(options) {
90
+ // 1. Require auth
91
+ const authService = new AuthService_1.AuthService();
92
+ try {
93
+ await authService.getValidToken();
94
+ }
95
+ catch {
96
+ console.error(chalk_1.default.red("Error: Not authenticated. Run 'kaven auth login' first."));
97
+ process.exit(1);
98
+ return;
99
+ }
100
+ // 2. Load current license key
101
+ const licenseKey = await loadLicenseKey();
102
+ if (!licenseKey) {
103
+ console.error(chalk_1.default.red("Error: No license found. Add your license key first with 'kaven license status'."));
104
+ process.exit(1);
105
+ return;
106
+ }
107
+ // 3. Get current tier
108
+ const client = new MarketplaceClient_1.MarketplaceClient(authService);
109
+ const tierSpinner = (0, ora_1.default)("Loading your current license...").start();
110
+ let currentTier;
111
+ try {
112
+ const licenseStatus = await client.getLicenseStatus(licenseKey);
113
+ currentTier = licenseStatus.tier.toLowerCase();
114
+ tierSpinner.succeed(`Current tier: ${chalk_1.default.bold(TIER_LABELS[currentTier] || currentTier)}`);
115
+ }
116
+ catch {
117
+ tierSpinner.fail("Could not load license status");
118
+ console.error(chalk_1.default.gray("Try: kaven license status"));
119
+ process.exit(1);
120
+ return;
121
+ }
122
+ // 4. Show tier comparison table (imported from license command)
123
+ const { printTierComparisonTable } = await Promise.resolve().then(() => __importStar(require("../license/tier-table")));
124
+ printTierComparisonTable(currentTier, "pro");
125
+ console.log();
126
+ // 5. Prompt target tier (exclude current tier)
127
+ const { select } = await Promise.resolve().then(() => __importStar(require("@inquirer/prompts")));
128
+ const availableTiers = TIERS.filter((t) => t !== currentTier && t !== "enterprise");
129
+ if (availableTiers.length === 0) {
130
+ console.log(chalk_1.default.yellow(`You're already on the highest available tier (${TIER_LABELS[currentTier] || currentTier}).`));
131
+ console.log(chalk_1.default.gray("For Enterprise plans, contact: enterprise@kaven.sh"));
132
+ return;
133
+ }
134
+ const targetTier = await select({
135
+ message: "Select target tier:",
136
+ choices: availableTiers.map((t) => ({
137
+ name: TIER_LABELS[t],
138
+ value: t,
139
+ })),
140
+ });
141
+ // 6. Guard: same tier
142
+ if (targetTier === currentTier) {
143
+ console.log(chalk_1.default.yellow(`Already on ${TIER_LABELS[currentTier] || currentTier}.`));
144
+ return;
145
+ }
146
+ // 7. Create checkout session
147
+ const checkoutSpinner = (0, ora_1.default)("Creating checkout session...").start();
148
+ let sessionUrl;
149
+ let sessionId;
150
+ try {
151
+ const session = await client.createCheckoutSession(targetTier, licenseKey);
152
+ sessionUrl = session.sessionUrl;
153
+ sessionId = session.sessionId;
154
+ checkoutSpinner.succeed("Checkout session created");
155
+ }
156
+ catch (error) {
157
+ checkoutSpinner.fail("Failed to create checkout session");
158
+ console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
159
+ process.exit(1);
160
+ return;
161
+ }
162
+ // 8. Open browser
163
+ if (options.browser !== false) {
164
+ console.log(chalk_1.default.cyan(`Opening checkout in your browser...`));
165
+ console.log(chalk_1.default.gray(`URL: ${sessionUrl}`));
166
+ try {
167
+ await (0, open_1.default)(sessionUrl);
168
+ }
169
+ catch {
170
+ console.log(chalk_1.default.yellow("Could not open browser automatically. Open this URL manually:"));
171
+ console.log(chalk_1.default.cyan(sessionUrl));
172
+ }
173
+ }
174
+ else {
175
+ console.log(chalk_1.default.cyan("Open this URL to complete checkout:"));
176
+ console.log(chalk_1.default.bold(sessionUrl));
177
+ }
178
+ console.log();
179
+ // 9. Poll for checkout status
180
+ const pollSpinner = (0, ora_1.default)(`Waiting for payment confirmation (checking every 5s, max 10 min)...`).start();
181
+ for (let i = 0; i < MAX_POLLS; i++) {
182
+ await sleep(POLL_INTERVAL_MS);
183
+ const remaining = MAX_POLLS - i - 1;
184
+ pollSpinner.text = `Waiting for payment confirmation... (${remaining * 5}s remaining)`;
185
+ try {
186
+ const status = await client.getCheckoutStatus(sessionId);
187
+ if (status.status === "confirmed") {
188
+ pollSpinner.succeed("Payment confirmed!");
189
+ const newTier = status.tier || targetTier;
190
+ await saveLicenseTier(newTier);
191
+ console.log();
192
+ console.log(chalk_1.default.green(`✅ Successfully upgraded to ${TIER_LABELS[newTier] || newTier}!`));
193
+ console.log(chalk_1.default.gray("Your new features are now unlocked."));
194
+ return;
195
+ }
196
+ if (status.status === "cancelled") {
197
+ pollSpinner.fail("Checkout was cancelled.");
198
+ console.log(chalk_1.default.gray("No changes were made to your subscription."));
199
+ return;
200
+ }
201
+ if (status.status === "failed") {
202
+ pollSpinner.fail("Payment failed.");
203
+ console.log(chalk_1.default.gray("Please try again or contact support@kaven.sh"));
204
+ process.exit(1);
205
+ return;
206
+ }
207
+ // status === "pending" — continue polling
208
+ }
209
+ catch {
210
+ // Network hiccup — keep polling
211
+ }
212
+ }
213
+ // Timeout
214
+ pollSpinner.warn("Timed out waiting for payment confirmation.");
215
+ console.log();
216
+ console.log(chalk_1.default.yellow("If you completed payment, your upgrade may take a few minutes to activate."));
217
+ console.log(chalk_1.default.gray("Check your upgrade status at: https://dashboard.kaven.sh/billing"));
218
+ }