@codebakers/cli 2.9.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Open billing page for subscription management
3
+ */
4
+ export declare function billing(): Promise<void>;
@@ -0,0 +1,91 @@
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.billing = billing;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const child_process_1 = require("child_process");
9
+ const config_js_1 = require("../config.js");
10
+ /**
11
+ * Open a URL in the default browser
12
+ */
13
+ function openBrowser(url) {
14
+ const platform = process.platform;
15
+ try {
16
+ if (platform === 'win32') {
17
+ (0, child_process_1.execSync)(`start "" "${url}"`, { stdio: 'ignore', shell: 'cmd.exe' });
18
+ }
19
+ else if (platform === 'darwin') {
20
+ (0, child_process_1.execSync)(`open "${url}"`, { stdio: 'ignore' });
21
+ }
22
+ else {
23
+ (0, child_process_1.execSync)(`xdg-open "${url}" || sensible-browser "${url}" || x-www-browser "${url}"`, {
24
+ stdio: 'ignore',
25
+ shell: '/bin/sh',
26
+ });
27
+ }
28
+ }
29
+ catch {
30
+ console.log(chalk_1.default.yellow(`\n Could not open browser automatically.`));
31
+ console.log(chalk_1.default.gray(` Please open this URL manually:\n`));
32
+ console.log(chalk_1.default.cyan(` ${url}\n`));
33
+ }
34
+ }
35
+ /**
36
+ * Open billing page for subscription management
37
+ */
38
+ async function billing() {
39
+ console.log(chalk_1.default.blue(`
40
+ ╔═══════════════════════════════════════════════════════════╗
41
+ ║ ║
42
+ ║ ${chalk_1.default.bold.white('CodeBakers Billing & Subscription')} ║
43
+ ║ ║
44
+ ╚═══════════════════════════════════════════════════════════╝
45
+ `));
46
+ // Check current status
47
+ const apiKey = (0, config_js_1.getApiKey)();
48
+ const trial = (0, config_js_1.getTrialState)();
49
+ if (apiKey) {
50
+ console.log(chalk_1.default.green(' ✓ You have an active subscription\n'));
51
+ console.log(chalk_1.default.gray(' Opening settings page to manage your subscription...\n'));
52
+ const apiUrl = (0, config_js_1.getApiUrl)();
53
+ const settingsUrl = `${apiUrl}/settings`;
54
+ openBrowser(settingsUrl);
55
+ console.log(chalk_1.default.gray(` ${settingsUrl}\n`));
56
+ return;
57
+ }
58
+ if (trial) {
59
+ if ((0, config_js_1.isTrialExpired)()) {
60
+ console.log(chalk_1.default.yellow(' ⚠️ Your trial has expired\n'));
61
+ }
62
+ else {
63
+ const daysRemaining = (0, config_js_1.getTrialDaysRemaining)();
64
+ console.log(chalk_1.default.gray(` Trial: ${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining\n`));
65
+ }
66
+ }
67
+ // Show pricing
68
+ console.log(chalk_1.default.white(' Choose your plan:\n'));
69
+ console.log(chalk_1.default.cyan(' Pro ') + chalk_1.default.white('- $49/month ') + chalk_1.default.gray('(1 seat)'));
70
+ console.log(chalk_1.default.gray(' All 40 pattern modules'));
71
+ console.log(chalk_1.default.gray(' Unlimited projects'));
72
+ console.log(chalk_1.default.gray(' Priority support\n'));
73
+ console.log(chalk_1.default.cyan(' Team ') + chalk_1.default.white('- $149/month ') + chalk_1.default.gray('(5 seats)'));
74
+ console.log(chalk_1.default.gray(' Everything in Pro'));
75
+ console.log(chalk_1.default.gray(' Team collaboration'));
76
+ console.log(chalk_1.default.gray(' Shared API keys\n'));
77
+ console.log(chalk_1.default.cyan(' Agency ') + chalk_1.default.white('- $349/month ') + chalk_1.default.gray('(unlimited seats)'));
78
+ console.log(chalk_1.default.gray(' Everything in Team'));
79
+ console.log(chalk_1.default.gray(' White-label option'));
80
+ console.log(chalk_1.default.gray(' Dedicated support\n'));
81
+ console.log(chalk_1.default.gray(' Enterprise pricing available for large teams.\n'));
82
+ // Open billing page
83
+ const apiUrl = (0, config_js_1.getApiUrl)();
84
+ const billingUrl = `${apiUrl}/billing`;
85
+ console.log(chalk_1.default.white(' Opening billing page...\n'));
86
+ openBrowser(billingUrl);
87
+ console.log(chalk_1.default.gray(` ${billingUrl}\n`));
88
+ console.log(chalk_1.default.gray(' After subscribing, run:'));
89
+ console.log(chalk_1.default.cyan(' codebakers setup\n'));
90
+ console.log(chalk_1.default.gray(' to configure your API key.\n'));
91
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Extend trial by connecting GitHub account
3
+ */
4
+ export declare function extend(): Promise<void>;
@@ -0,0 +1,141 @@
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.extend = extend;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const child_process_1 = require("child_process");
10
+ const config_js_1 = require("../config.js");
11
+ /**
12
+ * Open a URL in the default browser
13
+ */
14
+ function openBrowser(url) {
15
+ const platform = process.platform;
16
+ try {
17
+ if (platform === 'win32') {
18
+ (0, child_process_1.execSync)(`start "" "${url}"`, { stdio: 'ignore', shell: 'cmd.exe' });
19
+ }
20
+ else if (platform === 'darwin') {
21
+ (0, child_process_1.execSync)(`open "${url}"`, { stdio: 'ignore' });
22
+ }
23
+ else {
24
+ // Linux - try common browsers
25
+ (0, child_process_1.execSync)(`xdg-open "${url}" || sensible-browser "${url}" || x-www-browser "${url}"`, {
26
+ stdio: 'ignore',
27
+ shell: '/bin/sh',
28
+ });
29
+ }
30
+ }
31
+ catch {
32
+ console.log(chalk_1.default.yellow(`\n Could not open browser automatically.`));
33
+ console.log(chalk_1.default.gray(` Please open this URL manually:\n`));
34
+ console.log(chalk_1.default.cyan(` ${url}\n`));
35
+ }
36
+ }
37
+ /**
38
+ * Sleep for a specified number of milliseconds
39
+ */
40
+ function sleep(ms) {
41
+ return new Promise((resolve) => setTimeout(resolve, ms));
42
+ }
43
+ /**
44
+ * Extend trial by connecting GitHub account
45
+ */
46
+ async function extend() {
47
+ console.log(chalk_1.default.blue(`
48
+ ╔═══════════════════════════════════════════════════════════╗
49
+ ║ ║
50
+ ║ ${chalk_1.default.bold.white('Extend Your Trial with GitHub')} ║
51
+ ║ ║
52
+ ╚═══════════════════════════════════════════════════════════╝
53
+ `));
54
+ // Check if user already has an API key (paid user)
55
+ const apiKey = (0, config_js_1.getApiKey)();
56
+ if (apiKey) {
57
+ console.log(chalk_1.default.green(' ✓ You\'re already logged in with an API key!\n'));
58
+ console.log(chalk_1.default.gray(' You have unlimited access. No extension needed.\n'));
59
+ return;
60
+ }
61
+ // Check for existing trial
62
+ const trial = (0, config_js_1.getTrialState)();
63
+ if (!trial) {
64
+ console.log(chalk_1.default.yellow(' No trial found.\n'));
65
+ console.log(chalk_1.default.white(' Start your free trial first:\n'));
66
+ console.log(chalk_1.default.cyan(' codebakers go\n'));
67
+ return;
68
+ }
69
+ // Check if already extended
70
+ if (trial.stage === 'extended') {
71
+ console.log(chalk_1.default.yellow(' Your trial has already been extended.\n'));
72
+ if ((0, config_js_1.isTrialExpired)()) {
73
+ console.log(chalk_1.default.white(' Ready to upgrade? $49/month for unlimited access:\n'));
74
+ console.log(chalk_1.default.cyan(' codebakers upgrade\n'));
75
+ }
76
+ else {
77
+ const expiresAt = new Date(trial.expiresAt);
78
+ const daysRemaining = Math.max(0, Math.ceil((expiresAt.getTime() - Date.now()) / (1000 * 60 * 60 * 24)));
79
+ console.log(chalk_1.default.gray(` ${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining.\n`));
80
+ }
81
+ return;
82
+ }
83
+ // Check if converted
84
+ if (trial.stage === 'converted') {
85
+ console.log(chalk_1.default.green(' ✓ You\'ve upgraded to a paid plan!\n'));
86
+ console.log(chalk_1.default.gray(' Run ') + chalk_1.default.cyan('codebakers setup') + chalk_1.default.gray(' to configure your API key.\n'));
87
+ return;
88
+ }
89
+ // Open browser for GitHub OAuth
90
+ const apiUrl = (0, config_js_1.getApiUrl)();
91
+ const authUrl = `${apiUrl}/api/auth/github?trial_id=${trial.trialId}`;
92
+ console.log(chalk_1.default.white(' Opening browser for GitHub authorization...\n'));
93
+ openBrowser(authUrl);
94
+ console.log(chalk_1.default.gray(' Waiting for authorization...'));
95
+ console.log(chalk_1.default.gray(' (This may take a moment)\n'));
96
+ // Poll for completion
97
+ const spinner = (0, ora_1.default)('Checking authorization status...').start();
98
+ let extended = false;
99
+ let pollCount = 0;
100
+ const maxPolls = 60; // 2 minutes max
101
+ while (pollCount < maxPolls && !extended) {
102
+ await sleep(2000);
103
+ pollCount++;
104
+ try {
105
+ const response = await fetch(`${apiUrl}/api/trial/status?trialId=${trial.trialId}`);
106
+ const data = await response.json();
107
+ if (data.stage === 'extended') {
108
+ extended = true;
109
+ // Update local trial state
110
+ const updatedTrial = {
111
+ ...trial,
112
+ stage: 'extended',
113
+ expiresAt: data.expiresAt,
114
+ extendedAt: new Date().toISOString(),
115
+ ...(data.githubUsername && { githubUsername: data.githubUsername }),
116
+ };
117
+ (0, config_js_1.setTrialState)(updatedTrial);
118
+ spinner.succeed('Trial extended!');
119
+ }
120
+ }
121
+ catch {
122
+ // Ignore polling errors
123
+ }
124
+ }
125
+ if (extended) {
126
+ console.log(chalk_1.default.green(`
127
+ ╔═══════════════════════════════════════════════════════════╗
128
+ ║ ✅ Trial Extended! ║
129
+ ║ ║
130
+ ║ ${chalk_1.default.white('You have 7 more days to build with CodeBakers.')} ║
131
+ ║ ║
132
+ ║ ${chalk_1.default.gray('Keep building - your project is waiting!')} ║
133
+ ╚═══════════════════════════════════════════════════════════╝
134
+ `));
135
+ }
136
+ else {
137
+ spinner.warn('Authorization timed out');
138
+ console.log(chalk_1.default.yellow('\n Please try again or authorize manually:\n'));
139
+ console.log(chalk_1.default.cyan(` ${authUrl}\n`));
140
+ }
141
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Zero-friction entry point - start using CodeBakers instantly
3
+ */
4
+ export declare function go(): Promise<void>;
@@ -0,0 +1,328 @@
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.go = go;
7
+ const chalk_1 = __importDefault(require("chalk"));
8
+ const ora_1 = __importDefault(require("ora"));
9
+ const child_process_1 = require("child_process");
10
+ const fs_1 = require("fs");
11
+ const path_1 = require("path");
12
+ const readline_1 = require("readline");
13
+ const config_js_1 = require("../config.js");
14
+ const fingerprint_js_1 = require("../lib/fingerprint.js");
15
+ function prompt(question) {
16
+ const rl = (0, readline_1.createInterface)({
17
+ input: process.stdin,
18
+ output: process.stdout,
19
+ });
20
+ return new Promise((resolve) => {
21
+ rl.question(question, (answer) => {
22
+ rl.close();
23
+ resolve(answer.trim().toLowerCase());
24
+ });
25
+ });
26
+ }
27
+ /**
28
+ * Zero-friction entry point - start using CodeBakers instantly
29
+ */
30
+ async function go() {
31
+ console.log(chalk_1.default.blue(`
32
+ ╔═══════════════════════════════════════════════════════════╗
33
+ ║ ║
34
+ ║ ${chalk_1.default.bold.white('CodeBakers - Zero Setup Required')} ║
35
+ ║ ║
36
+ ╚═══════════════════════════════════════════════════════════╝
37
+ `));
38
+ // Check if user already has an API key (paid user)
39
+ const apiKey = (0, config_js_1.getApiKey)();
40
+ if (apiKey) {
41
+ console.log(chalk_1.default.green(' ✓ You\'re already logged in with an API key!\n'));
42
+ // Still install patterns if not already installed
43
+ await installPatternsWithApiKey(apiKey);
44
+ await configureMCP();
45
+ return;
46
+ }
47
+ // Check existing trial
48
+ const existingTrial = (0, config_js_1.getTrialState)();
49
+ if (existingTrial && !(0, config_js_1.isTrialExpired)()) {
50
+ const daysRemaining = (0, config_js_1.getTrialDaysRemaining)();
51
+ console.log(chalk_1.default.green(` ✓ Trial active (${daysRemaining} day${daysRemaining !== 1 ? 's' : ''} remaining)\n`));
52
+ if (existingTrial.stage === 'anonymous' && daysRemaining <= 2) {
53
+ console.log(chalk_1.default.yellow(' ⚠️ Trial expiring soon! Extend with GitHub:\n'));
54
+ console.log(chalk_1.default.cyan(' codebakers extend\n'));
55
+ }
56
+ // Install patterns if not already installed
57
+ await installPatterns(existingTrial.trialId);
58
+ await configureMCP();
59
+ return;
60
+ }
61
+ // Check if trial expired
62
+ if (existingTrial && (0, config_js_1.isTrialExpired)()) {
63
+ console.log(chalk_1.default.yellow(' ⚠️ Your trial has expired.\n'));
64
+ if (existingTrial.stage === 'anonymous') {
65
+ console.log(chalk_1.default.white(' Extend your trial for 7 more days with GitHub:\n'));
66
+ console.log(chalk_1.default.cyan(' codebakers extend\n'));
67
+ console.log(chalk_1.default.gray(' Or upgrade to Pro ($49/month):\n'));
68
+ console.log(chalk_1.default.cyan(' codebakers upgrade\n'));
69
+ }
70
+ else {
71
+ console.log(chalk_1.default.white(' Ready to upgrade? $49/month for unlimited access:\n'));
72
+ console.log(chalk_1.default.cyan(' codebakers upgrade\n'));
73
+ }
74
+ return;
75
+ }
76
+ // Start new trial
77
+ const spinner = (0, ora_1.default)('Starting your free trial...').start();
78
+ try {
79
+ const fingerprint = (0, fingerprint_js_1.getDeviceFingerprint)();
80
+ const apiUrl = (0, config_js_1.getApiUrl)();
81
+ const response = await fetch(`${apiUrl}/api/trial/start`, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({
85
+ deviceHash: fingerprint.deviceHash,
86
+ machineId: fingerprint.machineId,
87
+ platform: fingerprint.platform,
88
+ hostname: fingerprint.hostname,
89
+ }),
90
+ });
91
+ const data = await response.json();
92
+ if (data.error === 'trial_not_available') {
93
+ spinner.fail('Trial not available');
94
+ console.log(chalk_1.default.yellow(`
95
+ It looks like you've already used a CodeBakers trial.
96
+
97
+ Ready to upgrade? $49/month for unlimited access.
98
+
99
+ ${chalk_1.default.cyan('codebakers upgrade')} or visit ${chalk_1.default.underline('https://codebakers.ai/pricing')}
100
+ `));
101
+ return;
102
+ }
103
+ if (!response.ok) {
104
+ throw new Error(data.error || 'Failed to start trial');
105
+ }
106
+ // Check if returning existing trial
107
+ if (data.stage === 'expired') {
108
+ spinner.warn('Your previous trial has expired');
109
+ console.log('');
110
+ if (data.canExtend) {
111
+ console.log(chalk_1.default.white(' Extend your trial for 7 more days with GitHub:\n'));
112
+ console.log(chalk_1.default.cyan(' codebakers extend\n'));
113
+ }
114
+ else {
115
+ console.log(chalk_1.default.white(' Ready to upgrade? $49/month for unlimited access:\n'));
116
+ console.log(chalk_1.default.cyan(' codebakers upgrade\n'));
117
+ }
118
+ return;
119
+ }
120
+ // Save trial state
121
+ const trialState = {
122
+ trialId: data.trialId,
123
+ stage: data.stage,
124
+ deviceHash: fingerprint.deviceHash,
125
+ expiresAt: data.expiresAt,
126
+ startedAt: data.startedAt,
127
+ ...(data.githubUsername && { githubUsername: data.githubUsername }),
128
+ ...(data.projectId && { projectId: data.projectId }),
129
+ ...(data.projectName && { projectName: data.projectName }),
130
+ };
131
+ (0, config_js_1.setTrialState)(trialState);
132
+ spinner.succeed(`Trial started (${data.daysRemaining} days free)`);
133
+ console.log('');
134
+ // Install patterns (CLAUDE.md and .claude/)
135
+ await installPatterns(data.trialId);
136
+ // Configure MCP
137
+ await configureMCP();
138
+ // Show success message
139
+ console.log(chalk_1.default.green(`
140
+ ╔═══════════════════════════════════════════════════════════╗
141
+ ║ ✅ CodeBakers is ready! ║
142
+ ║ ║
143
+ ║ ${chalk_1.default.white('Your 7-day free trial has started.')} ║
144
+ ║ ║
145
+ ║ ${chalk_1.default.gray('Try: "Build me a todo app with authentication"')} ║
146
+ ╚═══════════════════════════════════════════════════════════╝
147
+ `));
148
+ // Attempt auto-restart Claude Code
149
+ await attemptAutoRestart();
150
+ }
151
+ catch (error) {
152
+ spinner.fail('Failed to start trial');
153
+ if (error instanceof Error) {
154
+ if (error.message.includes('fetch') || error.message.includes('network')) {
155
+ console.log(chalk_1.default.red('\n Could not connect to CodeBakers server.'));
156
+ console.log(chalk_1.default.gray(' Check your internet connection and try again.\n'));
157
+ }
158
+ else {
159
+ console.log(chalk_1.default.red(`\n ${error.message}\n`));
160
+ }
161
+ }
162
+ else {
163
+ console.log(chalk_1.default.red('\n An unexpected error occurred.\n'));
164
+ }
165
+ }
166
+ }
167
+ async function configureMCP() {
168
+ const spinner = (0, ora_1.default)('Configuring Claude Code integration...').start();
169
+ const isWindows = process.platform === 'win32';
170
+ const mcpCmd = isWindows
171
+ ? 'claude mcp add --transport stdio codebakers -- cmd /c npx -y @codebakers/cli serve'
172
+ : 'claude mcp add --transport stdio codebakers -- npx -y @codebakers/cli serve';
173
+ try {
174
+ (0, child_process_1.execSync)(mcpCmd, { stdio: 'pipe' });
175
+ spinner.succeed('CodeBakers connected to Claude Code');
176
+ }
177
+ catch (error) {
178
+ const errorMessage = error instanceof Error ? error.message : String(error);
179
+ if (errorMessage.includes('already exists') || errorMessage.includes('already registered')) {
180
+ spinner.succeed('CodeBakers already connected to Claude Code');
181
+ }
182
+ else {
183
+ spinner.warn('Could not auto-configure Claude Code');
184
+ console.log(chalk_1.default.gray('\n Run this command manually:\n'));
185
+ console.log(chalk_1.default.cyan(` ${mcpCmd}\n`));
186
+ }
187
+ }
188
+ }
189
+ async function attemptAutoRestart() {
190
+ const cwd = process.cwd();
191
+ console.log(chalk_1.default.yellow('\n ⚠️ RESTART REQUIRED\n'));
192
+ console.log(chalk_1.default.gray(' Claude Code needs to restart to load CodeBakers.\n'));
193
+ const answer = await prompt(chalk_1.default.cyan(' Restart Claude Code now? (Y/n): '));
194
+ if (answer === 'n' || answer === 'no') {
195
+ console.log(chalk_1.default.gray('\n No problem! Just restart Claude Code manually when ready.\n'));
196
+ return;
197
+ }
198
+ // Attempt to restart Claude Code
199
+ console.log(chalk_1.default.gray('\n Restarting Claude Code...\n'));
200
+ try {
201
+ const isWindows = process.platform === 'win32';
202
+ if (isWindows) {
203
+ // On Windows, spawn a new Claude process detached and exit
204
+ (0, child_process_1.spawn)('cmd', ['/c', 'start', 'claude'], {
205
+ cwd,
206
+ detached: true,
207
+ stdio: 'ignore',
208
+ shell: true,
209
+ }).unref();
210
+ }
211
+ else {
212
+ // On Mac/Linux, spawn claude in new terminal
213
+ (0, child_process_1.spawn)('claude', [], {
214
+ cwd,
215
+ detached: true,
216
+ stdio: 'ignore',
217
+ shell: true,
218
+ }).unref();
219
+ }
220
+ console.log(chalk_1.default.green(' ✓ Claude Code is restarting...\n'));
221
+ console.log(chalk_1.default.gray(' This terminal will close. Claude Code will open in a new window.\n'));
222
+ // Give the spawn a moment to start
223
+ await new Promise(resolve => setTimeout(resolve, 1000));
224
+ // Exit this process
225
+ process.exit(0);
226
+ }
227
+ catch (error) {
228
+ console.log(chalk_1.default.yellow(' Could not auto-restart. Please restart Claude Code manually.\n'));
229
+ }
230
+ }
231
+ /**
232
+ * Install pattern files for API key users (paid users)
233
+ */
234
+ async function installPatternsWithApiKey(apiKey) {
235
+ const spinner = (0, ora_1.default)('Installing CodeBakers patterns...').start();
236
+ const cwd = process.cwd();
237
+ const apiUrl = (0, config_js_1.getApiUrl)();
238
+ try {
239
+ const response = await fetch(`${apiUrl}/api/content`, {
240
+ method: 'GET',
241
+ headers: {
242
+ 'Authorization': `Bearer ${apiKey}`,
243
+ },
244
+ });
245
+ if (!response.ok) {
246
+ spinner.warn('Could not download patterns');
247
+ return;
248
+ }
249
+ const content = await response.json();
250
+ await writePatternFiles(cwd, content, spinner);
251
+ }
252
+ catch (error) {
253
+ spinner.warn('Could not install patterns');
254
+ console.log(chalk_1.default.gray(' Check your internet connection.\n'));
255
+ }
256
+ }
257
+ /**
258
+ * Install pattern files (CLAUDE.md and .claude/) for trial users
259
+ */
260
+ async function installPatterns(trialId) {
261
+ const spinner = (0, ora_1.default)('Installing CodeBakers patterns...').start();
262
+ const cwd = process.cwd();
263
+ const apiUrl = (0, config_js_1.getApiUrl)();
264
+ try {
265
+ // Fetch patterns using trial ID
266
+ const response = await fetch(`${apiUrl}/api/content`, {
267
+ method: 'GET',
268
+ headers: {
269
+ 'X-Trial-ID': trialId,
270
+ },
271
+ });
272
+ if (!response.ok) {
273
+ // Try without auth - some patterns may be available for trial
274
+ const publicResponse = await fetch(`${apiUrl}/api/content/trial`, {
275
+ method: 'GET',
276
+ headers: {
277
+ 'X-Trial-ID': trialId,
278
+ },
279
+ });
280
+ if (!publicResponse.ok) {
281
+ spinner.warn('Could not download patterns (will use MCP tools)');
282
+ return;
283
+ }
284
+ const content = await publicResponse.json();
285
+ await writePatternFiles(cwd, content, spinner);
286
+ return;
287
+ }
288
+ const content = await response.json();
289
+ await writePatternFiles(cwd, content, spinner);
290
+ }
291
+ catch (error) {
292
+ spinner.warn('Could not install patterns (will use MCP tools)');
293
+ console.log(chalk_1.default.gray(' Patterns will be available via MCP tools.\n'));
294
+ }
295
+ }
296
+ async function writePatternFiles(cwd, content, spinner) {
297
+ // Check if patterns already exist
298
+ const claudeMdPath = (0, path_1.join)(cwd, 'CLAUDE.md');
299
+ if ((0, fs_1.existsSync)(claudeMdPath)) {
300
+ spinner.succeed('CodeBakers patterns already installed');
301
+ return;
302
+ }
303
+ // Write CLAUDE.md (router file)
304
+ if (content.router) {
305
+ (0, fs_1.writeFileSync)(claudeMdPath, content.router);
306
+ }
307
+ // Write pattern modules to .claude/
308
+ if (content.modules && Object.keys(content.modules).length > 0) {
309
+ const modulesDir = (0, path_1.join)(cwd, '.claude');
310
+ if (!(0, fs_1.existsSync)(modulesDir)) {
311
+ (0, fs_1.mkdirSync)(modulesDir, { recursive: true });
312
+ }
313
+ for (const [name, data] of Object.entries(content.modules)) {
314
+ (0, fs_1.writeFileSync)((0, path_1.join)(modulesDir, name), data);
315
+ }
316
+ }
317
+ // Update .gitignore to exclude encoded patterns
318
+ const gitignorePath = (0, path_1.join)(cwd, '.gitignore');
319
+ if ((0, fs_1.existsSync)(gitignorePath)) {
320
+ const { readFileSync } = await import('fs');
321
+ const gitignore = readFileSync(gitignorePath, 'utf-8');
322
+ if (!gitignore.includes('.claude/')) {
323
+ (0, fs_1.writeFileSync)(gitignorePath, gitignore + '\n# CodeBakers patterns\n.claude/\n');
324
+ }
325
+ }
326
+ spinner.succeed(`CodeBakers patterns installed (v${content.version})`);
327
+ console.log(chalk_1.default.gray(` ${Object.keys(content.modules || {}).length} pattern modules ready\n`));
328
+ }
package/dist/config.d.ts CHANGED
@@ -24,12 +24,25 @@ export declare const PROVISIONABLE_KEYS: ServiceName[];
24
24
  type ServiceKeys = {
25
25
  [K in ServiceName]: string | null;
26
26
  };
27
+ export type TrialStage = 'anonymous' | 'extended' | 'expired' | 'converted';
28
+ export interface TrialState {
29
+ trialId: string;
30
+ stage: TrialStage;
31
+ deviceHash: string;
32
+ expiresAt: string;
33
+ startedAt: string;
34
+ extendedAt?: string;
35
+ githubUsername?: string;
36
+ projectId?: string;
37
+ projectName?: string;
38
+ }
27
39
  interface ConfigSchema {
28
40
  apiKey: string | null;
29
41
  apiUrl: string;
30
42
  experienceLevel: ExperienceLevel;
31
43
  serviceKeys: ServiceKeys;
32
44
  lastKeySync: string | null;
45
+ trial: TrialState | null;
33
46
  }
34
47
  export declare function getApiKey(): string | null;
35
48
  export declare function setApiKey(key: string): void;
@@ -72,4 +85,24 @@ export declare function writeKeysToEnvFile(projectPath: string, options?: {
72
85
  export declare function validateKeyFormat(name: ServiceName, value: string): boolean;
73
86
  export declare function getConfigPath(): string;
74
87
  export declare function getConfigStore(): ConfigSchema;
88
+ export declare function getTrialState(): TrialState | null;
89
+ export declare function setTrialState(trial: TrialState): void;
90
+ export declare function clearTrialState(): void;
91
+ export declare function updateTrialState(updates: Partial<TrialState>): void;
92
+ /**
93
+ * Check if the current trial has expired
94
+ */
95
+ export declare function isTrialExpired(): boolean;
96
+ /**
97
+ * Get the number of days remaining in the trial
98
+ */
99
+ export declare function getTrialDaysRemaining(): number;
100
+ /**
101
+ * Check if user has any valid access (API key OR active trial)
102
+ */
103
+ export declare function hasValidAccess(): boolean;
104
+ /**
105
+ * Get authentication mode: 'apiKey', 'trial', or 'none'
106
+ */
107
+ export declare function getAuthMode(): 'apiKey' | 'trial' | 'none';
75
108
  export {};