@capawesome/cli 1.13.2 → 1.14.0-dev.1f912c9.1755635879

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 (72) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +3 -3
  3. package/dist/commands/apps/bundles/create.js +215 -233
  4. package/dist/commands/apps/bundles/create.test.js +274 -0
  5. package/dist/commands/apps/bundles/delete.js +42 -47
  6. package/dist/commands/apps/bundles/delete.test.js +140 -0
  7. package/dist/commands/apps/bundles/update.js +69 -72
  8. package/dist/commands/apps/bundles/update.test.js +142 -0
  9. package/dist/commands/apps/channels/create.js +47 -70
  10. package/dist/commands/apps/channels/create.test.js +115 -0
  11. package/dist/commands/apps/channels/delete.js +53 -56
  12. package/dist/commands/apps/channels/delete.test.js +140 -0
  13. package/dist/commands/apps/channels/get.js +27 -61
  14. package/dist/commands/apps/channels/get.test.js +136 -0
  15. package/dist/commands/apps/channels/list.js +26 -63
  16. package/dist/commands/apps/channels/list.test.js +123 -0
  17. package/dist/commands/apps/channels/update.js +48 -67
  18. package/dist/commands/apps/channels/update.test.js +139 -0
  19. package/dist/commands/apps/create.js +38 -38
  20. package/dist/commands/apps/create.test.js +117 -0
  21. package/dist/commands/apps/delete.js +39 -40
  22. package/dist/commands/apps/delete.test.js +119 -0
  23. package/dist/commands/apps/devices/delete.js +42 -47
  24. package/dist/commands/apps/devices/delete.test.js +140 -0
  25. package/dist/commands/doctor.js +12 -29
  26. package/dist/commands/doctor.test.js +52 -0
  27. package/dist/commands/login.js +48 -69
  28. package/dist/commands/login.test.js +122 -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/whoami.js +13 -30
  34. package/dist/commands/whoami.test.js +30 -0
  35. package/dist/config/consts.js +4 -5
  36. package/dist/config/index.js +1 -17
  37. package/dist/index.js +50 -80
  38. package/dist/services/app-bundle-files.js +117 -136
  39. package/dist/services/app-bundles.js +22 -41
  40. package/dist/services/app-channels.js +54 -77
  41. package/dist/services/app-devices.js +10 -25
  42. package/dist/services/apps.js +25 -41
  43. package/dist/services/authorization-service.js +4 -8
  44. package/dist/services/config.js +15 -28
  45. package/dist/services/organizations.js +18 -0
  46. package/dist/services/session-code.js +7 -22
  47. package/dist/services/sessions.js +13 -30
  48. package/dist/services/update.js +17 -55
  49. package/dist/services/users.js +11 -26
  50. package/dist/types/app-bundle-file.js +1 -2
  51. package/dist/types/app-bundle.js +1 -2
  52. package/dist/types/app-channel.js +1 -2
  53. package/dist/types/app-device.js +1 -2
  54. package/dist/types/app.js +1 -2
  55. package/dist/types/index.js +8 -23
  56. package/dist/types/npm-package.js +1 -2
  57. package/dist/types/organization.js +1 -0
  58. package/dist/types/session-code.js +1 -2
  59. package/dist/types/session.js +1 -2
  60. package/dist/types/user.js +1 -2
  61. package/dist/utils/buffer.js +12 -43
  62. package/dist/utils/error.js +24 -14
  63. package/dist/utils/file.js +22 -41
  64. package/dist/utils/hash.js +3 -39
  65. package/dist/utils/http-client.js +27 -53
  66. package/dist/utils/manifest.js +11 -24
  67. package/dist/utils/prompt.js +9 -26
  68. package/dist/utils/signature.js +3 -39
  69. package/dist/utils/userConfig.js +5 -9
  70. package/dist/utils/zip.js +11 -27
  71. package/package.json +22 -9
  72. package/dist/utils/ci.js +0 -7
@@ -1,102 +1,99 @@
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 authorization_service_1 = __importDefault(require("../../../services/authorization-service"));
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: 'Update an app bundle.',
25
- },
26
- args: {
27
- androidMax: {
28
- type: 'string',
29
- description: 'The maximum Android version code (`versionCode`) that the bundle supports.',
30
- },
31
- androidMin: {
32
- type: 'string',
33
- description: 'The minimum Android version code (`versionCode`) that the bundle supports.',
34
- },
35
- appId: {
36
- type: 'string',
37
- description: 'ID of the app.',
38
- },
39
- bundleId: {
40
- type: 'string',
41
- description: 'ID of the bundle.',
42
- },
43
- rollout: {
44
- type: 'string',
45
- description: 'The percentage of devices to deploy the bundle to. Must be a number between 0 and 1 (e.g. 0.5).',
46
- },
47
- iosMax: {
48
- type: 'string',
49
- description: 'The maximum iOS bundle version (`CFBundleVersion`) that the bundle supports.',
50
- },
51
- iosMin: {
52
- type: 'string',
53
- description: 'The minimum iOS bundle version (`CFBundleVersion`) that the bundle supports.',
54
- },
55
- },
56
- run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
57
- if (!authorization_service_1.default.hasAuthorizationToken()) {
58
- consola_1.default.error('You must be logged in to run this command.');
1
+ import { defineCommand, defineOptions } from '@robingenz/zli';
2
+ import consola from 'consola';
3
+ import { z } from 'zod';
4
+ import appBundlesService from '../../../services/app-bundles.js';
5
+ import appsService from '../../../services/apps.js';
6
+ import authorizationService from '../../../services/authorization-service.js';
7
+ import organizationsService from '../../../services/organizations.js';
8
+ import { getMessageFromUnknownError } from '../../../utils/error.js';
9
+ import { prompt } from '../../../utils/prompt.js';
10
+ export default defineCommand({
11
+ description: 'Update an app bundle.',
12
+ options: defineOptions(z.object({
13
+ androidMax: z
14
+ .string()
15
+ .optional()
16
+ .describe('The maximum Android version code (`versionCode`) that the bundle supports.'),
17
+ androidMin: z
18
+ .string()
19
+ .optional()
20
+ .describe('The minimum Android version code (`versionCode`) that the bundle supports.'),
21
+ appId: z.string().optional().describe('ID of the app.'),
22
+ bundleId: z.string().optional().describe('ID of the bundle.'),
23
+ rollout: z.coerce
24
+ .number()
25
+ .min(0)
26
+ .max(1, {
27
+ message: 'Rollout percentage must be a number between 0 and 1 (e.g. 0.5).',
28
+ })
29
+ .optional()
30
+ .describe('The percentage of devices to deploy the bundle to. Must be a number between 0 and 1 (e.g. 0.5).'),
31
+ iosMax: z
32
+ .string()
33
+ .optional()
34
+ .describe('The maximum iOS bundle version (`CFBundleVersion`) that the bundle supports.'),
35
+ iosMin: z
36
+ .string()
37
+ .optional()
38
+ .describe('The minimum iOS bundle version (`CFBundleVersion`) that the bundle supports.'),
39
+ })),
40
+ action: async (options, args) => {
41
+ let { androidMax, androidMin, appId, bundleId, rollout, iosMax, iosMin } = options;
42
+ if (!authorizationService.hasAuthorizationToken()) {
43
+ consola.error('You must be logged in to run this command.');
59
44
  process.exit(1);
60
45
  }
61
46
  // Prompt for missing arguments
62
- const { androidMax, androidMin, rollout, iosMax, iosMin } = ctx.args;
63
- let appId = ctx.args.appId;
64
- let bundleId = ctx.args.bundleId;
65
47
  if (!appId) {
66
- const apps = yield apps_1.default.findAll();
48
+ const organizations = await organizationsService.findAll();
49
+ if (organizations.length === 0) {
50
+ consola.error('You must create an organization before updating a bundle.');
51
+ process.exit(1);
52
+ }
53
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
54
+ const organizationId = await prompt('Select the organization of the app for which you want to update a bundle.', {
55
+ type: 'select',
56
+ options: organizations.map((organization) => ({ label: organization.name, value: organization.id })),
57
+ });
58
+ if (!organizationId) {
59
+ consola.error('You must select the organization of an app for which you want to update a bundle.');
60
+ process.exit(1);
61
+ }
62
+ const apps = await appsService.findAll({
63
+ organizationId,
64
+ });
67
65
  if (!apps.length) {
68
- consola_1.default.error('You must create an app before updating a bundle.');
66
+ consola.error('You must create an app before updating a bundle.');
69
67
  process.exit(1);
70
68
  }
71
69
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
72
- appId = yield (0, prompt_1.prompt)('Which app do you want to update the bundle for?', {
70
+ appId = await prompt('Which app do you want to update the bundle for?', {
73
71
  type: 'select',
74
72
  options: apps.map((app) => ({ label: app.name, value: app.id })),
75
73
  });
76
74
  }
77
75
  if (!bundleId) {
78
- bundleId = yield (0, prompt_1.prompt)('Enter the bundle ID:', {
76
+ bundleId = await prompt('Enter the bundle ID:', {
79
77
  type: 'text',
80
78
  });
81
79
  }
82
80
  // Update bundle
83
81
  try {
84
- const rolloutAsNumber = parseFloat(rollout);
85
- yield app_bundles_1.default.update({
82
+ await appBundlesService.update({
86
83
  appId,
87
84
  appBundleId: bundleId,
88
85
  maxAndroidAppVersionCode: androidMax,
89
86
  maxIosAppVersionCode: iosMax,
90
87
  minAndroidAppVersionCode: androidMin,
91
88
  minIosAppVersionCode: iosMin,
92
- rolloutPercentage: rolloutAsNumber,
89
+ rolloutPercentage: rollout,
93
90
  });
94
- consola_1.default.success('Bundle updated successfully.');
91
+ consola.success('Bundle updated successfully.');
95
92
  }
96
93
  catch (error) {
97
- const message = (0, error_1.getMessageFromUnknownError)(error);
98
- consola_1.default.error(message);
94
+ const message = getMessageFromUnknownError(error);
95
+ consola.error(message);
99
96
  process.exit(1);
100
97
  }
101
- }),
98
+ },
102
99
  });
@@ -0,0 +1,142 @@
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/userConfig.js';
5
+ import consola from 'consola';
6
+ import nock from 'nock';
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import updateBundleCommand from './update.js';
9
+ // Mock dependencies
10
+ vi.mock('@/utils/userConfig.js');
11
+ vi.mock('@/utils/prompt.js');
12
+ vi.mock('@/services/authorization-service.js');
13
+ vi.mock('consola');
14
+ describe('apps-bundles-update', () => {
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.hasAuthorizationToken.mockReturnValue(true);
23
+ mockAuthorizationService.getCurrentAuthorizationToken.mockReturnValue('test-token');
24
+ vi.spyOn(process, 'exit').mockImplementation(() => undefined);
25
+ });
26
+ afterEach(() => {
27
+ nock.cleanAll();
28
+ vi.restoreAllMocks();
29
+ });
30
+ it('should require authentication', async () => {
31
+ const appId = 'app-123';
32
+ const bundleId = 'bundle-456';
33
+ const options = { appId, bundleId };
34
+ mockAuthorizationService.hasAuthorizationToken.mockReturnValue(false);
35
+ await updateBundleCommand.action(options, undefined);
36
+ expect(mockConsola.error).toHaveBeenCalledWith('You must be logged in to run this command.');
37
+ expect(process.exit).toHaveBeenCalledWith(1);
38
+ });
39
+ it('should update bundle with provided options', async () => {
40
+ const appId = 'app-123';
41
+ const bundleId = 'bundle-456';
42
+ const rollout = 0.5;
43
+ const androidMax = '1000';
44
+ const iosMin = '2.0.0';
45
+ const testToken = 'test-token';
46
+ const options = { appId, bundleId, rollout, androidMax, iosMin };
47
+ const scope = nock(DEFAULT_API_BASE_URL)
48
+ .patch(`/v1/apps/${appId}/bundles/${bundleId}`, {
49
+ appId,
50
+ appBundleId: bundleId,
51
+ maxAndroidAppVersionCode: androidMax,
52
+ maxIosAppVersionCode: undefined,
53
+ minAndroidAppVersionCode: undefined,
54
+ minIosAppVersionCode: iosMin,
55
+ rolloutPercentage: rollout,
56
+ })
57
+ .matchHeader('Authorization', `Bearer ${testToken}`)
58
+ .reply(200, { id: bundleId });
59
+ await updateBundleCommand.action(options, undefined);
60
+ expect(scope.isDone()).toBe(true);
61
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle updated successfully.');
62
+ });
63
+ it('should prompt for app selection when appId not provided', async () => {
64
+ const orgId = 'org-1';
65
+ const appId = 'app-1';
66
+ const bundleId = 'bundle-456';
67
+ const testToken = 'test-token';
68
+ const organization = { id: orgId, name: 'Org 1' };
69
+ const app = { id: appId, name: 'App 1' };
70
+ const options = { bundleId, rollout: 1 };
71
+ const orgsScope = nock(DEFAULT_API_BASE_URL)
72
+ .get('/v1/organizations')
73
+ .matchHeader('Authorization', `Bearer ${testToken}`)
74
+ .reply(200, [organization]);
75
+ const appsScope = nock(DEFAULT_API_BASE_URL)
76
+ .get('/v1/apps')
77
+ .query({ organizationId: orgId })
78
+ .matchHeader('Authorization', `Bearer ${testToken}`)
79
+ .reply(200, [app]);
80
+ const updateScope = nock(DEFAULT_API_BASE_URL)
81
+ .patch(`/v1/apps/${appId}/bundles/${bundleId}`)
82
+ .matchHeader('Authorization', `Bearer ${testToken}`)
83
+ .reply(200, { id: bundleId });
84
+ mockPrompt
85
+ .mockResolvedValueOnce(orgId) // organization selection
86
+ .mockResolvedValueOnce(appId); // app selection
87
+ await updateBundleCommand.action(options, undefined);
88
+ expect(orgsScope.isDone()).toBe(true);
89
+ expect(appsScope.isDone()).toBe(true);
90
+ expect(updateScope.isDone()).toBe(true);
91
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle updated successfully.');
92
+ });
93
+ it('should prompt for bundleId when not provided', async () => {
94
+ const appId = 'app-123';
95
+ const bundleId = 'bundle-456';
96
+ const testToken = 'test-token';
97
+ const options = { appId };
98
+ const scope = nock(DEFAULT_API_BASE_URL)
99
+ .patch(`/v1/apps/${appId}/bundles/${bundleId}`)
100
+ .matchHeader('Authorization', `Bearer ${testToken}`)
101
+ .reply(200, { id: bundleId });
102
+ mockPrompt.mockResolvedValueOnce(bundleId); // bundle ID input
103
+ await updateBundleCommand.action(options, undefined);
104
+ expect(scope.isDone()).toBe(true);
105
+ expect(mockPrompt).toHaveBeenCalledWith('Enter the bundle ID:', { type: 'text' });
106
+ expect(mockConsola.success).toHaveBeenCalledWith('Bundle updated successfully.');
107
+ });
108
+ it('should handle API error during update', async () => {
109
+ const appId = 'app-123';
110
+ const bundleId = 'bundle-456';
111
+ const testToken = 'test-token';
112
+ const options = { appId, bundleId };
113
+ const scope = nock(DEFAULT_API_BASE_URL)
114
+ .patch(`/v1/apps/${appId}/bundles/${bundleId}`)
115
+ .matchHeader('Authorization', `Bearer ${testToken}`)
116
+ .reply(404, { message: 'Bundle not found' });
117
+ await updateBundleCommand.action(options, undefined);
118
+ expect(scope.isDone()).toBe(true);
119
+ expect(mockConsola.error).toHaveBeenCalled();
120
+ expect(process.exit).toHaveBeenCalledWith(1);
121
+ });
122
+ it('should handle error when no organizations exist', async () => {
123
+ const testToken = 'test-token';
124
+ const options = {};
125
+ const scope = nock(DEFAULT_API_BASE_URL)
126
+ .get('/v1/organizations')
127
+ .matchHeader('Authorization', `Bearer ${testToken}`)
128
+ .reply(200, []);
129
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((code) => {
130
+ throw new Error(`process.exit called with code ${code}`);
131
+ });
132
+ try {
133
+ await updateBundleCommand.action(options, undefined);
134
+ }
135
+ catch (error) {
136
+ expect(error.message).toBe('process.exit called with code 1');
137
+ }
138
+ expect(scope.isDone()).toBe(true);
139
+ expect(mockConsola.error).toHaveBeenCalledWith('You must create an organization before updating a bundle.');
140
+ expect(exitSpy).toHaveBeenCalledWith(1);
141
+ });
142
+ });
@@ -1,93 +1,70 @@
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_channels_1 = __importDefault(require("../../../services/app-channels"));
18
- const apps_1 = __importDefault(require("../../../services/apps"));
19
- const error_1 = require("../../../utils/error");
20
- const prompt_1 = require("../../../utils/prompt");
21
- exports.default = (0, citty_1.defineCommand)({
22
- meta: {
23
- description: 'Create a new app channel.',
24
- },
25
- args: {
26
- appId: {
27
- type: 'string',
28
- description: 'ID of the app.',
29
- },
30
- bundleLimit: {
31
- type: 'string',
32
- description: 'Maximum number of bundles that can be assigned to the channel. If more bundles are assigned, the oldest bundles will be automatically deleted.',
33
- },
34
- ignoreErrors: {
35
- type: 'boolean',
36
- description: 'Whether to ignore errors or not.',
37
- },
38
- name: {
39
- type: 'string',
40
- description: 'Name of the channel.',
41
- },
42
- },
43
- run: (ctx) => __awaiter(void 0, void 0, void 0, function* () {
44
- let appId = ctx.args.appId;
45
- let bundleLimitAsString = ctx.args.bundleLimit;
46
- let ignoreErrors = ctx.args.ignoreErrors;
47
- let name = ctx.args.name;
48
- // Convert ignoreErrors to boolean
49
- if (typeof ignoreErrors === 'string') {
50
- ignoreErrors = ignoreErrors.toLowerCase() === 'true';
51
- }
1
+ import { defineCommand, defineOptions } from '@robingenz/zli';
2
+ import consola from 'consola';
3
+ import { z } from 'zod';
4
+ import appChannelsService from '../../../services/app-channels.js';
5
+ import appsService from '../../../services/apps.js';
6
+ import organizationsService from '../../../services/organizations.js';
7
+ import { getMessageFromUnknownError } from '../../../utils/error.js';
8
+ import { prompt } from '../../../utils/prompt.js';
9
+ export default defineCommand({
10
+ description: 'Create a new app channel.',
11
+ options: defineOptions(z.object({
12
+ appId: z.string().optional().describe('ID of the app.'),
13
+ bundleLimit: z.coerce
14
+ .number()
15
+ .optional()
16
+ .describe('Maximum number of bundles that can be assigned to the channel. If more bundles are assigned, the oldest bundles will be automatically deleted.'),
17
+ ignoreErrors: z.boolean().optional().describe('Whether to ignore errors or not.'),
18
+ name: z.string().optional().describe('Name of the channel.'),
19
+ })),
20
+ action: async (options, args) => {
21
+ let { appId, bundleLimit, ignoreErrors, name } = options;
52
22
  // Validate the app ID
53
23
  if (!appId) {
54
- const apps = yield apps_1.default.findAll();
55
- if (!apps.length) {
56
- consola_1.default.error('You must create an app before creating a channel.');
24
+ const organizations = await organizationsService.findAll();
25
+ if (organizations.length === 0) {
26
+ consola.error('You must create an organization before creating a channel.');
57
27
  process.exit(1);
58
28
  }
59
29
  // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
60
- appId = yield (0, prompt_1.prompt)('Which app do you want to create the channel for?', {
30
+ const organizationId = await prompt('Select the organization of the app for which you want to create a channel.', {
61
31
  type: 'select',
62
- options: apps.map((app) => ({ label: app.name, value: app.id })),
32
+ options: organizations.map((organization) => ({ label: organization.name, value: organization.id })),
63
33
  });
64
- }
65
- // Validate the bundle limit
66
- let bundleLimit;
67
- if (bundleLimitAsString) {
68
- bundleLimit = parseInt(bundleLimitAsString, 10);
69
- if (isNaN(bundleLimit)) {
70
- consola_1.default.error('The bundle limit must be a number.');
34
+ if (!organizationId) {
35
+ consola.error('You must select the organization of an app for which you want to create a channel.');
71
36
  process.exit(1);
72
37
  }
38
+ const apps = await appsService.findAll({
39
+ organizationId,
40
+ });
41
+ if (!apps.length) {
42
+ consola.error('You must create an app before creating a channel.');
43
+ process.exit(1);
44
+ }
45
+ // @ts-ignore wait till https://github.com/unjs/consola/pull/280 is merged
46
+ appId = await prompt('Which app do you want to create the channel for?', {
47
+ type: 'select',
48
+ options: apps.map((app) => ({ label: app.name, value: app.id })),
49
+ });
73
50
  }
74
51
  // Validate the channel name
75
52
  if (!name) {
76
- name = yield (0, prompt_1.prompt)('Enter the name of the channel:', { type: 'text' });
53
+ name = await prompt('Enter the name of the channel:', { type: 'text' });
77
54
  }
78
55
  try {
79
- const response = yield app_channels_1.default.create({
56
+ const response = await appChannelsService.create({
80
57
  appId,
81
58
  name,
82
59
  totalAppBundleLimit: bundleLimit,
83
60
  });
84
- consola_1.default.success('Channel created successfully.');
85
- consola_1.default.info(`Channel ID: ${response.id}`);
61
+ consola.success('Channel created successfully.');
62
+ consola.info(`Channel ID: ${response.id}`);
86
63
  }
87
64
  catch (error) {
88
- const message = (0, error_1.getMessageFromUnknownError)(error);
89
- consola_1.default.error(message);
65
+ const message = getMessageFromUnknownError(error);
66
+ consola.error(message);
90
67
  process.exit(ignoreErrors ? 0 : 1);
91
68
  }
92
- }),
69
+ },
93
70
  });
@@ -0,0 +1,115 @@
1
+ import { DEFAULT_API_BASE_URL } from '../../../config/consts.js';
2
+ import { prompt } from '../../../utils/prompt.js';
3
+ import userConfig from '../../../utils/userConfig.js';
4
+ import consola from 'consola';
5
+ import nock from 'nock';
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
7
+ import createChannelCommand from './create.js';
8
+ // Mock dependencies
9
+ vi.mock('@/utils/userConfig.js');
10
+ vi.mock('@/utils/prompt.js');
11
+ vi.mock('consola');
12
+ describe('apps-channels-create', () => {
13
+ const mockUserConfig = vi.mocked(userConfig);
14
+ const mockPrompt = vi.mocked(prompt);
15
+ const mockConsola = vi.mocked(consola);
16
+ beforeEach(() => {
17
+ vi.clearAllMocks();
18
+ mockUserConfig.read.mockReturnValue({ token: 'test-token' });
19
+ vi.spyOn(process, 'exit').mockImplementation(() => undefined);
20
+ });
21
+ afterEach(() => {
22
+ nock.cleanAll();
23
+ vi.restoreAllMocks();
24
+ });
25
+ it('should create channel with provided options', async () => {
26
+ const appId = 'app-123';
27
+ const channelName = 'production';
28
+ const bundleLimit = 5;
29
+ const channelId = 'channel-456';
30
+ const testToken = 'test-token';
31
+ const options = { appId, name: channelName, bundleLimit };
32
+ const scope = nock(DEFAULT_API_BASE_URL)
33
+ .post(`/v1/apps/${appId}/channels`, {
34
+ appId,
35
+ name: channelName,
36
+ totalAppBundleLimit: bundleLimit,
37
+ })
38
+ .matchHeader('Authorization', `Bearer ${testToken}`)
39
+ .reply(201, { id: channelId, name: channelName });
40
+ await createChannelCommand.action(options, undefined);
41
+ expect(scope.isDone()).toBe(true);
42
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel created successfully.');
43
+ expect(mockConsola.info).toHaveBeenCalledWith(`Channel ID: ${channelId}`);
44
+ });
45
+ it('should prompt for app when not provided', async () => {
46
+ const channelName = 'staging';
47
+ const orgId = 'org-1';
48
+ const appId = 'app-1';
49
+ const channelId = 'channel-456';
50
+ const testToken = 'test-token';
51
+ const options = { name: channelName };
52
+ const orgsScope = nock(DEFAULT_API_BASE_URL)
53
+ .get('/v1/organizations')
54
+ .matchHeader('Authorization', `Bearer ${testToken}`)
55
+ .reply(200, [{ id: orgId, name: 'Org 1' }]);
56
+ const appsScope = nock(DEFAULT_API_BASE_URL)
57
+ .get('/v1/apps')
58
+ .query({ organizationId: orgId })
59
+ .matchHeader('Authorization', `Bearer ${testToken}`)
60
+ .reply(200, [{ id: appId, name: 'App 1' }]);
61
+ const createScope = nock(DEFAULT_API_BASE_URL)
62
+ .post(`/v1/apps/${appId}/channels`, {
63
+ appId,
64
+ name: channelName,
65
+ totalAppBundleLimit: undefined,
66
+ })
67
+ .matchHeader('Authorization', `Bearer ${testToken}`)
68
+ .reply(201, { id: channelId, name: channelName });
69
+ mockPrompt
70
+ .mockResolvedValueOnce(orgId) // organization selection
71
+ .mockResolvedValueOnce(appId); // app selection
72
+ await createChannelCommand.action(options, undefined);
73
+ expect(orgsScope.isDone()).toBe(true);
74
+ expect(appsScope.isDone()).toBe(true);
75
+ expect(createScope.isDone()).toBe(true);
76
+ expect(mockConsola.success).toHaveBeenCalledWith('Channel created successfully.');
77
+ });
78
+ it('should prompt for channel name when not provided', async () => {
79
+ const options = { appId: 'app-123' };
80
+ const scope = nock(DEFAULT_API_BASE_URL)
81
+ .post('/v1/apps/app-123/channels', {
82
+ appId: 'app-123',
83
+ name: 'development',
84
+ totalAppBundleLimit: undefined,
85
+ })
86
+ .matchHeader('Authorization', 'Bearer test-token')
87
+ .reply(201, { id: 'channel-456', name: 'development' });
88
+ mockPrompt.mockResolvedValueOnce('development');
89
+ await createChannelCommand.action(options, undefined);
90
+ expect(scope.isDone()).toBe(true);
91
+ expect(mockPrompt).toHaveBeenCalledWith('Enter the name of the channel:', { type: 'text' });
92
+ });
93
+ it('should handle error with ignoreErrors flag', async () => {
94
+ const options = { appId: 'app-123', name: 'production', ignoreErrors: true };
95
+ const scope = nock(DEFAULT_API_BASE_URL)
96
+ .post('/v1/apps/app-123/channels')
97
+ .matchHeader('Authorization', 'Bearer test-token')
98
+ .reply(400, { message: 'Channel name already exists' });
99
+ await createChannelCommand.action(options, undefined);
100
+ expect(scope.isDone()).toBe(true);
101
+ expect(mockConsola.error).toHaveBeenCalled();
102
+ expect(process.exit).toHaveBeenCalledWith(0);
103
+ });
104
+ it('should handle error without ignoreErrors flag', async () => {
105
+ const options = { appId: 'app-123', name: 'production' };
106
+ const scope = nock(DEFAULT_API_BASE_URL)
107
+ .post('/v1/apps/app-123/channels')
108
+ .matchHeader('Authorization', 'Bearer test-token')
109
+ .reply(400, { message: 'Channel name already exists' });
110
+ await createChannelCommand.action(options, undefined);
111
+ expect(scope.isDone()).toBe(true);
112
+ expect(mockConsola.error).toHaveBeenCalled();
113
+ expect(process.exit).toHaveBeenCalledWith(1);
114
+ });
115
+ });