zcatalyst-cli 1.18.0-beta.5 → 1.18.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ [ZEST-GEN-1]
2
+ context = '''Oops! It's looks like you haven't created any specification.'''
3
+ aid = '''Please visit the below link to add a zest specifications.'''
4
+ link = 'https://docs-ea.catalyst.localzoho.com/en/zest/help/introduction/'
@@ -33,11 +33,15 @@ const logger_1 = require("../util_modules/logger");
33
33
  const option_1 = require("../util_modules/option");
34
34
  const crypto_1 = require("crypto");
35
35
  exports.missingScopes = {
36
- [constants_1.DC_TYPE.in.value]: ['dataverse'],
37
- [constants_1.DC_TYPE.eu.value]: ['quick_ml', 'dataverse'],
38
- [constants_1.DC_TYPE.au.value]: ['dataverse'],
39
- [constants_1.DC_TYPE.ca.value]: ['quick_ml', 'dataverse']
36
+ [constants_1.DC_TYPE.in.value]: getScopes(['zest', 'dataverse']),
37
+ [constants_1.DC_TYPE.eu.value]: getScopes(['zest', 'quick_ml', 'dataverse']),
38
+ [constants_1.DC_TYPE.au.value]: getScopes(['zest', 'dataverse']),
39
+ [constants_1.DC_TYPE.ca.value]: getScopes(['zest', 'quick_ml', 'dataverse']),
40
+ [constants_1.DC_TYPE.sa.value]: getScopes(['zest', 'quick_ml', 'dataverse'])
40
41
  };
42
+ function getScopes(keys) {
43
+ return Object.keys(constants_1.SCOPE).filter((scope) => keys.some((prefix) => scope.startsWith(prefix)));
44
+ }
41
45
  class Login {
42
46
  constructor(localhost = true, user = true) {
43
47
  this.localhost = localhost;
package/lib/code-deck.js CHANGED
@@ -20,6 +20,7 @@ const prompt_1 = __importDefault(require("./prompt"));
20
20
  const tree_1 = require("./prompt/types/tree");
21
21
  const runtime_store_1 = __importDefault(require("./runtime-store"));
22
22
  const logger_1 = require("./util_modules/logger");
23
+ const project_1 = require("./util_modules/project");
23
24
  const shell_1 = require("./util_modules/shell");
24
25
  function listenDeploy(id, gitUrl) {
25
26
  return __awaiter(this, void 0, void 0, function* () {
@@ -31,7 +32,7 @@ function listenDeploy(id, gitUrl) {
31
32
  arr.push(allGlobalOpts[key]);
32
33
  }
33
34
  return arr;
34
- }, ['--id', id]);
35
+ }, ['--id', id, '--org', (0, project_1.getEnvId)() || '']);
35
36
  const childRes = yield (0, shell_1.spawn)('catalyst', ['iac:status', 'import', ...optsArr], {
36
37
  shell: true,
37
38
  stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
@@ -50,7 +50,7 @@ exports.default = new command_1.default('appsail:add')
50
50
  const config = runtime_store_1.default.get('config');
51
51
  yield (yield Promise.resolve().then(() => __importStar(require('../../init/features')))).appsail();
52
52
  yield config.save();
53
- (0, logger_1.message)((0, ansi_colors_1.bold)(constants_1.FILENAME.config) + ' file has been successfully updated with functions details.');
53
+ (0, logger_1.message)((0, ansi_colors_1.bold)(constants_1.FILENAME.config) + ' file has been successfully updated with appsail details.');
54
54
  (0, logger_1.info)();
55
55
  (0, logger_1.success)('AppSail service successfully linked');
56
56
  }));
@@ -73,7 +73,11 @@ exports.default = new command_1.default('iac:export')
73
73
  arr.push(allGlobalOpts[key]);
74
74
  }
75
75
  return arr;
76
- }, (env === 'Production' ? ['--production'] : []));
76
+ }, [
77
+ '--org',
78
+ (0, project_1.getEnvId)(),
79
+ ...(env === 'Production' ? ['--production'] : [])
80
+ ]);
77
81
  (0, shell_1.spawn)('catalyst', ['iac:status', 'export', ...optsArr], {
78
82
  shell: true,
79
83
  stdio: 'inherit'
@@ -58,6 +58,7 @@ const logger_1 = require("../../util_modules/logger");
58
58
  const option_1 = require("../../util_modules/option");
59
59
  const shell_1 = require("../../util_modules/shell");
60
60
  const server_js_1 = require("../../util_modules/server.js");
61
+ const project_1 = require("../../util_modules/project");
61
62
  const getZipAndTemplate = (filePath, stagedDeploy) => __awaiter(void 0, void 0, void 0, function* () {
62
63
  const zipFile = filePath
63
64
  ? yield ASYNC.readFile((0, utils_js_1.untildify)(filePath), 'buffer')
@@ -84,6 +85,8 @@ const ensureUserAction = (deployRes) => __awaiter(void 0, void 0, void 0, functi
84
85
  const callbackPort = yield port_resolver_1.default.getFreePort(3000, 10, false);
85
86
  const accessUrl = new url_1.URL(`/baas/v1/project/import/${deployRes.id}/deploy`, `${constants_1.ORIGIN.admin}`);
86
87
  accessUrl.searchParams.set('redirect_url', `http://localhost:${callbackPort}/success`);
88
+ const orgId = (0, project_1.getEnvId)();
89
+ orgId && accessUrl.searchParams.set('catalyst_org', orgId);
87
90
  const server = (0, http_1.createServer)((req, resp) => __awaiter(void 0, void 0, void 0, function* () {
88
91
  try {
89
92
  if (req.url !== '/success') {
@@ -136,7 +139,7 @@ const ensureUserAction = (deployRes) => __awaiter(void 0, void 0, void 0, functi
136
139
  arr.push(allGlobalOpts[key]);
137
140
  }
138
141
  return arr;
139
- }, ['--id', deployRes.id]);
142
+ }, ['--id', deployRes.id, '--org', (0, project_1.getEnvId)() || '']);
140
143
  yield (0, shell_1.spawn)('catalyst', ['iac:status', 'import', ...optsArr], {
141
144
  shell: true,
142
145
  stdio: 'inherit'
@@ -80,6 +80,7 @@ exports.default = (client) => {
80
80
  loadCommand('codelib:install'),
81
81
  loadCommand('event:generate'),
82
82
  loadCommand('event:generate:integ'),
83
+ loadCommand('zest:generate'),
83
84
  loadCommand('event:generate:job'),
84
85
  loadCommand('serve'),
85
86
  loadCommand('deploy'),
@@ -0,0 +1,304 @@
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 command_1 = __importDefault(require("../../../internal/command"));
39
+ const constants_1 = require("../../../util_modules/constants");
40
+ const prompt_1 = __importDefault(require("../../../prompt"));
41
+ const js_1 = require("../../../util_modules/js");
42
+ const endpoints_1 = require("../../../endpoints");
43
+ const runtime_store_1 = __importDefault(require("../../../runtime-store"));
44
+ const archiver_1 = __importDefault(require("../../../archiver"));
45
+ const logger_1 = require("../../../util_modules/logger");
46
+ const inquirer_1 = __importStar(require("inquirer"));
47
+ const error_1 = __importDefault(require("../../../error"));
48
+ const project_1 = require("../../../util_modules/project");
49
+ const features_1 = require("../../../init/features");
50
+ const path_1 = require("path");
51
+ const throbber_1 = __importDefault(require("../../../throbber"));
52
+ const config_1 = require("../../../util_modules/config");
53
+ const common_1 = require("../../../init/util/common");
54
+ const ansi_colors_1 = require("ansi-colors");
55
+ const fs_1 = require("../../../util_modules/fs");
56
+ const console_1 = require("console");
57
+ function getSpecification(specs = []) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ const res = (yield (yield (0, endpoints_1.zestAPI)()).getSpecifications());
60
+ if (!res) {
61
+ return specs;
62
+ }
63
+ specs.push(...res.specifications);
64
+ if (res.info.more_records) {
65
+ yield getSpecification(specs);
66
+ }
67
+ return specs;
68
+ });
69
+ }
70
+ function searchSpecification(filter, specArray = []) {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ if (filter) {
73
+ const response = [];
74
+ specArray.forEach((spec) => {
75
+ if (spec.name.includes(filter)) {
76
+ response.push(spec);
77
+ }
78
+ });
79
+ return response;
80
+ }
81
+ return specArray;
82
+ });
83
+ }
84
+ function pollScheduledJob(job_id) {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ const throbber = throbber_1.default.getInstance();
87
+ try {
88
+ const res = (yield (yield (0, endpoints_1.zestAPI)()).getScheduledJob(job_id));
89
+ const status = js_1.JS.capitalize(res.scheduled_jobs[0].status);
90
+ if (status === 'Completed') {
91
+ throbber.succeed('processing', { text: `Status >> ${status}` });
92
+ return res;
93
+ }
94
+ throbber.add('processing', { text: `Status >> ${status}` });
95
+ if (status === 'Failed') {
96
+ throbber.fail('processing', { text: `Status >> ${status}` });
97
+ throw new error_1.default('zest generation failed', {
98
+ exit: 2,
99
+ original: `${res.scheduled_jobs[0].action_info.failure_reason}`
100
+ });
101
+ }
102
+ yield js_1.JS.sleep(1000);
103
+ }
104
+ catch (err) {
105
+ throw new error_1.default('Error while processing scheduled job', {
106
+ exit: 2,
107
+ original: err
108
+ });
109
+ }
110
+ return yield pollScheduledJob(job_id);
111
+ });
112
+ }
113
+ function downloadSourceCode(fileId, outputDir, srcType, srcName) {
114
+ return __awaiter(this, void 0, void 0, function* () {
115
+ const zestZip = (yield (yield (0, endpoints_1.zestAPI)()).getFile(fileId, srcType, srcName));
116
+ yield new archiver_1.default().load(zestZip).extract(outputDir).finalize();
117
+ });
118
+ }
119
+ exports.default = new command_1.default('zest:generate')
120
+ .description('Generate the functions or appsail source code for your ZEST Specifications')
121
+ .needs('auth', [
122
+ constants_1.SCOPE.zest_spec_all,
123
+ constants_1.SCOPE.zest_schedule_job_read,
124
+ constants_1.SCOPE.zest_spec_all,
125
+ constants_1.SCOPE.zest_spec_src_action
126
+ ])
127
+ .needs('config', { optional: true })
128
+ .needs('rc', { skipOrgCheck: false })
129
+ .action(() => __awaiter(void 0, void 0, void 0, function* () {
130
+ var _a;
131
+ const specArray = yield getSpecification();
132
+ if (specArray.length === 0) {
133
+ throw new error_1.default('No Specifications Found', {
134
+ exit: 1,
135
+ errorId: 'ZEST-GEN-1'
136
+ });
137
+ }
138
+ yield prompt_1.default.register('search-box');
139
+ const specName = yield inquirer_1.default.prompt([
140
+ {
141
+ type: 'search-box',
142
+ name: 'specs',
143
+ searchable: true,
144
+ pageSize: 10,
145
+ highlight: true,
146
+ notFoundMsg: 'No specifications found!',
147
+ searchMsg: 'Search specifications...',
148
+ message: 'Please search and select the specifications(Use space key to select)',
149
+ source(_answersSoFar, input) {
150
+ input || (input = '');
151
+ return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
152
+ const fuzzyResult = yield searchSpecification(input, specArray);
153
+ const data = fuzzyResult.map((element) => {
154
+ return {
155
+ name: `${element.name}(${element.version})`,
156
+ value: element.id
157
+ };
158
+ });
159
+ resolve(data);
160
+ }));
161
+ },
162
+ validate: (ansArr) => {
163
+ if (js_1.JS.isEmpty(ansArr)) {
164
+ return 'Must select one specification.';
165
+ }
166
+ return true;
167
+ }
168
+ }
169
+ ]);
170
+ const srcTypeAns = yield prompt_1.default.ask(prompt_1.default.question('source', 'Please specify which source type you want to download', {
171
+ type: 'list',
172
+ choices: [
173
+ prompt_1.default.choice('Function', {
174
+ value: 'functions'
175
+ }),
176
+ prompt_1.default.choice('AppSail', {
177
+ value: 'appsail'
178
+ })
179
+ ]
180
+ }));
181
+ const srcType = srcTypeAns.source;
182
+ const sourceLabel = srcType.replace('functions', 'function');
183
+ const runtimeChoices = yield (0, common_1.getRuntimeChoices)({ fnType: 'aio' });
184
+ const ignoreRuntimes = ['node14', 'node12', 'node20'];
185
+ const stackChoices = runtimeChoices.filter((choice) => {
186
+ if (!(choice instanceof inquirer_1.Separator)) {
187
+ return !ignoreRuntimes.includes(choice.value.runtime);
188
+ }
189
+ return choice;
190
+ });
191
+ const srcStackAns = yield prompt_1.default.ask(prompt_1.default.question('stack', `Please select the language for your ${sourceLabel}`, {
192
+ type: 'list',
193
+ choices: stackChoices.map((choice) => {
194
+ if (!(choice instanceof inquirer_1.Separator)) {
195
+ return choice;
196
+ }
197
+ return choice;
198
+ }),
199
+ when: () => {
200
+ return runtimeChoices.length > 1;
201
+ }
202
+ }));
203
+ const srcStack = srcStackAns.stack.runtime;
204
+ const existingSails = config_1.appSailConfig.raw() || [];
205
+ const existingFuncs = ((_a = config_1.functionsConfig.raw()) === null || _a === void 0 ? void 0 : _a.targets) || [];
206
+ const source = yield prompt_1.default.ask(prompt_1.default.question('name', `Please provide a name for your ${(0, ansi_colors_1.bold)(sourceLabel)} `, {
207
+ type: 'input',
208
+ default: 'sample',
209
+ validate: (input) => __awaiter(void 0, void 0, void 0, function* () {
210
+ if (input === '') {
211
+ return 'Please provide a valid name.';
212
+ }
213
+ if (input === '' || !input.match(constants_1.REGEX.functions.package.name)) {
214
+ return `Special characters are not allowed. Includes only alphabets, numbers, hyphen and underscores.`;
215
+ }
216
+ if (srcType === 'functions' &&
217
+ existingFuncs.findIndex((func) => func === input) !== -1) {
218
+ return 'function name already exists';
219
+ }
220
+ if (srcType === 'appsail' &&
221
+ existingSails.findIndex((appSail) => appSail.name === input) !== -1) {
222
+ return 'appsail name already exists';
223
+ }
224
+ return true;
225
+ })
226
+ }));
227
+ const srcName = source.name;
228
+ let sourceCodeRes;
229
+ const resources = [];
230
+ specName.specs.forEach((element) => {
231
+ resources.push({ id: element });
232
+ });
233
+ const config = runtime_store_1.default.get('config');
234
+ let payload, outputDir;
235
+ if (srcType === 'appsail') {
236
+ const generateAppsailParams = {
237
+ resources: resources,
238
+ stack: srcStack,
239
+ name: srcName
240
+ };
241
+ outputDir = (0, project_1.resolveProjectPath)(`appsail-${srcName}`);
242
+ payload = {
243
+ source: outputDir,
244
+ name: srcName
245
+ };
246
+ if (srcStackAns.stack.lang.startsWith('java')) {
247
+ const basePackage = yield prompt_1.default.ask(prompt_1.default.question('basePkg', 'Please specify the base package name', {
248
+ type: 'input',
249
+ default: 'com.zoho'
250
+ }));
251
+ const install = yield prompt_1.default.ask(prompt_1.default.question('consent', 'Do you wish to install dependencies ? ', {
252
+ type: 'confirm',
253
+ default: true
254
+ }));
255
+ Object.assign(generateAppsailParams, {
256
+ with_dependency: install.consent,
257
+ config: {
258
+ base_package: basePackage.basePkg
259
+ }
260
+ });
261
+ }
262
+ sourceCodeRes = yield (yield (0, endpoints_1.zestAPI)()).generateAppsail(generateAppsailParams);
263
+ }
264
+ else {
265
+ const functionsDirPath = (0, project_1.resolveProjectPath)(config.get('functions.source') || constants_1.FOLDERNAME.functions);
266
+ outputDir = (0, path_1.join)(functionsDirPath, srcName);
267
+ payload = {
268
+ source: outputDir,
269
+ name: srcName,
270
+ stack: srcStack,
271
+ type: 'aio'
272
+ };
273
+ sourceCodeRes = yield (yield (0, endpoints_1.zestAPI)()).generateFunction(resources, srcStack, srcName);
274
+ }
275
+ const folderExists = yield fs_1.ASYNC.dirExists(outputDir);
276
+ const overwriteAns = folderExists
277
+ ? yield prompt_1.default.ask(prompt_1.default.question('overwrite', 'Directory ' + (0, ansi_colors_1.underline)(outputDir) + ' already exists. Overwrite ?', {
278
+ type: 'confirm',
279
+ defaultAns: false
280
+ }))
281
+ : { overwrite: true };
282
+ if (!overwriteAns.overwrite) {
283
+ (0, logger_1.labeled)('zest', `${sourceLabel} generation skipped.`).WARN();
284
+ return;
285
+ }
286
+ yield fs_1.ASYNC.deleteDir(outputDir);
287
+ runtime_store_1.default.set(`payload.${srcType}.targets`, [payload]);
288
+ const job_id = sourceCodeRes.job_id;
289
+ const throbber = throbber_1.default.getInstance();
290
+ (0, console_1.info)('\n' + (0, ansi_colors_1.white)('==> ') + `Generating ${js_1.JS.capitalize(sourceLabel)}`);
291
+ const fileId = yield pollScheduledJob(job_id).then((data) => {
292
+ throbber.remove('processing');
293
+ return data.scheduled_jobs[0].action_info.file_id;
294
+ });
295
+ (0, console_1.info)('\n' + (0, ansi_colors_1.white)('==> ') + `Downloading ${js_1.JS.capitalize(sourceLabel)}`);
296
+ yield downloadSourceCode(fileId, outputDir, sourceLabel, srcName);
297
+ (0, features_1.setCatalystConfig)(srcType, true);
298
+ yield config.save();
299
+ (0, console_1.info)();
300
+ (0, logger_1.message)((0, ansi_colors_1.bold)(constants_1.FILENAME.config) +
301
+ ` file has been successfully updated with ${sourceLabel} details.`);
302
+ (0, console_1.info)();
303
+ (0, logger_1.success)(`Zest successfully generated in ${(0, ansi_colors_1.bold)((0, path_1.join)(outputDir))}.`);
304
+ }));
@@ -32,7 +32,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
32
  });
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.credentialsAPI = exports.tunnelAPI = exports.commonAPI = exports.jobScheduling = exports.codeDeck = exports.gitHubAPI = exports.stratusAPI = exports.appSailAPI = exports.logAPI = exports.eventBusAPI = exports.functionsAPI = exports.applogicAPI = exports.bulkDSAPI = exports.apigAPI = exports.clientAPI = exports.datastoreAPI = exports.zcqlAPI = exports.queueAPI = exports.filestoreAPI = exports.cacheAPI = exports.sdkAPI = exports.envAPI = exports.projectAPI = exports.orgAPI = void 0;
35
+ exports.tunnelAPI = exports.commonAPI = exports.jobScheduling = exports.codeDeck = exports.gitHubAPI = exports.stratusAPI = exports.zestAPI = exports.appSailAPI = exports.logAPI = exports.eventBusAPI = exports.functionsAPI = exports.applogicAPI = exports.bulkDSAPI = exports.apigAPI = exports.clientAPI = exports.datastoreAPI = exports.zcqlAPI = exports.queueAPI = exports.filestoreAPI = exports.cacheAPI = exports.sdkAPI = exports.envAPI = exports.projectAPI = exports.orgAPI = void 0;
36
36
  const project_1 = require("../util_modules/project");
37
37
  function orgAPI({ auth = true } = {}) {
38
38
  return __awaiter(this, void 0, void 0, function* () {
@@ -156,6 +156,13 @@ function appSailAPI({ auth = true, projectId = (0, project_1.getProjectId)(), en
156
156
  });
157
157
  }
158
158
  exports.appSailAPI = appSailAPI;
159
+ function zestAPI({ auth = true, projectId = (0, project_1.getProjectId)(), env = (0, project_1.getEnvName)() } = {}) {
160
+ return __awaiter(this, void 0, void 0, function* () {
161
+ const zest = (yield Promise.resolve().then(() => __importStar(require('./lib/zest.js')))).default;
162
+ return new zest(projectId, { authNeeded: auth, env, isExternal: true });
163
+ });
164
+ }
165
+ exports.zestAPI = zestAPI;
159
166
  function stratusAPI({ auth = true, projectId = (0, project_1.getProjectId)(), env = (0, project_1.getEnvName)() } = {}) {
160
167
  return __awaiter(this, void 0, void 0, function* () {
161
168
  const stratus = (yield Promise.resolve().then(() => __importStar(require('./lib/stratus')))).default;
@@ -198,10 +205,3 @@ function tunnelAPI({ auth = true, projectId = (0, project_1.getProjectId)() } =
198
205
  });
199
206
  }
200
207
  exports.tunnelAPI = tunnelAPI;
201
- function credentialsAPI({ auth = false, projectId = (0, project_1.getProjectId)() } = {}) {
202
- return __awaiter(this, void 0, void 0, function* () {
203
- const credentials = (yield Promise.resolve().then(() => __importStar(require('./lib/credentials')))).default;
204
- return new credentials(projectId, { authNeeded: auth });
205
- });
206
- }
207
- exports.credentialsAPI = credentialsAPI;
@@ -0,0 +1,124 @@
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 error_1 = __importDefault(require("../../error"));
16
+ const api_1 = __importDefault(require("../../internal/api"));
17
+ const js_1 = require("../../util_modules/js");
18
+ const logger_1 = require("../../util_modules/logger");
19
+ const project_1 = require("../../util_modules/project");
20
+ class Zest {
21
+ constructor(projectId, opts) {
22
+ this.opts = Object.assign(Object.assign({}, opts), { headers: {
23
+ 'CATALYST-ORG': (0, project_1.getEnvId)()
24
+ } });
25
+ this.projectId = projectId;
26
+ }
27
+ getSpecifications(query) {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ try {
30
+ const res = yield new api_1.default(this.opts).get(`/zest/v1/project/${this.projectId}/specifications`, {
31
+ qs: query,
32
+ log: {
33
+ awaitingSpinner: 'Getting Zest Specifications'
34
+ }
35
+ });
36
+ if (res.body || res.status === 204) {
37
+ return res.body;
38
+ }
39
+ (0, logger_1.debug)('get specifications response from server : ' + res.body);
40
+ throw new error_1.default('Server Error: Unexpected Response from server.', {
41
+ exit: 2
42
+ });
43
+ }
44
+ catch (err) {
45
+ if (err.status === 429) {
46
+ const responseData = err.context;
47
+ const retryAfter = responseData.response.headers['Retry-After'];
48
+ setTimeout(() => __awaiter(this, void 0, void 0, function* () { return yield this.getSpecifications(query); }), (retryAfter ? parseInt(retryAfter, 10) : 1) * 1000);
49
+ }
50
+ throw err;
51
+ }
52
+ });
53
+ }
54
+ generateFunction(resources, specEnv, name) {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ const res = yield new api_1.default(this.opts).post(`/zest/v1/project/${this.projectId}/specifications/actions/generate_function`, {
57
+ body: {
58
+ name,
59
+ stack: specEnv,
60
+ resources: resources
61
+ },
62
+ log: {
63
+ awaitingSpinner: `Scheduling Function Generation ${name}`
64
+ }
65
+ });
66
+ if (res.body && res.body.details && res.body.code === 'SCHEDULED') {
67
+ return res.body.details;
68
+ }
69
+ (0, logger_1.debug)('generate function response from server : ' + res.body);
70
+ throw new error_1.default('Server Error: Unexpected Response from server.', {
71
+ exit: 2
72
+ });
73
+ });
74
+ }
75
+ generateAppsail(requestJson) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ const res = yield new api_1.default(this.opts).post(`/zest/v1/project/${this.projectId}/specifications/actions/generate_appsail`, {
78
+ body: requestJson,
79
+ log: {
80
+ awaitingSpinner: `Scheduling Appsail Generation${requestJson.name}`
81
+ }
82
+ });
83
+ if (res.body && res.body.details && res.body.code === 'SCHEDULED') {
84
+ return res.body.details;
85
+ }
86
+ (0, logger_1.debug)('generate appsail response from server : ' + res.body);
87
+ throw new error_1.default('Server Error: Unexpected Response from server.', {
88
+ exit: 2
89
+ });
90
+ });
91
+ }
92
+ getScheduledJob(job_id) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ const res = yield new api_1.default(this.opts).get(`/zest/v1/scheduled_jobs/${job_id}`);
95
+ if (res.body) {
96
+ return res.body;
97
+ }
98
+ (0, logger_1.debug)('get scheduled job response from server : ' + res.body);
99
+ throw new error_1.default('Server Error: Unexpected Response from server.', {
100
+ exit: 2
101
+ });
102
+ });
103
+ }
104
+ getFile(file_id, source, name) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ const res = yield new api_1.default(Object.assign(Object.assign({}, this.opts), { json: false })).get(`/zest/v1/files/${file_id}`, {
107
+ encoding: null,
108
+ log: {
109
+ progress: {
110
+ title: `${js_1.JS.capitalize(source)} (${name})`
111
+ }
112
+ }
113
+ });
114
+ if (res.body) {
115
+ return res.body;
116
+ }
117
+ (0, logger_1.debug)('get file response from server : ' + res);
118
+ throw new error_1.default('Server Error: Unexpected Response from server.', {
119
+ exit: 2
120
+ });
121
+ });
122
+ }
123
+ }
124
+ exports.default = Zest;
@@ -14,7 +14,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  const project_1 = __importDefault(require("../endpoints/lib/project"));
16
16
  const credential_1 = __importDefault(require("../internal/credential"));
17
- const endpoints_1 = require("../endpoints");
18
17
  exports.default = (req, _RES, next) => __awaiter(void 0, void 0, void 0, function* () {
19
18
  var _a;
20
19
  const projectId = req.headers['x-zc-projectid'];
@@ -35,16 +34,7 @@ exports.default = (req, _RES, next) => __awaiter(void 0, void 0, void 0, functio
35
34
  }, [false, false, false]);
36
35
  if (hasCSRF && hasADT && hasBDT) {
37
36
  req.headers['x-zc-user-type'] = 'project-user';
38
- try {
39
- const jwtResponse = yield (yield (0, endpoints_1.credentialsAPI)()).generateJWTToken(cookie);
40
- const tokenRes = yield (yield (0, endpoints_1.credentialsAPI)()).convertJwtToAuthToken(jwtResponse);
41
- req.headers['x-zc-user-cred-type'] = 'token';
42
- req.headers['x-zc-user-cred-token'] = tokenRes
43
- .access_token;
44
- }
45
- catch (err) {
46
- req.headers['x-zc-cookie'] = cookie;
47
- }
37
+ req.headers['x-zc-cookie'] = cookie;
48
38
  }
49
39
  else if (typeof authorization !== 'undefined') {
50
40
  const currentUser = yield new project_1.default({
@@ -341,7 +341,12 @@ function pack(target) {
341
341
  }
342
342
  exports.pack = pack;
343
343
  function generateUrlForTarget(target) {
344
- const urlDefault = 'https://' + (0, project_1.getDomainPrefix)() + '.' + constants_1.ORIGIN.app.replace('https://', '');
344
+ const domainPrefix = (0, project_1.getDomainPrefix)(false);
345
+ if (!domainPrefix) {
346
+ (0, logger_1.warning)('Failed to retrieve the domain name, so the function URL generation was skipped.');
347
+ return;
348
+ }
349
+ const urlDefault = 'https://' + domainPrefix + '.' + constants_1.ORIGIN.app.replace('https://', '');
345
350
  switch (target.type) {
346
351
  case constants_1.FN_TYPE.basic:
347
352
  case constants_1.FN_TYPE.browserLogic:
@@ -61,6 +61,7 @@ exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
61
61
  when: orgChoice.length > 1
62
62
  }));
63
63
  const selectedOrg = orgAns.org || orgList[0];
64
+ runtime_store_1.default.set('project.env.id', selectedOrg.id);
64
65
  (0, logger_1.message)('Setting up a new default project for this folder\n');
65
66
  const projectAPI = yield (0, endpoints_1.projectAPI)({ auth: true, org: selectedOrg.id });
66
67
  const allProjects = (yield projectAPI.getAllProjects());
@@ -47,11 +47,11 @@ const project_1 = require("../util_modules/project");
47
47
  const fs_1 = require("fs");
48
48
  const throbber_1 = __importDefault(require("../throbber"));
49
49
  class API {
50
- constructor({ authNeeded = true, resolveOnError = false, maxRetry = 3, env = constants_1.DEFAULT.env_name, log = {}, headers = {}, isExternal = false, origin = constants_1.ORIGIN.admin, showWarning = true, envId = (0, project_1.getEnvId)(), printError = true } = {}) {
50
+ constructor({ authNeeded = true, resolveOnError = false, maxRetry = 3, env = constants_1.DEFAULT.env_name, log = {}, headers = {}, isExternal = false, origin = constants_1.ORIGIN.admin, json = true, showWarning = true, envId = (0, project_1.getEnvId)(), printError = true } = {}) {
51
51
  this.requestOpts = {
52
52
  url: origin,
53
53
  method: 'GET',
54
- json: true,
54
+ json,
55
55
  headers
56
56
  };
57
57
  const projectSecretKey = process.env.CATALYST_PROJECT_SECRET_KEY;
@@ -63,11 +63,14 @@ exports.default = {
63
63
  const filePathExt = yield Promise.resolve().then(() => __importStar(require('./types/file-path')));
64
64
  inquirer_1.default.registerPrompt('file-path', filePathExt.default);
65
65
  break;
66
- case 'tree': {
66
+ case 'tree':
67
67
  const treeExt = yield Promise.resolve().then(() => __importStar(require('./types/tree')));
68
68
  inquirer_1.default.registerPrompt('tree', treeExt.default);
69
69
  break;
70
- }
70
+ case 'search-box':
71
+ const searchExt = yield Promise.resolve().then(() => __importStar(require('./types/search-box')));
72
+ inquirer_1.default.registerPrompt('search-box', searchExt.default);
73
+ break;
71
74
  default:
72
75
  throw new error_1.default('No such type registered', { exit: 2 });
73
76
  }
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const chalk_1 = __importDefault(require("chalk"));
7
+ const cli_cursor_1 = __importDefault(require("cli-cursor"));
8
+ const figures_1 = __importDefault(require("figures"));
9
+ const choices_1 = __importDefault(require("inquirer/lib/objects/choices"));
10
+ const base_1 = __importDefault(require("inquirer/lib/prompts/base"));
11
+ const events_1 = __importDefault(require("inquirer/lib/utils/events"));
12
+ const paginator_1 = __importDefault(require("inquirer/lib/utils/paginator"));
13
+ const operators_1 = require("rxjs/operators");
14
+ class SearchBox extends base_1.default {
15
+ constructor(questions, rl, answers) {
16
+ super(questions, rl, answers);
17
+ this.pointer = 0;
18
+ if (this.opt.highlight == null) {
19
+ this.opt.highlight = false;
20
+ }
21
+ if (typeof this.opt.searchable == null) {
22
+ this.opt.searchable = false;
23
+ }
24
+ if (typeof this.opt.default == null) {
25
+ this.opt.default = undefined;
26
+ }
27
+ if (this.opt.source == null) {
28
+ this.throwParamError('source');
29
+ }
30
+ if (this.opt.notFoundMsg === undefined) {
31
+ this.opt.notFoundMsg = 'No results...';
32
+ }
33
+ if (this.opt.searchMsg === undefined) {
34
+ this.opt.searchMsg = 'Searching...';
35
+ }
36
+ this.pointer = 0;
37
+ this.firstSourceLoading = true;
38
+ this.choices = new choices_1.default([], answers);
39
+ this.checkedChoices = [];
40
+ this.value = [];
41
+ this.lastQuery = undefined;
42
+ this.searching = false;
43
+ this.lastSourcePromise = undefined;
44
+ this.default = this.opt.default;
45
+ this.opt.default = undefined;
46
+ this.selection = [];
47
+ this.done = undefined;
48
+ this.paginator = new paginator_1.default(this.screen);
49
+ }
50
+ _run(callback) {
51
+ this.done = callback;
52
+ this.executeSource().then(() => {
53
+ const events = (0, events_1.default)(this.rl);
54
+ const validation = this.handleSubmitEvents(events.line.pipe((0, operators_1.map)(this.getCurrentValue.bind(this))));
55
+ validation.success.forEach(this.onEnd.bind(this));
56
+ validation.error.forEach(this.onError.bind(this));
57
+ events.normalizedUpKey
58
+ .pipe((0, operators_1.takeUntil)(validation.success))
59
+ .forEach(this.onUpKey.bind(this));
60
+ events.normalizedDownKey
61
+ .pipe((0, operators_1.takeUntil)(validation.success))
62
+ .forEach(this.onDownKey.bind(this));
63
+ events.spaceKey.pipe((0, operators_1.takeUntil)(validation.success)).forEach(this.onSpaceKey.bind(this));
64
+ if (this.opt.searchable === false) {
65
+ events.numberKey
66
+ .pipe((0, operators_1.takeUntil)(validation.success))
67
+ .forEach(this.onNumberKey.bind(this));
68
+ events.aKey.pipe((0, operators_1.takeUntil)(validation.success)).forEach(this.onAllKey.bind(this));
69
+ events.iKey
70
+ .pipe((0, operators_1.takeUntil)(validation.success))
71
+ .forEach(this.onInverseKey.bind(this));
72
+ }
73
+ else {
74
+ events.keypress
75
+ .pipe((0, operators_1.takeUntil)(validation.success))
76
+ .forEach(this.onKeypress.bind(this));
77
+ }
78
+ if (this.rl.line) {
79
+ this.onKeypress();
80
+ }
81
+ cli_cursor_1.default.hide();
82
+ this.render();
83
+ });
84
+ return this;
85
+ }
86
+ getValue(choice) {
87
+ if (choice.type === 'separator') {
88
+ return undefined;
89
+ }
90
+ return choice.value;
91
+ }
92
+ executeSource() {
93
+ let sourcePromise;
94
+ this.rl.line = this.rl.line.trim();
95
+ if (this.rl.line === this.lastQuery) {
96
+ return Promise.resolve(undefined);
97
+ }
98
+ if (this.opt.searchable) {
99
+ sourcePromise = this.opt.source(this.answers, this.rl.line);
100
+ }
101
+ else {
102
+ sourcePromise = this.opt.source(this.answers, undefined);
103
+ }
104
+ this.lastQuery = this.rl.line;
105
+ this.lastSourcePromise = sourcePromise;
106
+ this.searching = true;
107
+ sourcePromise.then((choices) => {
108
+ if (this.lastSourcePromise !== sourcePromise) {
109
+ return;
110
+ }
111
+ this.searching = false;
112
+ this.choices = new choices_1.default(choices, this.answers);
113
+ this.choices.forEach((choice) => {
114
+ var _a;
115
+ if (this.value.some((eachValue) => this.getValue(choice) === eachValue)) {
116
+ this.toggleChoice(choice, true);
117
+ }
118
+ else {
119
+ this.toggleChoice(choice, false);
120
+ }
121
+ if (this.default !== null) {
122
+ if ((_a = this.default) === null || _a === void 0 ? void 0 : _a.some((defaultValue) => this.getValue(choice) === defaultValue)) {
123
+ this.toggleChoice(choice, true);
124
+ }
125
+ }
126
+ });
127
+ this.pointer = 0;
128
+ this.render();
129
+ this.default = undefined;
130
+ this.firstSourceLoading = false;
131
+ });
132
+ return sourcePromise;
133
+ }
134
+ render(error) {
135
+ let message = this.getQuestion();
136
+ let bottomContent = '';
137
+ if (this.status === 'answered') {
138
+ message += chalk_1.default.cyan(this.selection.join(', '));
139
+ return this.screen.render(message, bottomContent);
140
+ }
141
+ if (this.firstSourceLoading) {
142
+ if (this.opt.searchable) {
143
+ message += `(Press ${chalk_1.default.cyan.bold('<space>')} to select, or type anything to filter the list)`;
144
+ }
145
+ else {
146
+ message += `(Press ${chalk_1.default.cyan.bold('<space>')} to select, ${chalk_1.default.cyan.bold('<a>')} to toggle all, ${chalk_1.default.cyan.bold('<i>')} to invert selection)`;
147
+ }
148
+ }
149
+ if (this.opt.searchable) {
150
+ message += this.rl.line;
151
+ }
152
+ if (this.searching) {
153
+ message += `\n ${chalk_1.default.cyan(this.opt.searchMsg)}`;
154
+ }
155
+ else if (!this.choices.length) {
156
+ message += `\n ${chalk_1.default.yellow(this.opt.notFoundMsg)}`;
157
+ }
158
+ else {
159
+ const choicesStr = this.renderChoices(this.choices, this.pointer);
160
+ const choice = this.choices.getChoice(this.pointer);
161
+ const indexPosition = this.choices.indexOf(choice);
162
+ message += `\n${this.paginator.paginate(choicesStr, indexPosition, this.opt.pageSize)}`;
163
+ }
164
+ if (error) {
165
+ bottomContent = chalk_1.default.red('>> ') + error;
166
+ }
167
+ return this.screen.render(message, bottomContent);
168
+ }
169
+ onEnd(state) {
170
+ var _a;
171
+ this.status = 'answered';
172
+ this.render();
173
+ this.screen.done();
174
+ cli_cursor_1.default.show();
175
+ (_a = this.done) === null || _a === void 0 ? void 0 : _a.call(this, 'value' in state ? state.value : undefined);
176
+ }
177
+ onError(state) {
178
+ if (state.isValid) {
179
+ this.render();
180
+ }
181
+ }
182
+ getCurrentValue() {
183
+ this.selection = this.checkedChoices.map((checkedChoice) => checkedChoice.short);
184
+ const values = this.checkedChoices.map((checkedChoice) => checkedChoice.value);
185
+ return values;
186
+ }
187
+ onUpKey() {
188
+ const len = this.choices.realLength;
189
+ this.pointer = this.pointer > 0 ? this.pointer - 1 : len - 1;
190
+ this.render();
191
+ }
192
+ onDownKey() {
193
+ const len = this.choices.realLength;
194
+ this.pointer = this.pointer < len - 1 ? this.pointer + 1 : 0;
195
+ this.render();
196
+ }
197
+ onNumberKey(input) {
198
+ if (input <= this.choices.realLength) {
199
+ this.pointer = input - 1;
200
+ this.toggleChoice(this.choices.getChoice(this.pointer));
201
+ }
202
+ this.render();
203
+ }
204
+ onSpaceKey() {
205
+ if (this.choices.getChoice(this.pointer) == null) {
206
+ return;
207
+ }
208
+ this.toggleChoice(this.choices.getChoice(this.pointer));
209
+ this.render();
210
+ }
211
+ onAllKey() {
212
+ const shouldBeChecked = Boolean(this.choices.find((choice) => {
213
+ return choice.type !== 'separator' && !choice.checked;
214
+ }));
215
+ this.choices.forEach((choice) => {
216
+ if (choice.type !== 'separator') {
217
+ choice.checked = shouldBeChecked;
218
+ }
219
+ return choice;
220
+ });
221
+ this.render();
222
+ }
223
+ onInverseKey() {
224
+ this.choices.forEach((choice) => {
225
+ if (choice.type !== 'separator') {
226
+ choice.checked = !choice.checked;
227
+ }
228
+ });
229
+ this.render();
230
+ }
231
+ onKeypress() {
232
+ this.executeSource();
233
+ this.render();
234
+ }
235
+ toggleChoice(choice, nextChecked) {
236
+ var _a;
237
+ if (choice.type === 'separator') {
238
+ return;
239
+ }
240
+ const checked = nextChecked == null ? !((_a = choice.checked) !== null && _a !== void 0 ? _a : false) : nextChecked;
241
+ this.value = this.value.filter((eachValue) => eachValue !== choice.value);
242
+ this.checkedChoices = this.checkedChoices.filter((checkedChoice) => checkedChoice.value !== choice.value);
243
+ choice.checked = false;
244
+ if (checked === true) {
245
+ this.value.push(choice.value);
246
+ this.checkedChoices.push(choice);
247
+ choice.checked = true;
248
+ }
249
+ }
250
+ static getCheckboxFigure(checked = false) {
251
+ return checked ? chalk_1.default.green(figures_1.default.radioOn) : figures_1.default.radioOff;
252
+ }
253
+ renderChoices(choices, pointer) {
254
+ const output = [];
255
+ let separatorOffset = 0;
256
+ choices.forEach((choice, index) => {
257
+ if (choice.type === 'separator') {
258
+ separatorOffset += 1;
259
+ output.push(` ${choice}\n`);
260
+ return;
261
+ }
262
+ if (choice.disabled) {
263
+ separatorOffset += 1;
264
+ output.push(` - ${choice.name} (${typeof choice.disabled === 'string' ? choice.disabled : 'Disabled'})\n`);
265
+ return;
266
+ }
267
+ if (index - separatorOffset === pointer) {
268
+ output.push(chalk_1.default.cyan(figures_1.default.pointer));
269
+ output.push(SearchBox.getCheckboxFigure(choice.checked));
270
+ output.push(' ');
271
+ output.push(this.opt.highlight ? chalk_1.default.gray(choice.name) : choice.name);
272
+ }
273
+ else {
274
+ output.push(` ${SearchBox.getCheckboxFigure(choice.checked)} ${choice.name}`);
275
+ }
276
+ output.push('\n');
277
+ });
278
+ return output.join('').replace(/\n$/, '');
279
+ }
280
+ }
281
+ exports.default = SearchBox;
@@ -40,5 +40,13 @@ exports.default = Object.freeze({
40
40
  w_auth: 'us',
41
41
  m_auth: 'us',
42
42
  ext: '.ca'
43
+ },
44
+ sa: {
45
+ loc: 'SaudiArabia',
46
+ ref: 'sa',
47
+ value: 'sa',
48
+ w_auth: 'us',
49
+ m_auth: 'us',
50
+ ext: '.sa'
43
51
  }
44
52
  });
@@ -75,5 +75,10 @@ exports.default = Object.freeze({
75
75
  bucket_read: 'ZohoCatalyst.buckets.READ',
76
76
  object_create: 'ZohoCatalyst.buckets.objects.CREATE',
77
77
  pipline_read: 'ZohoCatalyst.pipeline.READ',
78
- pipeline_exec_create: 'ZohoCatalyst.pipeline.execution.CREATE'
78
+ pipeline_exec_create: 'ZohoCatalyst.pipeline.execution.CREATE',
79
+ zest_file_read: 'ZohoZEST.files.READ',
80
+ zest_spec_read: 'ZohoZEST.specifications.READ',
81
+ zest_spec_all: 'ZohoZEST.specifications.ALL',
82
+ zest_spec_src_action: 'ZohoZEST.specifications.sources.CREATE',
83
+ zest_schedule_job_read: 'ZohoZEST.scheduled_jobs.READ'
79
84
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zcatalyst-cli",
3
- "version": "1.18.0-beta.5",
3
+ "version": "1.18.0-beta.7",
4
4
  "description": "Command Line Tool for CATALYST",
5
5
  "main": "./lib/index.js",
6
6
  "bin": {
@@ -25,7 +25,7 @@
25
25
  "homepage": "https://catalyst.zoho.com",
26
26
  "license": "MIT",
27
27
  "dependencies": {
28
- "ansi-colors": "^4.1.1",
28
+ "ansi-colors": "^4.1.3",
29
29
  "app-module-path": "^2.2.0",
30
30
  "better-queue": "^3.8.10",
31
31
  "chokidar": "^3.5.3",
@@ -1,59 +0,0 @@
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 api_1 = __importDefault(require("../../internal/api"));
16
- const logger_1 = require("../../util_modules/logger");
17
- const error_1 = __importDefault(require("../../error"));
18
- const project_1 = require("../../util_modules/project");
19
- const constants_1 = require("../../util_modules/constants");
20
- const js_1 = require("../../util_modules/js");
21
- class Credentials {
22
- constructor(projectId, opts) {
23
- this.opts = opts;
24
- this.projectId = projectId;
25
- this.projectDomain = `https://${(0, project_1.getDomainPrefix)()}.${constants_1.ORIGIN.app.replace('https://', '')}`;
26
- }
27
- generateJWTToken(cookie) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const res = yield new api_1.default(Object.assign(Object.assign({}, this.opts), { headers: { Cookie: cookie }, origin: this.projectDomain })).get(`/baas/v1/project/${this.projectId}/authentication/custom-token`);
30
- if (res.body && res.body.data) {
31
- return res.body.data;
32
- }
33
- (0, logger_1.debug)('Download response from server : ' + res.body);
34
- throw new error_1.default('Server Error: Unexpected Response from server.', {
35
- exit: 2
36
- });
37
- });
38
- }
39
- convertJwtToAuthToken(reqOpts) {
40
- return __awaiter(this, void 0, void 0, function* () {
41
- const res = yield new api_1.default(Object.assign(Object.assign({}, this.opts), { origin: constants_1.ORIGIN.iamPortal, headers: { Origin: this.projectDomain } })).post(`/clientoauth/v2/${(0, project_1.getDomainKey)()}/remote/auth`, {
42
- qs: {
43
- response_type: 'remote_token',
44
- jwt_token: reqOpts.jwt_token,
45
- client_id: reqOpts.client_id,
46
- scope: js_1.JS.values(reqOpts.scopes).join(' ')
47
- }
48
- });
49
- if (res.body) {
50
- return res.body;
51
- }
52
- (0, logger_1.debug)('Download response from server : ' + res.body);
53
- throw new error_1.default('Server Error: Unexpected Response from server.', {
54
- exit: 2
55
- });
56
- });
57
- }
58
- }
59
- exports.default = Credentials;