@squiz/dxp-cli-next 5.22.0 → 5.22.1-develop.2

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,3 @@
1
+ import { Command } from 'commander';
2
+ declare const loginCommand: Command;
3
+ export default loginCommand;
@@ -0,0 +1,237 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const cli_color_1 = __importDefault(require("cli-color"));
39
+ const commander_1 = require("commander");
40
+ const ApiService_1 = require("../ApiService");
41
+ const ApplicationStore_1 = require("../ApplicationStore");
42
+ const prompt_1 = __importDefault(require("prompt"));
43
+ const PRODUCTION_URL = 'https://dxp.squiz.cloud';
44
+ const loginCommand = new commander_1.Command('login')
45
+ .name('login')
46
+ .description('Login to the DXP platform')
47
+ .addOption(new commander_1.Option('--username <username>', 'Optionally provide username through CLI, or environment variable. If this option is omitted you will be prompted for input in interactive mode').env('DXP_USERNAME'))
48
+ .addOption(new commander_1.Option('--password <password>', 'Optionally provide password through CLI, or environment variable. If this option is omitted you will be prompted for input in interactive mode').env('DXP_PASSWORD'))
49
+ .addOption(new commander_1.Option('--dxp-base-url <baseURL>', 'dxp cloud base url e.g. "https://develop-apps-dxp-console.dev.dxp.squiz.cloud/"')
50
+ .env('DXP_BASE_URL')
51
+ .default(PRODUCTION_URL))
52
+ .addOption(new commander_1.Option('--region <region>').choices(['au']).default('au'))
53
+ .addOption(new commander_1.Option('--tenant <tenantID>'))
54
+ .configureOutput({
55
+ outputError(str, write) {
56
+ write(cli_color_1.default.red(str));
57
+ },
58
+ })
59
+ .action((options) => __awaiter(void 0, void 0, void 0, function* () {
60
+ try {
61
+ const credentials = yield getLoginCredentials(options.username, options.password);
62
+ if (credentials == false) {
63
+ console.log(''); // needed to not screw up line endings in terminal
64
+ return;
65
+ }
66
+ yield handleLoginRequest(credentials, options);
67
+ const availableTenants = yield handleGetTenantsRequest(options);
68
+ if (options.tenant == undefined) {
69
+ const selectedTenant = yield promptForTenant(availableTenants);
70
+ options.tenant = selectedTenant;
71
+ }
72
+ else {
73
+ validateTenant(options.tenant, availableTenants);
74
+ }
75
+ return yield writeTenantToSessionConfig(options);
76
+ }
77
+ catch (error) {
78
+ if (!!process.env.DEBUG && error.stack) {
79
+ loginCommand.error(error.stack);
80
+ }
81
+ if (error.message) {
82
+ loginCommand.error(cli_color_1.default.red(error.message));
83
+ }
84
+ else {
85
+ loginCommand.error(cli_color_1.default.red('An unknown error occurred'));
86
+ }
87
+ }
88
+ }));
89
+ function getLoginCredentials(optionalUsername, optionalPassword) {
90
+ return __awaiter(this, void 0, void 0, function* () {
91
+ const prompts = [];
92
+ let username = '';
93
+ let password = '';
94
+ if (!optionalUsername) {
95
+ prompts.push({
96
+ name: 'username',
97
+ description: 'Username: ',
98
+ required: true,
99
+ });
100
+ }
101
+ else {
102
+ username = optionalUsername;
103
+ }
104
+ if (!optionalPassword) {
105
+ prompts.push({
106
+ name: 'password',
107
+ description: 'Password: ',
108
+ hidden: true,
109
+ replace: '*',
110
+ required: true,
111
+ });
112
+ }
113
+ else {
114
+ password = optionalPassword;
115
+ }
116
+ let result;
117
+ try {
118
+ prompt_1.default.start({ message: ' ', delimiter: ' ' });
119
+ result = yield prompt_1.default.get(prompts);
120
+ }
121
+ catch (e) {
122
+ if (e instanceof Error && e.message === 'canceled') {
123
+ return false;
124
+ }
125
+ else {
126
+ throw e;
127
+ }
128
+ }
129
+ if (result.username)
130
+ username = result.username;
131
+ if (result.password)
132
+ password = result.password;
133
+ return { username, password };
134
+ });
135
+ }
136
+ function handleLoginRequest(login, options) {
137
+ return __awaiter(this, void 0, void 0, function* () {
138
+ const apiService = new ApiService_1.ApiService();
139
+ // Just need to make sure no extra slash at the end
140
+ const baseUrl = options.dxpBaseUrl.replace(/\/$/, '');
141
+ const loginUrl = `${baseUrl}/__dxp/${options.region}/dxp/access/login`;
142
+ const loginString = Buffer.from(JSON.stringify(login)).toString('base64');
143
+ const loginResponse = yield apiService.client.post(loginUrl, {
144
+ token: loginString,
145
+ });
146
+ switch (loginResponse.status) {
147
+ case 204:
148
+ console.log('Login successful');
149
+ yield (0, ApplicationStore_1.saveApplicationFile)(ApplicationStore_1.STORE_FILES.sessionConfig, JSON.stringify({
150
+ baseUrl,
151
+ region: options.region,
152
+ }));
153
+ return;
154
+ default:
155
+ throw new Error(`An error occurred during login ${loginResponse.data.message ? `"${loginResponse.data.message}"` : ''} (code: ${loginResponse.status})`.trim());
156
+ }
157
+ });
158
+ }
159
+ function handleGetTenantsRequest(options) {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ const apiService = new ApiService_1.ApiService();
162
+ const baseUrl = options.dxpBaseUrl.replace(/\/$/, '');
163
+ const tenantsUrl = `${baseUrl}/__dxp/${options.region}/dxp/access/tenants`;
164
+ const tenantsResponse = yield apiService.client.get(tenantsUrl);
165
+ switch (tenantsResponse.status) {
166
+ case 200:
167
+ return tenantsResponse.data;
168
+ default:
169
+ throw new Error(`An error occurred fetching tenants ${tenantsResponse.data.message
170
+ ? `"${tenantsResponse.data.message}"`
171
+ : ''} (code: ${tenantsResponse.status})`.trim());
172
+ }
173
+ });
174
+ }
175
+ function promptForTenant(tenants) {
176
+ return __awaiter(this, void 0, void 0, function* () {
177
+ //Our tsconfig module is commonjs so we need to use require here and only version ^8.0.0 of inquirer as latest is default esm
178
+ const inquirer = yield Promise.resolve().then(() => __importStar(require('inquirer')));
179
+ const tenantChoices = formatTenantResponseForInquirer(tenants);
180
+ const selectedTenant = yield inquirer.default.prompt([
181
+ {
182
+ type: 'list',
183
+ name: 'selectedTenantId',
184
+ message: 'Select a tenant: ',
185
+ choices: tenantChoices,
186
+ },
187
+ ]);
188
+ //return the tenant ID
189
+ return selectedTenant.selectedTenantId;
190
+ });
191
+ }
192
+ function formatTenantResponseForInquirer(tenants) {
193
+ return tenants.organisations.map(tenant => {
194
+ return {
195
+ name: `${tenant.name} : (${tenant.id})`,
196
+ value: tenant.id,
197
+ };
198
+ });
199
+ }
200
+ function validateTenant(tenant, tenants) {
201
+ if (tenants.organisations.some(t => t.id === tenant)) {
202
+ return true;
203
+ }
204
+ else {
205
+ let tenantListErrorString = undefined;
206
+ if (tenants.organisations.length > 5) {
207
+ const initialTenants = tenants.organisations.slice(0, 5).map(t => t.name);
208
+ tenantListErrorString = `${initialTenants} ... and ${tenants.organisations.length - 5} more}`;
209
+ }
210
+ else {
211
+ tenantListErrorString = tenants.organisations.map(t => t.name).join(', ');
212
+ }
213
+ throw new Error(`
214
+ The tenant ID you provided : ${tenant} does not correspond to a tenant that you have access to.\n
215
+ Please ensure that you are using the correct ID and that you have the appropriate permissions to access this tenant.
216
+ Here is a list of the tenants you have access to: ${tenantListErrorString || 'None'}
217
+ `);
218
+ }
219
+ }
220
+ function writeTenantToSessionConfig(options) {
221
+ return __awaiter(this, void 0, void 0, function* () {
222
+ const baseUrl = options.dxpBaseUrl.replace(/\/$/, '');
223
+ try {
224
+ yield (0, ApplicationStore_1.saveApplicationFile)(ApplicationStore_1.STORE_FILES.sessionConfig, JSON.stringify({
225
+ baseUrl,
226
+ tenant: options.tenant,
227
+ region: options.region,
228
+ }));
229
+ console.log('Tenant saved to session');
230
+ return;
231
+ }
232
+ catch (error) {
233
+ throw new Error(`An error occurred during saving of tenant: ${error}`);
234
+ }
235
+ });
236
+ }
237
+ exports.default = loginCommand;
@@ -0,0 +1,3 @@
1
+ import { Command } from 'commander';
2
+ declare const initCommand: Command;
3
+ export default initCommand;
@@ -0,0 +1,52 @@
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 commander_1 = require("commander");
16
+ const cli_color_1 = __importDefault(require("cli-color"));
17
+ const component_cli_lib_1 = require("@squiz/component-cli-lib");
18
+ var componentTypes;
19
+ (function (componentTypes) {
20
+ componentTypes["basic"] = "basic";
21
+ componentTypes["advanced"] = "advanced";
22
+ })(componentTypes || (componentTypes = {}));
23
+ const initCommand = new commander_1.Command('init')
24
+ .name('init')
25
+ .addOption(new commander_1.Option('-t, --type <string>', 'Type of component to create. Must be one of: basic, advanced (default: basic)')
26
+ .choices(['basic', 'advanced'])
27
+ .default('basic'))
28
+ .addOption(new commander_1.Option('-d, --destination <string>', 'Destination folder to create the component in (default: current directory)'))
29
+ .action(({ type: componentType, destination }) => __awaiter(void 0, void 0, void 0, function* () {
30
+ if (componentType !== 'basic' && componentType !== 'advanced') {
31
+ initCommand.error(cli_color_1.default.red('Invalid component type. Must be one of: basic, advanced'));
32
+ }
33
+ if (!destination) {
34
+ destination = '.';
35
+ }
36
+ console.log(`Creating ${componentType} component in current directory`);
37
+ try {
38
+ yield (0, component_cli_lib_1.componentInit)({ componentType, destination });
39
+ }
40
+ catch (error) {
41
+ if (!!process.env.DEBUG && error.stack) {
42
+ initCommand.error(error.stack);
43
+ }
44
+ if (error.message) {
45
+ initCommand.error(cli_color_1.default.red(error.message));
46
+ }
47
+ else {
48
+ initCommand.error(cli_color_1.default.red('An unknown error occurred'));
49
+ }
50
+ }
51
+ }));
52
+ exports.default = initCommand;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squiz/dxp-cli-next",
3
- "version": "5.22.0",
3
+ "version": "5.22.1-develop.2",
4
4
  "repository": {
5
5
  "url": "https://gitlab.squiz.net/dxp/dxp-cli-next"
6
6
  },
@@ -41,7 +41,7 @@
41
41
  ],
42
42
  "dependencies": {
43
43
  "@apidevtools/swagger-parser": "10.1.0",
44
- "@squiz/component-cli-lib": "~1.70.3",
44
+ "@squiz/component-cli-lib": "~1.71.1",
45
45
  "@squiz/dxp-porter-shared": "0.4.0",
46
46
  "@squiz/local-component-dev-ui": "^0.6.1",
47
47
  "axios": "1.1.3",