@capawesome/cli 1.14.0 → 2.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +7 -3
  3. package/dist/commands/apps/bundles/create.js +206 -239
  4. package/dist/commands/apps/bundles/create.test.js +276 -0
  5. package/dist/commands/apps/bundles/delete.js +35 -60
  6. package/dist/commands/apps/bundles/delete.test.js +139 -0
  7. package/dist/commands/apps/bundles/update.js +61 -89
  8. package/dist/commands/apps/bundles/update.test.js +141 -0
  9. package/dist/commands/apps/channels/create.js +45 -75
  10. package/dist/commands/apps/channels/create.test.js +119 -0
  11. package/dist/commands/apps/channels/delete.js +46 -69
  12. package/dist/commands/apps/channels/delete.test.js +141 -0
  13. package/dist/commands/apps/channels/get.js +52 -94
  14. package/dist/commands/apps/channels/get.test.js +135 -0
  15. package/dist/commands/apps/channels/list.js +37 -82
  16. package/dist/commands/apps/channels/list.test.js +121 -0
  17. package/dist/commands/apps/channels/update.js +39 -83
  18. package/dist/commands/apps/channels/update.test.js +138 -0
  19. package/dist/commands/apps/create.js +28 -53
  20. package/dist/commands/apps/create.test.js +117 -0
  21. package/dist/commands/apps/delete.js +29 -50
  22. package/dist/commands/apps/delete.test.js +120 -0
  23. package/dist/commands/apps/devices/delete.js +35 -60
  24. package/dist/commands/apps/devices/delete.test.js +139 -0
  25. package/dist/commands/doctor.js +12 -29
  26. package/dist/commands/doctor.test.js +52 -0
  27. package/dist/commands/login.js +50 -71
  28. package/dist/commands/login.test.js +116 -0
  29. package/dist/commands/logout.js +13 -31
  30. package/dist/commands/logout.test.js +47 -0
  31. package/dist/commands/manifests/generate.js +20 -38
  32. package/dist/commands/manifests/generate.test.js +60 -0
  33. package/dist/commands/organizations/create.js +25 -0
  34. package/dist/commands/organizations/create.test.js +80 -0
  35. package/dist/commands/whoami.js +20 -31
  36. package/dist/commands/whoami.test.js +30 -0
  37. package/dist/config/consts.js +4 -5
  38. package/dist/config/index.js +1 -17
  39. package/dist/index.js +59 -80
  40. package/dist/services/app-bundle-files.js +117 -136
  41. package/dist/services/app-bundles.js +22 -41
  42. package/dist/services/app-channels.js +54 -77
  43. package/dist/services/app-devices.js +10 -25
  44. package/dist/services/apps.js +25 -43
  45. package/dist/services/authorization-service.js +4 -8
  46. package/dist/services/config.js +15 -28
  47. package/dist/services/organizations.js +19 -26
  48. package/dist/services/session-code.js +7 -22
  49. package/dist/services/sessions.js +13 -30
  50. package/dist/services/update.js +17 -55
  51. package/dist/services/users.js +11 -26
  52. package/dist/types/app-bundle-file.js +1 -2
  53. package/dist/types/app-bundle.js +1 -2
  54. package/dist/types/app-channel.js +1 -2
  55. package/dist/types/app-device.js +1 -2
  56. package/dist/types/app.js +1 -2
  57. package/dist/types/index.js +8 -24
  58. package/dist/types/npm-package.js +1 -2
  59. package/dist/types/organization.js +1 -2
  60. package/dist/types/session-code.js +1 -2
  61. package/dist/types/session.js +1 -2
  62. package/dist/types/user.js +1 -2
  63. package/dist/utils/buffer.js +12 -43
  64. package/dist/utils/error.js +24 -14
  65. package/dist/utils/file.js +22 -41
  66. package/dist/utils/hash.js +3 -39
  67. package/dist/utils/http-client.js +27 -53
  68. package/dist/utils/manifest.js +11 -24
  69. package/dist/utils/private-key.js +23 -0
  70. package/dist/utils/prompt.js +9 -26
  71. package/dist/utils/signature.js +3 -39
  72. package/dist/utils/user-config.js +12 -0
  73. package/dist/utils/zip.js +11 -27
  74. package/package.json +22 -9
  75. package/dist/utils/ci.js +0 -7
  76. package/dist/utils/userConfig.js +0 -16
@@ -0,0 +1,276 @@
1
+ import { DEFAULT_API_BASE_URL } from '../../../config/consts.js';
2
+ import authorizationService from '../../../services/authorization-service.js';
3
+ import { fileExistsAtPath, isDirectory } from '../../../utils/file.js';
4
+ import userConfig from '../../../utils/user-config.js';
5
+ import consola from 'consola';
6
+ import nock from 'nock';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import createBundleCommand from './create.js';
9
+ // Mock dependencies
10
+ vi.mock('@/utils/user-config.js');
11
+ vi.mock('@/services/authorization-service.js');
12
+ vi.mock('@/utils/file.js');
13
+ vi.mock('@/utils/zip.js');
14
+ vi.mock('@/utils/buffer.js');
15
+ vi.mock('@/utils/private-key.js');
16
+ vi.mock('@/utils/hash.js');
17
+ vi.mock('@/utils/signature.js');
18
+ vi.mock('consola');
19
+ describe('apps-bundles-create', () => {
20
+ const mockUserConfig = vi.mocked(userConfig);
21
+ const mockAuthorizationService = vi.mocked(authorizationService);
22
+ const mockFileExistsAtPath = vi.mocked(fileExistsAtPath);
23
+ const mockIsDirectory = vi.mocked(isDirectory);
24
+ const mockConsola = vi.mocked(consola);
25
+ beforeEach(() => {
26
+ vi.clearAllMocks();
27
+ mockUserConfig.read.mockReturnValue({ token: 'test-token' });
28
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(true);
29
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue('test-token');
30
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
31
+ throw new Error(`Process exited with code ${code}`);
32
+ });
33
+ });
34
+ afterEach(() => {
35
+ nock.cleanAll();
36
+ vi.restoreAllMocks();
37
+ });
38
+ it('should require authentication', async () => {
39
+ const appId = 'app-123';
40
+ const options = { appId, path: './dist', artifactType: 'zip', rollout: 1 };
41
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(false);
42
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
43
+ expect(mockConsola.error).toHaveBeenCalledWith('You must be logged in to run this command.');
44
+ });
45
+ it('should create bundle with self-hosted URL', async () => {
46
+ const appId = 'app-123';
47
+ const bundleUrl = 'https://example.com/bundle.zip';
48
+ const bundlePath = './bundle.zip';
49
+ const testHash = 'test-hash';
50
+ const bundleId = 'bundle-456';
51
+ const testToken = 'test-token';
52
+ const testBuffer = Buffer.from('test');
53
+ const options = {
54
+ appId,
55
+ url: bundleUrl,
56
+ path: bundlePath,
57
+ artifactType: 'zip',
58
+ rollout: 1,
59
+ };
60
+ mockFileExistsAtPath.mockResolvedValue(true);
61
+ mockIsDirectory.mockResolvedValue(false);
62
+ // Mock utility functions
63
+ const mockZip = await import('../../../utils/zip.js');
64
+ const mockBuffer = await import('../../../utils/buffer.js');
65
+ const mockHash = await import('../../../utils/hash.js');
66
+ vi.mocked(mockZip.default.isZipped).mockReturnValue(true);
67
+ vi.mocked(mockBuffer.createBufferFromPath).mockResolvedValue(testBuffer);
68
+ vi.mocked(mockHash.createHash).mockResolvedValue(testHash);
69
+ const scope = nock(DEFAULT_API_BASE_URL)
70
+ .post(`/v1/apps/${appId}/bundles`, {
71
+ appId,
72
+ url: bundleUrl,
73
+ checksum: testHash,
74
+ artifactType: 'zip',
75
+ rolloutPercentage: 1,
76
+ })
77
+ .matchHeader('Authorization', `Bearer ${testToken}`)
78
+ .reply(201, { id: bundleId });
79
+ await createBundleCommand.action(options, undefined);
80
+ expect(scope.isDone()).toBe(true);
81
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle successfully created.');
82
+ expect(mockConsola.info).toHaveBeenCalledWith(`Bundle ID: ${bundleId}`);
83
+ });
84
+ it('should handle path validation errors', async () => {
85
+ const appId = 'app-123';
86
+ const nonexistentPath = './nonexistent';
87
+ const options = { appId, path: nonexistentPath, artifactType: 'zip', rollout: 1 };
88
+ mockFileExistsAtPath.mockResolvedValue(false);
89
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
90
+ expect(mockConsola.error).toHaveBeenCalledWith('The path does not exist.');
91
+ });
92
+ it('should validate manifest artifact type requires directory', async () => {
93
+ const appId = 'app-123';
94
+ const bundlePath = './bundle.zip';
95
+ const options = {
96
+ appId,
97
+ path: bundlePath,
98
+ artifactType: 'manifest',
99
+ rollout: 1,
100
+ };
101
+ mockFileExistsAtPath.mockResolvedValue(true);
102
+ mockIsDirectory.mockResolvedValue(false);
103
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
104
+ expect(mockConsola.error).toHaveBeenCalledWith('The path must be a folder when creating a bundle with an artifact type of `manifest`.');
105
+ });
106
+ it('should validate manifest artifact type cannot use URL', async () => {
107
+ const appId = 'app-123';
108
+ const bundleUrl = 'https://example.com/bundle.zip';
109
+ const options = {
110
+ appId,
111
+ url: bundleUrl,
112
+ artifactType: 'manifest',
113
+ rollout: 1,
114
+ };
115
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
116
+ expect(mockConsola.error).toHaveBeenCalledWith('It is not yet possible to provide a URL when creating a bundle with an artifact type of `manifest`.');
117
+ });
118
+ it('should handle API error during creation', async () => {
119
+ const appId = 'app-123';
120
+ const bundleUrl = 'https://example.com/bundle.zip';
121
+ const testToken = 'test-token';
122
+ const options = {
123
+ appId,
124
+ url: bundleUrl,
125
+ artifactType: 'zip',
126
+ rollout: 1,
127
+ };
128
+ const scope = nock(DEFAULT_API_BASE_URL)
129
+ .post(`/v1/apps/${appId}/bundles`)
130
+ .matchHeader('Authorization', `Bearer ${testToken}`)
131
+ .reply(400, { message: 'Invalid bundle data' });
132
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow();
133
+ expect(scope.isDone()).toBe(true);
134
+ });
135
+ it('should handle private key file path', async () => {
136
+ const appId = 'app-123';
137
+ const bundleUrl = 'https://example.com/bundle.zip';
138
+ const bundlePath = './bundle.zip';
139
+ const privateKeyPath = 'private-key.pem';
140
+ const testHash = 'test-hash';
141
+ const testSignature = 'test-signature';
142
+ const bundleId = 'bundle-456';
143
+ const testToken = 'test-token';
144
+ const testBuffer = Buffer.from('test');
145
+ const options = {
146
+ appId,
147
+ url: bundleUrl,
148
+ path: bundlePath,
149
+ privateKey: privateKeyPath,
150
+ artifactType: 'zip',
151
+ rollout: 1,
152
+ };
153
+ mockFileExistsAtPath.mockImplementation((path) => {
154
+ if (path === privateKeyPath)
155
+ return Promise.resolve(true);
156
+ if (path === bundlePath)
157
+ return Promise.resolve(true);
158
+ return Promise.resolve(false);
159
+ });
160
+ mockIsDirectory.mockResolvedValue(false);
161
+ // Mock utility functions
162
+ const mockZip = await import('../../../utils/zip.js');
163
+ const mockBuffer = await import('../../../utils/buffer.js');
164
+ const mockPrivateKey = await import('../../../utils/private-key.js');
165
+ const mockHash = await import('../../../utils/hash.js');
166
+ const mockSignature = await import('../../../utils/signature.js');
167
+ vi.mocked(mockZip.default.isZipped).mockReturnValue(true);
168
+ vi.mocked(mockBuffer.createBufferFromPath).mockResolvedValue(testBuffer);
169
+ vi.mocked(mockBuffer.isPrivateKeyContent).mockReturnValue(false);
170
+ vi.mocked(mockPrivateKey.formatPrivateKey).mockReturnValue('formatted-private-key');
171
+ vi.mocked(mockBuffer.createBufferFromString).mockReturnValue(testBuffer);
172
+ vi.mocked(mockHash.createHash).mockResolvedValue(testHash);
173
+ vi.mocked(mockSignature.createSignature).mockResolvedValue(testSignature);
174
+ const scope = nock(DEFAULT_API_BASE_URL)
175
+ .post(`/v1/apps/${appId}/bundles`, {
176
+ appId,
177
+ url: bundleUrl,
178
+ checksum: testHash,
179
+ signature: testSignature,
180
+ artifactType: 'zip',
181
+ rolloutPercentage: 1,
182
+ })
183
+ .matchHeader('Authorization', `Bearer ${testToken}`)
184
+ .reply(201, { id: bundleId });
185
+ await createBundleCommand.action(options, undefined);
186
+ expect(scope.isDone()).toBe(true);
187
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle successfully created.');
188
+ });
189
+ it('should handle private key plain text content', async () => {
190
+ const appId = 'app-123';
191
+ const bundleUrl = 'https://example.com/bundle.zip';
192
+ const bundlePath = './bundle.zip';
193
+ const privateKeyContent = '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCgxvzJrMCbmtjb\n-----END PRIVATE KEY-----';
194
+ const testHash = 'test-hash';
195
+ const testSignature = 'test-signature';
196
+ const bundleId = 'bundle-456';
197
+ const testToken = 'test-token';
198
+ const testBuffer = Buffer.from('test');
199
+ const options = {
200
+ appId,
201
+ url: bundleUrl,
202
+ path: bundlePath,
203
+ privateKey: privateKeyContent,
204
+ artifactType: 'zip',
205
+ rollout: 1,
206
+ };
207
+ mockFileExistsAtPath.mockResolvedValue(true);
208
+ mockIsDirectory.mockResolvedValue(false);
209
+ // Mock utility functions
210
+ const mockZip = await import('../../../utils/zip.js');
211
+ const mockBuffer = await import('../../../utils/buffer.js');
212
+ const mockPrivateKey = await import('../../../utils/private-key.js');
213
+ const mockHash = await import('../../../utils/hash.js');
214
+ const mockSignature = await import('../../../utils/signature.js');
215
+ vi.mocked(mockZip.default.isZipped).mockReturnValue(true);
216
+ vi.mocked(mockBuffer.createBufferFromPath).mockResolvedValue(testBuffer);
217
+ vi.mocked(mockBuffer.createBufferFromString).mockReturnValue(testBuffer);
218
+ vi.mocked(mockBuffer.isPrivateKeyContent).mockReturnValue(true);
219
+ vi.mocked(mockPrivateKey.formatPrivateKey).mockReturnValue('formatted-private-key');
220
+ vi.mocked(mockHash.createHash).mockResolvedValue(testHash);
221
+ vi.mocked(mockSignature.createSignature).mockResolvedValue(testSignature);
222
+ const scope = nock(DEFAULT_API_BASE_URL)
223
+ .post(`/v1/apps/${appId}/bundles`, {
224
+ appId,
225
+ url: bundleUrl,
226
+ checksum: testHash,
227
+ signature: testSignature,
228
+ artifactType: 'zip',
229
+ rolloutPercentage: 1,
230
+ })
231
+ .matchHeader('Authorization', `Bearer ${testToken}`)
232
+ .reply(201, { id: bundleId });
233
+ await createBundleCommand.action(options, undefined);
234
+ expect(scope.isDone()).toBe(true);
235
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle successfully created.');
236
+ });
237
+ it('should handle private key file not found', async () => {
238
+ const appId = 'app-123';
239
+ const privateKeyPath = 'nonexistent-key.pem';
240
+ const options = {
241
+ appId,
242
+ path: './dist',
243
+ privateKey: privateKeyPath,
244
+ artifactType: 'zip',
245
+ rollout: 1,
246
+ };
247
+ mockFileExistsAtPath.mockImplementation((path) => {
248
+ if (path === privateKeyPath)
249
+ return Promise.resolve(false);
250
+ return Promise.resolve(true);
251
+ });
252
+ // Mock utility functions
253
+ const mockBuffer = await import('../../../utils/buffer.js');
254
+ vi.mocked(mockBuffer.isPrivateKeyContent).mockReturnValue(false);
255
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
256
+ expect(mockConsola.error).toHaveBeenCalledWith('Private key file not found.');
257
+ });
258
+ it('should handle invalid private key format', async () => {
259
+ const appId = 'app-123';
260
+ const invalidPrivateKey = 'not-a-valid-key';
261
+ const options = {
262
+ appId,
263
+ path: './dist',
264
+ privateKey: invalidPrivateKey,
265
+ artifactType: 'zip',
266
+ rollout: 1,
267
+ };
268
+ mockFileExistsAtPath.mockResolvedValue(true);
269
+ mockIsDirectory.mockResolvedValue(false);
270
+ // Mock utility functions
271
+ const mockBuffer = await import('../../../utils/buffer.js');
272
+ vi.mocked(mockBuffer.isPrivateKeyContent).mockReturnValue(false);
273
+ await expect(createBundleCommand.action(options, undefined)).rejects.toThrow('Process exited with code 1');
274
+ expect(mockConsola.error).toHaveBeenCalledWith('Private key must be either a path to a .pem file or the private key content as plain text.');
275
+ });
276
+ });
@@ -1,94 +1,69 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const citty_1 = require("citty");
16
- const consola_1 = __importDefault(require("consola"));
17
- const app_bundles_1 = __importDefault(require("../../../services/app-bundles"));
18
- const apps_1 = __importDefault(require("../../../services/apps"));
19
- const organizations_1 = __importDefault(require("../../../services/organizations"));
20
- const error_1 = require("../../../utils/error");
21
- const prompt_1 = require("../../../utils/prompt");
22
- exports.default = (0, citty_1.defineCommand)({
23
- meta: {
24
- description: 'Delete an app bundle.',
25
- },
26
- args: {
27
- appId: {
28
- type: 'string',
29
- description: 'ID of the app.',
30
- },
31
- bundleId: {
32
- type: 'string',
33
- description: 'ID of the bundle.',
34
- },
35
- },
36
- run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
1
+ import appBundlesService from '../../../services/app-bundles.js';
2
+ import appsService from '../../../services/apps.js';
3
+ import authorizationService from '../../../services/authorization-service.js';
4
+ import organizationsService from '../../../services/organizations.js';
5
+ import { prompt } from '../../../utils/prompt.js';
6
+ import { defineCommand, defineOptions } from '@robingenz/zli';
7
+ import consola from 'consola';
8
+ import { z } from 'zod';
9
+ export default defineCommand({
10
+ description: 'Delete an app bundle.',
11
+ options: defineOptions(z.object({
12
+ appId: z.string().optional().describe('ID of the app.'),
13
+ bundleId: z.string().optional().describe('ID of the bundle.'),
14
+ })),
15
+ action: async (options, args) => {
16
+ let { appId, bundleId } = options;
17
+ if (!authorizationService.hasAuthorizationToken()) {
18
+ consola.error('You must be logged in to run this command.');
19
+ process.exit(1);
20
+ }
37
21
  // Prompt for missing arguments
38
- let appId = ctx.args.appId;
39
- let bundleId = ctx.args.bundleId;
40
22
  if (!appId) {
41
- const organizations = yield organizations_1.default.findAll();
23
+ const organizations = await organizationsService.findAll();
42
24
  if (organizations.length === 0) {
43
- consola_1.default.error('You must create an organization before deleting a bundle.');
25
+ consola.error('You must create an organization before deleting a bundle.');
44
26
  process.exit(1);
45
27
  }
46
28
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
47
- const organizationId = yield (0, prompt_1.prompt)('Select the organization of the app from which you want to delete a bundle.', {
29
+ const organizationId = await prompt('Select the organization of the app from which you want to delete a bundle.', {
48
30
  type: 'select',
49
31
  options: organizations.map((organization) => ({ label: organization.name, value: organization.id })),
50
32
  });
51
33
  if (!organizationId) {
52
- consola_1.default.error('You must select the organization of an app from which you want to delete a bundle.');
34
+ consola.error('You must select the organization of an app from which you want to delete a bundle.');
53
35
  process.exit(1);
54
36
  }
55
- const apps = yield apps_1.default.findAll({
37
+ const apps = await appsService.findAll({
56
38
  organizationId,
57
39
  });
58
40
  if (!apps.length) {
59
- consola_1.default.error('You must create an app before deleting a bundle.');
41
+ consola.error('You must create an app before deleting a bundle.');
60
42
  process.exit(1);
61
43
  }
62
44
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
63
- appId = yield (0, prompt_1.prompt)('Which app do you want to delete the bundle from?', {
45
+ appId = await prompt('Which app do you want to delete the bundle from?', {
64
46
  type: 'select',
65
47
  options: apps.map((app) => ({ label: app.name, value: app.id })),
66
48
  });
67
49
  }
68
50
  if (!bundleId) {
69
- bundleId = yield (0, prompt_1.prompt)('Enter the bundle ID:', {
51
+ bundleId = await prompt('Enter the bundle ID:', {
70
52
  type: 'text',
71
53
  });
72
54
  }
73
55
  // Confirm deletion
74
- const confirmed = yield (0, prompt_1.prompt)('Are you sure you want to delete this bundle?', {
56
+ const confirmed = await prompt('Are you sure you want to delete this bundle?', {
75
57
  type: 'confirm',
76
58
  });
77
59
  if (!confirmed) {
78
60
  return;
79
61
  }
80
62
  // Delete bundle
81
- try {
82
- yield app_bundles_1.default.delete({
83
- appId,
84
- appBundleId: bundleId,
85
- });
86
- consola_1.default.success('Bundle deleted successfully.');
87
- }
88
- catch (error) {
89
- const message = (0, error_1.getMessageFromUnknownError)(error);
90
- consola_1.default.error(message);
91
- process.exit(1);
92
- }
93
- }),
63
+ await appBundlesService.delete({
64
+ appId,
65
+ appBundleId: bundleId,
66
+ });
67
+ consola.success('Bundle deleted successfully.');
68
+ },
94
69
  });
@@ -0,0 +1,139 @@
1
+ import { DEFAULT_API_BASE_URL } from '../../../config/consts.js';
2
+ import authorizationService from '../../../services/authorization-service.js';
3
+ import { prompt } from '../../../utils/prompt.js';
4
+ import userConfig from '../../../utils/user-config.js';
5
+ import consola from 'consola';
6
+ import nock from 'nock';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import deleteBundleCommand from './delete.js';
9
+ // Mock dependencies
10
+ vi.mock('@/utils/user-config.js');
11
+ vi.mock('@/utils/prompt.js');
12
+ vi.mock('@/services/authorization-service.js');
13
+ vi.mock('consola');
14
+ describe('apps-bundles-delete', () => {
15
+ const mockUserConfig = vi.mocked(userConfig);
16
+ const mockPrompt = vi.mocked(prompt);
17
+ const mockConsola = vi.mocked(consola);
18
+ const mockAuthorizationService = vi.mocked(authorizationService);
19
+ beforeEach(() => {
20
+ vi.clearAllMocks();
21
+ mockUserConfig.read.mockReturnValue({ token: 'test-token' });
22
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue('test-token');
23
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(true);
24
+ vi.spyOn(process, 'exit').mockImplementation(() => undefined);
25
+ });
26
+ afterEach(() => {
27
+ nock.cleanAll();
28
+ vi.restoreAllMocks();
29
+ });
30
+ it('should delete bundle with provided appId and bundleId after confirmation', async () => {
31
+ const appId = 'app-123';
32
+ const bundleId = 'bundle-456';
33
+ const testToken = 'test-token';
34
+ const options = { appId, bundleId };
35
+ mockPrompt.mockResolvedValueOnce(true); // confirmation
36
+ const scope = nock(DEFAULT_API_BASE_URL)
37
+ .delete(`/v1/apps/${appId}/bundles/${bundleId}`)
38
+ .matchHeader('Authorization', `Bearer ${testToken}`)
39
+ .reply(200);
40
+ await deleteBundleCommand.action(options, undefined);
41
+ expect(scope.isDone()).toBe(true);
42
+ expect(mockPrompt).toHaveBeenCalledWith('Are you sure you want to delete this bundle?', {
43
+ type: 'confirm',
44
+ });
45
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle deleted successfully.');
46
+ });
47
+ it('should not delete bundle when confirmation is declined', async () => {
48
+ const appId = 'app-123';
49
+ const bundleId = 'bundle-456';
50
+ const options = { appId, bundleId };
51
+ mockPrompt.mockResolvedValueOnce(false); // declined confirmation
52
+ await deleteBundleCommand.action(options, undefined);
53
+ expect(mockPrompt).toHaveBeenCalledWith('Are you sure you want to delete this bundle?', {
54
+ type: 'confirm',
55
+ });
56
+ expect(mockConsola.success).not.toHaveBeenCalled();
57
+ });
58
+ it('should prompt for app selection when appId not provided', async () => {
59
+ const orgId = 'org-1';
60
+ const appId = 'app-1';
61
+ const bundleId = 'bundle-456';
62
+ const testToken = 'test-token';
63
+ const organization = { id: orgId, name: 'Org 1' };
64
+ const app = { id: appId, name: 'App 1' };
65
+ const options = { bundleId };
66
+ const orgsScope = nock(DEFAULT_API_BASE_URL)
67
+ .get('/v1/organizations')
68
+ .matchHeader('Authorization', `Bearer ${testToken}`)
69
+ .reply(200, [organization]);
70
+ const appsScope = nock(DEFAULT_API_BASE_URL)
71
+ .get('/v1/apps')
72
+ .query({ organizationId: orgId })
73
+ .matchHeader('Authorization', `Bearer ${testToken}`)
74
+ .reply(200, [app]);
75
+ const deleteScope = nock(DEFAULT_API_BASE_URL)
76
+ .delete(`/v1/apps/${appId}/bundles/${bundleId}`)
77
+ .matchHeader('Authorization', `Bearer ${testToken}`)
78
+ .reply(200);
79
+ mockPrompt
80
+ .mockResolvedValueOnce(orgId) // organization selection
81
+ .mockResolvedValueOnce(appId) // app selection
82
+ .mockResolvedValueOnce(true); // confirmation
83
+ await deleteBundleCommand.action(options, undefined);
84
+ expect(orgsScope.isDone()).toBe(true);
85
+ expect(appsScope.isDone()).toBe(true);
86
+ expect(deleteScope.isDone()).toBe(true);
87
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle deleted successfully.');
88
+ });
89
+ it('should prompt for bundleId when not provided', async () => {
90
+ const appId = 'app-123';
91
+ const bundleId = 'bundle-456';
92
+ const testToken = 'test-token';
93
+ const options = { appId };
94
+ const scope = nock(DEFAULT_API_BASE_URL)
95
+ .delete(`/v1/apps/${appId}/bundles/${bundleId}`)
96
+ .matchHeader('Authorization', `Bearer ${testToken}`)
97
+ .reply(200);
98
+ mockPrompt
99
+ .mockResolvedValueOnce(bundleId) // bundle ID input
100
+ .mockResolvedValueOnce(true); // confirmation
101
+ await deleteBundleCommand.action(options, undefined);
102
+ expect(scope.isDone()).toBe(true);
103
+ expect(mockPrompt).toHaveBeenCalledWith('Enter the bundle ID:', { type: 'text' });
104
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle deleted successfully.');
105
+ });
106
+ it('should handle error when no organizations exist', async () => {
107
+ const testToken = 'test-token';
108
+ const options = {};
109
+ const scope = nock(DEFAULT_API_BASE_URL)
110
+ .get('/v1/organizations')
111
+ .matchHeader('Authorization', `Bearer ${testToken}`)
112
+ .reply(200, []);
113
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
114
+ throw new Error(`process.exit called with code ${code}`);
115
+ });
116
+ try {
117
+ await deleteBundleCommand.action(options, undefined);
118
+ }
119
+ catch (error) {
120
+ expect(error.message).toBe('process.exit called with code 1');
121
+ }
122
+ expect(scope.isDone()).toBe(true);
123
+ expect(mockConsola.error).toHaveBeenCalledWith('You must create an organization before deleting a bundle.');
124
+ expect(exitSpy).toHaveBeenCalledWith(1);
125
+ });
126
+ it('should handle API error during deletion', async () => {
127
+ const appId = 'app-123';
128
+ const bundleId = 'bundle-456';
129
+ const testToken = 'test-token';
130
+ const options = { appId, bundleId };
131
+ mockPrompt.mockResolvedValueOnce(true);
132
+ const scope = nock(DEFAULT_API_BASE_URL)
133
+ .delete(`/v1/apps/${appId}/bundles/${bundleId}`)
134
+ .matchHeader('Authorization', `Bearer ${testToken}`)
135
+ .reply(404, { message: 'Bundle not found' });
136
+ await expect(deleteBundleCommand.action(options, undefined)).rejects.toThrow();
137
+ expect(scope.isDone()).toBe(true);
138
+ });
139
+ });