berget 1.0.0 → 1.1.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 (37) hide show
  1. package/README.md +92 -0
  2. package/dist/index.js +7 -471
  3. package/dist/src/client.js +193 -102
  4. package/dist/src/commands/api-keys.js +271 -0
  5. package/dist/src/commands/auth.js +65 -0
  6. package/dist/src/commands/autocomplete.js +24 -0
  7. package/dist/src/commands/billing.js +53 -0
  8. package/dist/src/commands/chat.js +276 -0
  9. package/dist/src/commands/clusters.js +69 -0
  10. package/dist/src/commands/index.js +25 -0
  11. package/dist/src/commands/models.js +69 -0
  12. package/dist/src/commands/users.js +43 -0
  13. package/dist/src/constants/command-structure.js +14 -0
  14. package/dist/src/services/auth-service.js +49 -47
  15. package/dist/src/services/chat-service.js +177 -0
  16. package/dist/src/utils/config-checker.js +50 -0
  17. package/dist/src/utils/default-api-key.js +111 -0
  18. package/dist/src/utils/token-manager.js +165 -0
  19. package/index.ts +5 -566
  20. package/package.json +6 -1
  21. package/src/client.ts +262 -80
  22. package/src/commands/api-keys.ts +364 -0
  23. package/src/commands/auth.ts +58 -0
  24. package/src/commands/autocomplete.ts +19 -0
  25. package/src/commands/billing.ts +41 -0
  26. package/src/commands/chat.ts +345 -0
  27. package/src/commands/clusters.ts +65 -0
  28. package/src/commands/index.ts +23 -0
  29. package/src/commands/models.ts +63 -0
  30. package/src/commands/users.ts +37 -0
  31. package/src/constants/command-structure.ts +16 -0
  32. package/src/services/auth-service.ts +90 -50
  33. package/src/services/chat-service.ts +177 -0
  34. package/src/types/api.d.ts +58 -192
  35. package/src/utils/config-checker.ts +23 -0
  36. package/src/utils/default-api-key.ts +94 -0
  37. package/src/utils/token-manager.ts +150 -0
@@ -17,6 +17,7 @@ exports.COMMAND_GROUPS = {
17
17
  FLUX: 'flux',
18
18
  USERS: 'users',
19
19
  BILLING: 'billing',
20
+ CHAT: 'chat',
20
21
  };
21
22
  // Subcommands for each group
22
23
  exports.SUBCOMMANDS = {
@@ -26,6 +27,11 @@ exports.SUBCOMMANDS = {
26
27
  LOGOUT: 'logout',
27
28
  WHOAMI: 'whoami',
28
29
  },
30
+ // Chat commands
31
+ CHAT: {
32
+ RUN: 'run',
33
+ LIST: 'list',
34
+ },
29
35
  // API Keys commands
30
36
  API_KEYS: {
31
37
  LIST: 'list',
@@ -33,6 +39,8 @@ exports.SUBCOMMANDS = {
33
39
  DELETE: 'delete',
34
40
  ROTATE: 'rotate',
35
41
  DESCRIBE: 'describe',
42
+ SET_DEFAULT: 'set-default',
43
+ GET_DEFAULT: 'get-default',
36
44
  },
37
45
  // Clusters commands
38
46
  CLUSTERS: {
@@ -102,6 +110,8 @@ exports.COMMAND_DESCRIPTIONS = {
102
110
  [`${exports.COMMAND_GROUPS.API_KEYS} ${exports.SUBCOMMANDS.API_KEYS.DELETE}`]: 'Delete an API key',
103
111
  [`${exports.COMMAND_GROUPS.API_KEYS} ${exports.SUBCOMMANDS.API_KEYS.ROTATE}`]: 'Rotate an API key',
104
112
  [`${exports.COMMAND_GROUPS.API_KEYS} ${exports.SUBCOMMANDS.API_KEYS.DESCRIBE}`]: 'Get usage statistics for an API key',
113
+ [`${exports.COMMAND_GROUPS.API_KEYS} ${exports.SUBCOMMANDS.API_KEYS.SET_DEFAULT}`]: 'Set an API key as the default for chat commands',
114
+ [`${exports.COMMAND_GROUPS.API_KEYS} ${exports.SUBCOMMANDS.API_KEYS.GET_DEFAULT}`]: 'Show the current default API key',
105
115
  // Clusters group
106
116
  [exports.COMMAND_GROUPS.CLUSTERS]: 'Manage Kubernetes clusters',
107
117
  [`${exports.COMMAND_GROUPS.CLUSTERS} ${exports.SUBCOMMANDS.CLUSTERS.LIST}`]: 'List all clusters',
@@ -147,4 +157,8 @@ exports.COMMAND_DESCRIPTIONS = {
147
157
  [`${exports.COMMAND_GROUPS.BILLING} ${exports.SUBCOMMANDS.BILLING.ADD_PAYMENT_METHOD}`]: 'Add a new payment method',
148
158
  [`${exports.COMMAND_GROUPS.BILLING} ${exports.SUBCOMMANDS.BILLING.REMOVE_PAYMENT_METHOD}`]: 'Remove a payment method',
149
159
  [`${exports.COMMAND_GROUPS.BILLING} ${exports.SUBCOMMANDS.BILLING.UPDATE_SUBSCRIPTION}`]: 'Update subscription plan',
160
+ // Chat group
161
+ [exports.COMMAND_GROUPS.CHAT]: 'Interact with AI chat models',
162
+ [`${exports.COMMAND_GROUPS.CHAT} ${exports.SUBCOMMANDS.CHAT.RUN}`]: 'Run a chat session with a specified model',
163
+ [`${exports.COMMAND_GROUPS.CHAT} ${exports.SUBCOMMANDS.CHAT.LIST}`]: 'List available chat models',
150
164
  };
@@ -55,6 +55,21 @@ class AuthService {
55
55
  }
56
56
  return AuthService.instance;
57
57
  }
58
+ whoami() {
59
+ return __awaiter(this, void 0, void 0, function* () {
60
+ try {
61
+ const { data: profile, error } = yield this.client.GET('/v1/users/me');
62
+ if (error) {
63
+ throw new Error(error ? JSON.stringify(error) : 'Failed to get user profile');
64
+ }
65
+ return profile;
66
+ }
67
+ catch (error) {
68
+ (0, error_handler_1.handleError)('Failed to get user profile', error);
69
+ return null;
70
+ }
71
+ });
72
+ }
58
73
  login() {
59
74
  return __awaiter(this, void 0, void 0, function* () {
60
75
  try {
@@ -68,16 +83,20 @@ class AuthService {
68
83
  ? JSON.stringify(deviceError)
69
84
  : 'Failed to get device authorization data');
70
85
  }
86
+ // Type assertion for deviceData
87
+ const typedDeviceData = deviceData;
71
88
  // Display information to user
72
89
  console.log(chalk_1.default.cyan('\nTo complete login:'));
73
- console.log(chalk_1.default.cyan(`1. Open this URL: ${chalk_1.default.bold(deviceData.verification_url || 'https://auth.berget.ai/device')}`));
74
- console.log(chalk_1.default.cyan(`2. Enter this code: ${chalk_1.default.bold(deviceData.user_code || '')}\n`));
90
+ console.log(chalk_1.default.cyan(`1. Open this URL: ${chalk_1.default.bold(typedDeviceData.verification_url ||
91
+ 'https://keycloak.berget.ai/device')}`));
92
+ if (!typedDeviceData.verification_url)
93
+ console.log(chalk_1.default.cyan(`2. Enter this code: ${chalk_1.default.bold(typedDeviceData.user_code || '')}\n`));
75
94
  // Try to open browser automatically
76
95
  try {
77
- if (deviceData.verification_url) {
96
+ if (typedDeviceData.verification_url) {
78
97
  // Use dynamic import for the 'open' package
79
- const open = yield Promise.resolve().then(() => __importStar(require('open'))).then(m => m.default);
80
- yield open(deviceData.verification_url);
98
+ const open = yield Promise.resolve().then(() => __importStar(require('open'))).then((m) => m.default);
99
+ yield open(typedDeviceData.verification_url);
81
100
  console.log(chalk_1.default.dim("Browser opened automatically. If it didn't open, please use the URL above."));
82
101
  }
83
102
  }
@@ -87,9 +106,11 @@ class AuthService {
87
106
  console.log(chalk_1.default.dim('\nWaiting for authentication to complete...'));
88
107
  // Step 2: Poll for completion
89
108
  const startTime = Date.now();
90
- const expiresIn = deviceData.expires_in !== undefined ? deviceData.expires_in : 900;
109
+ const expiresIn = typedDeviceData.expires_in !== undefined
110
+ ? typedDeviceData.expires_in
111
+ : 900;
91
112
  const expiresAt = startTime + expiresIn * 1000;
92
- let pollInterval = (deviceData.interval || 5) * 1000;
113
+ let pollInterval = (typedDeviceData.interval || 5) * 1000;
93
114
  const spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
94
115
  let spinnerIdx = 0;
95
116
  while (Date.now() < expiresAt) {
@@ -99,7 +120,7 @@ class AuthService {
99
120
  process.stdout.write(`\r${chalk_1.default.blue(spinner[spinnerIdx])} Waiting for authentication...`);
100
121
  spinnerIdx = (spinnerIdx + 1) % spinner.length;
101
122
  // Check if authentication is complete
102
- const deviceCode = deviceData.device_code || '';
123
+ const deviceCode = typedDeviceData.device_code || '';
103
124
  const { data: tokenData, error: tokenError } = yield client_1.apiClient.POST('/v1/auth/device/token', {
104
125
  body: {
105
126
  device_code: deviceCode,
@@ -147,16 +168,27 @@ class AuthService {
147
168
  continue;
148
169
  }
149
170
  }
150
- else if (tokenData && tokenData.token) {
151
- // Success!
152
- (0, client_1.saveAuthToken)(tokenData.token);
153
- process.stdout.write('\r' + ' '.repeat(50) + '\r'); // Clear the spinner line
154
- console.log(chalk_1.default.green('✓ Successfully logged in to Berget'));
155
- if (tokenData.user) {
156
- const user = tokenData.user;
157
- console.log(chalk_1.default.green(`Logged in as ${user.name || user.email || 'User'}`));
171
+ else if (tokenData) {
172
+ // Type assertion for tokenData
173
+ const typedTokenData = tokenData;
174
+ if (typedTokenData.token) {
175
+ // Success!
176
+ (0, client_1.saveAuthToken)(typedTokenData.token, typedTokenData.refresh_token || '', typedTokenData.expires_in || 3600);
177
+ if (process.argv.includes('--debug')) {
178
+ console.log(chalk_1.default.yellow('DEBUG: Token data received:'));
179
+ console.log(chalk_1.default.yellow(JSON.stringify({
180
+ expires_in: typedTokenData.expires_in,
181
+ refresh_expires_in: typedTokenData.refresh_expires_in,
182
+ }, null, 2)));
183
+ }
184
+ process.stdout.write('\r' + ' '.repeat(50) + '\r'); // Clear the spinner line
185
+ console.log(chalk_1.default.green('✓ Successfully logged in to Berget'));
186
+ if (typedTokenData.user) {
187
+ const user = typedTokenData.user;
188
+ console.log(chalk_1.default.green(`Logged in as ${user.name || user.email || 'User'}`));
189
+ }
190
+ return true;
158
191
  }
159
- return true;
160
192
  }
161
193
  }
162
194
  console.log(chalk_1.default.red('\n\nAuthentication timed out. Please try again.'));
@@ -168,36 +200,6 @@ class AuthService {
168
200
  }
169
201
  });
170
202
  }
171
- isAuthenticated() {
172
- return __awaiter(this, void 0, void 0, function* () {
173
- try {
174
- // Call an API endpoint that requires authentication
175
- const { data, error } = yield this.client.GET('/v1/users/me');
176
- return !!data && !error;
177
- }
178
- catch (_a) {
179
- return false;
180
- }
181
- });
182
- }
183
- /**
184
- * Get current user profile
185
- * Command: berget auth whoami
186
- */
187
- whoami() {
188
- return __awaiter(this, void 0, void 0, function* () {
189
- try {
190
- const { data, error } = yield this.client.GET('/v1/users/me');
191
- if (error)
192
- throw new Error(JSON.stringify(error));
193
- return data;
194
- }
195
- catch (error) {
196
- (0, error_handler_1.handleError)('Failed to get user profile', error);
197
- throw error;
198
- }
199
- });
200
- }
201
203
  }
202
204
  exports.AuthService = AuthService;
203
205
  // Command group name for this service
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.ChatService = void 0;
27
+ const client_1 = require("../client");
28
+ const chalk_1 = __importDefault(require("chalk"));
29
+ /**
30
+ * Service for interacting with the chat API
31
+ * Command group: chat
32
+ */
33
+ class ChatService {
34
+ constructor() {
35
+ this.client = (0, client_1.createAuthenticatedClient)();
36
+ }
37
+ static getInstance() {
38
+ if (!ChatService.instance) {
39
+ ChatService.instance = new ChatService();
40
+ }
41
+ return ChatService.instance;
42
+ }
43
+ /**
44
+ * Create a chat completion
45
+ * Command: berget chat completion
46
+ */
47
+ createCompletion(options) {
48
+ return __awaiter(this, void 0, void 0, function* () {
49
+ try {
50
+ const headers = {};
51
+ // Check if debug is enabled
52
+ const isDebug = process.argv.includes('--debug');
53
+ if (isDebug) {
54
+ console.log(chalk_1.default.yellow('DEBUG: Chat completion options:'));
55
+ console.log(chalk_1.default.yellow(JSON.stringify(options, null, 2)));
56
+ }
57
+ // If an API key is provided, use it for this request
58
+ if (options.apiKey) {
59
+ headers['Authorization'] = `Bearer ${options.apiKey}`;
60
+ // Remove apiKey from options before sending to API
61
+ const { apiKey } = options, requestOptions = __rest(options, ["apiKey"]);
62
+ if (isDebug) {
63
+ console.log(chalk_1.default.yellow('DEBUG: Using provided API key'));
64
+ console.log(chalk_1.default.yellow('DEBUG: Request options:'));
65
+ console.log(chalk_1.default.yellow(JSON.stringify(requestOptions, null, 2)));
66
+ }
67
+ const { data, error } = yield this.client.POST('/v1/chat/completions', {
68
+ body: requestOptions,
69
+ headers
70
+ });
71
+ if (isDebug) {
72
+ console.log(chalk_1.default.yellow('DEBUG: API response:'));
73
+ console.log(chalk_1.default.yellow(JSON.stringify({ data, error }, null, 2)));
74
+ // Output the complete response data for debugging
75
+ console.log(chalk_1.default.yellow('DEBUG: Complete response data:'));
76
+ console.log(chalk_1.default.yellow(JSON.stringify(data, null, 2)));
77
+ }
78
+ if (error)
79
+ throw new Error(JSON.stringify(error));
80
+ return data;
81
+ }
82
+ else {
83
+ // Use the default authenticated client
84
+ if (isDebug) {
85
+ console.log(chalk_1.default.yellow('DEBUG: Using default authentication'));
86
+ }
87
+ const { data, error } = yield this.client.POST('/v1/chat/completions', {
88
+ body: options
89
+ });
90
+ if (isDebug) {
91
+ console.log(chalk_1.default.yellow('DEBUG: API response:'));
92
+ console.log(chalk_1.default.yellow(JSON.stringify({ data, error }, null, 2)));
93
+ // Output the complete response data for debugging
94
+ console.log(chalk_1.default.yellow('DEBUG: Complete response data:'));
95
+ console.log(chalk_1.default.yellow(JSON.stringify(data, null, 2)));
96
+ }
97
+ if (error)
98
+ throw new Error(JSON.stringify(error));
99
+ return data;
100
+ }
101
+ }
102
+ catch (error) {
103
+ // Improved error handling
104
+ let errorMessage = 'Failed to create chat completion';
105
+ if (error instanceof Error) {
106
+ try {
107
+ // Try to parse the error message as JSON
108
+ const parsedError = JSON.parse(error.message);
109
+ if (parsedError.error && parsedError.error.message) {
110
+ errorMessage = `Chat error: ${parsedError.error.message}`;
111
+ }
112
+ }
113
+ catch (e) {
114
+ // If parsing fails, use the original error message
115
+ errorMessage = `Chat error: ${error.message}`;
116
+ }
117
+ }
118
+ console.error(chalk_1.default.red(errorMessage));
119
+ throw new Error(errorMessage);
120
+ }
121
+ });
122
+ }
123
+ /**
124
+ * List available models
125
+ * Command: berget chat list
126
+ */
127
+ listModels(apiKey) {
128
+ return __awaiter(this, void 0, void 0, function* () {
129
+ try {
130
+ if (apiKey) {
131
+ const headers = {
132
+ 'Authorization': `Bearer ${apiKey}`
133
+ };
134
+ const { data, error } = yield this.client.GET('/v1/models', { headers });
135
+ if (error)
136
+ throw new Error(JSON.stringify(error));
137
+ return data;
138
+ }
139
+ else {
140
+ const { data, error } = yield this.client.GET('/v1/models');
141
+ if (error)
142
+ throw new Error(JSON.stringify(error));
143
+ return data;
144
+ }
145
+ }
146
+ catch (error) {
147
+ // Improved error handling
148
+ let errorMessage = 'Failed to list models';
149
+ if (error instanceof Error) {
150
+ try {
151
+ // Try to parse the error message as JSON
152
+ const parsedError = JSON.parse(error.message);
153
+ if (parsedError.error) {
154
+ errorMessage = `Models error: ${typeof parsedError.error === 'string' ?
155
+ parsedError.error :
156
+ (parsedError.error.message || JSON.stringify(parsedError.error))}`;
157
+ }
158
+ }
159
+ catch (e) {
160
+ // If parsing fails, use the original error message
161
+ errorMessage = `Models error: ${error.message}`;
162
+ }
163
+ }
164
+ console.error(chalk_1.default.red(errorMessage));
165
+ throw new Error(errorMessage);
166
+ }
167
+ });
168
+ }
169
+ }
170
+ exports.ChatService = ChatService;
171
+ // Command group name for this service
172
+ ChatService.COMMAND_GROUP = 'chat';
173
+ // Subcommands for this service
174
+ ChatService.COMMANDS = {
175
+ RUN: 'run',
176
+ LIST: 'list'
177
+ };
@@ -0,0 +1,50 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.checkBergetConfig = void 0;
27
+ const fs = __importStar(require("fs"));
28
+ const path = __importStar(require("path"));
29
+ /**
30
+ * Check for .bergetconfig file and handle cluster switching
31
+ */
32
+ function checkBergetConfig() {
33
+ const configPath = path.join(process.cwd(), '.bergetconfig');
34
+ if (fs.existsSync(configPath)) {
35
+ try {
36
+ const config = fs.readFileSync(configPath, 'utf8');
37
+ const match = config.match(/cluster:\s*(.+)/);
38
+ if (match && match[1]) {
39
+ const clusterName = match[1].trim();
40
+ console.log(`🔄 Berget: Switched to cluster "${clusterName}"`);
41
+ console.log('✓ kubectl config updated');
42
+ console.log('');
43
+ }
44
+ }
45
+ catch (error) {
46
+ // Silently ignore errors reading config
47
+ }
48
+ }
49
+ }
50
+ exports.checkBergetConfig = checkBergetConfig;
@@ -0,0 +1,111 @@
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 (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.DefaultApiKeyManager = void 0;
30
+ const fs = __importStar(require("fs"));
31
+ const path = __importStar(require("path"));
32
+ const os = __importStar(require("os"));
33
+ const chalk_1 = __importDefault(require("chalk"));
34
+ /**
35
+ * Manages the default API key for chat commands
36
+ */
37
+ class DefaultApiKeyManager {
38
+ constructor() {
39
+ this.defaultApiKey = null;
40
+ // Set up config file path in user's home directory
41
+ const bergetDir = path.join(os.homedir(), '.berget');
42
+ if (!fs.existsSync(bergetDir)) {
43
+ fs.mkdirSync(bergetDir, { recursive: true });
44
+ }
45
+ this.configFilePath = path.join(bergetDir, 'default-api-key.json');
46
+ this.loadConfig();
47
+ }
48
+ static getInstance() {
49
+ if (!DefaultApiKeyManager.instance) {
50
+ DefaultApiKeyManager.instance = new DefaultApiKeyManager();
51
+ }
52
+ return DefaultApiKeyManager.instance;
53
+ }
54
+ /**
55
+ * Load default API key from file
56
+ */
57
+ loadConfig() {
58
+ try {
59
+ if (fs.existsSync(this.configFilePath)) {
60
+ const data = fs.readFileSync(this.configFilePath, 'utf8');
61
+ this.defaultApiKey = JSON.parse(data);
62
+ }
63
+ }
64
+ catch (error) {
65
+ console.error(chalk_1.default.dim('Failed to load default API key configuration'));
66
+ this.defaultApiKey = null;
67
+ }
68
+ }
69
+ /**
70
+ * Save default API key to file
71
+ */
72
+ saveConfig() {
73
+ try {
74
+ if (this.defaultApiKey) {
75
+ fs.writeFileSync(this.configFilePath, JSON.stringify(this.defaultApiKey, null, 2));
76
+ // Set file permissions to be readable only by the owner
77
+ fs.chmodSync(this.configFilePath, 0o600);
78
+ }
79
+ else {
80
+ // If default API key is null, remove the file
81
+ if (fs.existsSync(this.configFilePath)) {
82
+ fs.unlinkSync(this.configFilePath);
83
+ }
84
+ }
85
+ }
86
+ catch (error) {
87
+ console.error(chalk_1.default.dim('Failed to save default API key configuration'));
88
+ }
89
+ }
90
+ /**
91
+ * Set the default API key
92
+ */
93
+ setDefaultApiKey(id, name, prefix) {
94
+ this.defaultApiKey = { id, name, prefix };
95
+ this.saveConfig();
96
+ }
97
+ /**
98
+ * Get the default API key
99
+ */
100
+ getDefaultApiKey() {
101
+ return this.defaultApiKey;
102
+ }
103
+ /**
104
+ * Clear the default API key
105
+ */
106
+ clearDefaultApiKey() {
107
+ this.defaultApiKey = null;
108
+ this.saveConfig();
109
+ }
110
+ }
111
+ exports.DefaultApiKeyManager = DefaultApiKeyManager;