@controlplane/cli
Version:
Control Plane Corporation CLI
209 lines • 7.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.newDefaultSession = newDefaultSession;
const chalk = require("chalk");
const axios_1 = require("axios");
const uuid_1 = require("uuid");
const format_1 = require("../format/format");
const objects_1 = require("../util/objects");
const logger_1 = require("../util/logger");
const errors_1 = require("../util/errors");
function applyColor(text, color) {
if (!color) {
return text;
}
switch (color) {
case 'yellow':
return chalk.yellow(text);
case 'red':
return chalk.red(text);
case 'green':
return chalk.green(text);
case 'blue':
return chalk.blue(text);
case 'cyan':
return chalk.cyan(text);
case 'magenta':
return chalk.magenta(text);
case 'gray':
return chalk.gray(text);
default:
return text;
}
}
function newDefaultSession(env, args) {
var _a, _b, _c;
let pfName;
let pfSource;
const guessed = env.profileManager.guessDefault();
if (guessed) {
pfName = guessed.name;
pfSource = guessed.source;
}
if (args.profile) {
// override
pfName = args.profile;
pfSource = 'arg';
}
let profile;
if (pfName) {
profile = env.profileManager.find(pfName);
if (!profile) {
throw new Error(buildProfileNotFoundError(pfName, pfSource));
}
}
else {
const endpoint = args.endpoint || process.env['CPLN_ENDPOINT'] || 'https://api.cpln.io';
const token = args.token || process.env['CPLN_TOKEN'];
// we can talk to to the API with a token & endpoint
if (endpoint && token) {
profile = {
name: 'anonymous',
synthesized: true,
request: {
endpoint: endpoint,
token: token,
},
context: {},
format: {},
tokenServer: {
code: '',
secret: '',
},
};
}
else {
throw new Error('no profile defined. Set a default one or provide one using --profile');
}
}
const sid = (0, uuid_1.v4)();
logger_1.logger.debug('Starting session ' + sid);
const session = {
id: sid,
env: env,
profile: profile,
pendingNotice: undefined,
debug: (0, objects_1.pick)(args, 'debug', 'verbose'),
context: (0, objects_1.merge)((_a = profile.context) !== null && _a !== void 0 ? _a : {}, {
org: process.env['CPLN_ORG'], //
gvc: process.env['CPLN_GVC'],
}, (0, objects_1.pick)(args, 'org', 'gvc', 'profile'), {
profile: pfName,
}),
request: (0, objects_1.merge)((_b = profile.request) !== null && _b !== void 0 ? _b : {}, {
endpoint: process.env['CPLN_ENDPOINT'], //
token: process.env['CPLN_TOKEN'],
}, (0, objects_1.pick)(args, 'endpoint', 'insecure', 'timeout', 'token')),
format: (0, objects_1.merge)((_c = profile.format) !== null && _c !== void 0 ? _c : {}, (0, objects_1.pick)(args, 'color', 'max', 'output', 'ts')),
err: (obj, color) => {
(0, format_1.write)(env.err, typeof obj === 'string' ? applyColor(obj, color) : obj);
},
out: (obj, color) => {
(0, format_1.write)(env.out, applyColor(obj, color));
},
end(message) {
this.out(message + '\n');
process.exit(0);
},
abort(why) {
var _a;
logger_1.logger.debug('Abnormal exit ', why);
if (why.message) {
// prefer message to the error
this.err(why.message + '\n');
}
else {
this.errFormat(why.error);
}
process.exit((_a = why.exitCode) !== null && _a !== void 0 ? _a : 1);
},
async outFormat(obj, options) {
try {
this.out(await (0, format_1.formatAsync)(session, obj, options !== null && options !== void 0 ? options : this.format));
// Flush any pending notice after output
if (this.pendingNotice) {
this.err(this.pendingNotice, 'yellow');
this.pendingNotice = undefined;
}
}
catch (e) {
if (e instanceof errors_1.PrettifyTableError) {
this.err(e.message);
throw e.catchedError;
}
if (e instanceof errors_1.FormatNamesError) {
this.err(e.message);
process.exit(1);
}
throw e;
}
},
errFormat(obj, options) {
this.err((0, format_1.format)(obj, { ...(options !== null && options !== void 0 ? options : this.format), _hints: { kind: 'error' } }));
},
};
// Inform about where the profile comes from
if (!args.profile && !!process.env.CPLN_PROFILE) {
logger_1.logger.debug(`Using profile "${process.env.CPLN_PROFILE}" from environment variable "CPLN_PROFILE"`);
}
// Inform about where the token comes from
if (args.token) {
logger_1.logger.debug('Using token from argument "--token"');
}
else if (!!process.env.CPLN_TOKEN) {
logger_1.logger.debug('Using token from environment variable "CPLN_TOKEN"');
}
else if (session.request.token) {
logger_1.logger.info('Using token from the profile');
}
// Inform about where the org comes from
if (!args.org && !!process.env.CPLN_ORG) {
logger_1.logger.debug(`Using org "${process.env.CPLN_ORG}" from environment variable "CPLN_ORG"`);
}
// Inform about where the gvc comes from
if (!args.gvc && !!process.env.CPLN_GVC) {
logger_1.logger.debug(`Using gvc "${process.env.CPLN_GVC}" from environment variable "CPLN_GVC"`);
}
// Inform about where the endpoint comes from
if (!args.endpoint && !!process.env.CPLN_ENDPOINT) {
logger_1.logger.debug(`Using endpoint "${process.env.CPLN_ENDPOINT}" from environment variable "CPLN_ENDPOINT"`);
}
let discovery;
Object.defineProperty(session, 'discovery', {
get: () => {
if (!discovery) {
discovery = axios_1.default
.get('/discovery', {
baseURL: session.request.endpoint,
})
.then((res) => res.data);
}
return discovery;
},
});
return session;
}
function buildProfileNotFoundError(profileName, source) {
const baseMessage = `Profile '${profileName}' does not exist.`;
const listProfilesHint = `Run 'cpln profile get' to see available profiles.`;
if (source === 'env') {
return (`${baseMessage}\n\n` +
`The profile was specified by the CPLN_PROFILE environment variable.\n\n` +
`To fix this, either:\n` +
` - Update CPLN_PROFILE to a valid profile name, or\n` +
` - Unset CPLN_PROFILE and set a default profile with 'cpln profile set-default <name>'\n\n` +
listProfilesHint);
}
if (source === 'arg') {
return `${baseMessage}\n\n${listProfilesHint}`;
}
if (source === 'default') {
return (`${baseMessage}\n\n` +
`The profile was set as the default but no longer exists.\n\n` +
`Run 'cpln profile set-default <name>' to set a valid default profile.\n\n` +
listProfilesHint);
}
// 'smart' or undefined - generic message
return `${baseMessage}\n\n${listProfilesHint}`;
}
//# sourceMappingURL=session.js.map