@graphql-hive/cli
Version:
A CLI util to manage and control your GraphQL Hive
235 lines • 10.1 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = require("node:fs");
const node_process_1 = require("node:process");
const graphql_1 = require("graphql");
const core_1 = require("@graphql-hive/core");
const core_2 = require("@oclif/core");
const config_1 = require("./helpers/config");
const errors_1 = require("./helpers/errors");
const texture_1 = require("./helpers/texture/texture");
class BaseCommand extends core_2.Command {
get userConfig() {
if (!this._userConfig) {
throw new Error('User config is not initialized');
}
return this._userConfig;
}
async init() {
await super.init();
this._userConfig = new config_1.Config({
// eslint-disable-next-line no-process-env
filepath: process.env.HIVE_CONFIG,
rootDir: process.cwd(),
});
const { args, flags } = await this.parse({
flags: this.ctor.flags,
baseFlags: super.ctor.baseFlags,
args: this.ctor.args,
strict: this.ctor.strict,
});
this.flags = flags;
this.args = args;
}
logSuccess(...args) {
this.log(texture_1.Texture.success(...args));
}
logFailure(...args) {
this.logToStderr(texture_1.Texture.failure(...args));
}
logInfo(...args) {
this.log(texture_1.Texture.info(...args));
}
logWarning(...args) {
this.log(texture_1.Texture.warning(...args));
}
maybe({ key, env, args, }) {
if (args[key] != null) {
return args[key];
}
// eslint-disable-next-line no-process-env
if (env && process.env[env]) {
// eslint-disable-next-line no-process-env
return process.env[env];
}
return undefined;
}
/**
* Get a value from arguments or flags first, then from env variables,
* then fallback to config.
* Throw when there's no value.
*
* @param key
* @param args all arguments or flags
* @param defaultValue default value
* @param description description of the flag in case of no value
* @param env an env var name
*/
ensure({ key, args, legacyFlagName, defaultValue, env: envName, description, }) {
let value;
if (args[key] != null) {
value = args[key];
}
else if (legacyFlagName && args[legacyFlagName] != null) {
value = args[legacyFlagName];
}
else if (envName && node_process_1.env[envName] !== undefined) {
value = node_process_1.env[envName];
}
else {
const configValue = this._userConfig.get(key);
if (configValue !== undefined) {
value = configValue;
}
else if (defaultValue) {
value = defaultValue;
}
}
if (value === null || value === void 0 ? void 0 : value.length) {
return value;
}
throw new errors_1.MissingArgumentsError([String(key), description]);
}
cleanRequestId(requestId) {
return requestId ? requestId.split(',')[0].trim() : undefined;
}
registryApi(registry, token) {
const requestHeaders = {
Authorization: `Bearer ${token}`,
'graphql-client-name': 'Hive CLI',
'graphql-client-version': this.config.version,
};
return this.graphql(registry, requestHeaders);
}
graphql(endpoint, additionalHeaders = {}) {
const requestHeaders = Object.assign({ 'Content-Type': 'application/json', Accept: 'application/json', 'User-Agent': `hive-cli/${this.config.version}` }, additionalHeaders);
const isDebug = this.flags.debug;
return {
request: async (args) => {
var _a, _b, _c, _d, _e, _f, _g;
let response;
try {
response = await core_1.http.post(endpoint, JSON.stringify({
query: typeof args.operation === 'string' ? args.operation : (0, graphql_1.print)(args.operation),
variables: args.variables,
}), {
logger: {
info: (...args) => {
if (isDebug) {
this.logInfo(...args);
}
},
error: (...args) => {
// Allow retrying requests without noise
if (isDebug) {
this.logWarning(...args);
}
},
},
headers: requestHeaders,
timeout: args.timeout,
});
}
catch (e) {
const sourceError = (_a = e === null || e === void 0 ? void 0 : e.cause) !== null && _a !== void 0 ? _a : e;
if ((0, errors_1.isAggregateError)(sourceError)) {
throw new errors_1.NetworkError((_b = sourceError.errors[0]) === null || _b === void 0 ? void 0 : _b.message);
}
else {
throw new errors_1.NetworkError(sourceError);
}
}
if (!response.ok) {
throw new errors_1.HTTPError(endpoint, response.status, (_c = response.statusText) !== null && _c !== void 0 ? _c : 'Invalid status code for HTTP call');
}
let jsonData;
try {
jsonData = (await response.json());
}
catch (err) {
const contentType = (_d = response === null || response === void 0 ? void 0 : response.headers) === null || _d === void 0 ? void 0 : _d.get('content-type');
throw new errors_1.APIError(`Response from graphql was not valid JSON.${contentType ? ` Received "content-type": "${contentType}".` : ''}`, this.cleanRequestId((_e = response === null || response === void 0 ? void 0 : response.headers) === null || _e === void 0 ? void 0 : _e.get('x-request-id')));
}
if (jsonData.errors && jsonData.errors.length > 0) {
if (((_f = jsonData.errors[0].extensions) === null || _f === void 0 ? void 0 : _f.code) === 'ERR_MISSING_TARGET') {
throw new errors_1.MissingArgumentsError([
'target',
'The target on which the action is performed.' +
' This can either be a slug following the format "$organizationSlug/$projectSlug/$targetSlug" (e.g "the-guild/graphql-hive/staging")' +
' or an UUID (e.g. "a0f4c605-6541-4350-8cfe-b31f21a4bf80").',
]);
}
if (jsonData.errors[0].message === 'Invalid token provided') {
throw new errors_1.InvalidRegistryTokenError();
}
if (isDebug) {
this.logFailure(jsonData.errors);
}
throw new errors_1.APIError(jsonData.errors.map(e => e.message).join('\n'), this.cleanRequestId((_g = response === null || response === void 0 ? void 0 : response.headers) === null || _g === void 0 ? void 0 : _g.get('x-request-id')));
}
return jsonData.data;
},
};
}
async require(flags) {
if (flags.require && flags.require.length > 0) {
await Promise.all(flags.require.map(mod => Promise.resolve(`${require.resolve(mod, { paths: [process.cwd()] })}`).then(s => __importStar(require(s)))));
}
}
readJSON(file) {
// If we can't parse it, we can try to load it from FS
const exists = (0, node_fs_1.existsSync)(file);
if (!exists) {
throw new errors_1.FileMissingError(file, 'Please specify a path to an existing file, or a string with valid JSON');
}
try {
const fileContent = (0, node_fs_1.readFileSync)(file, 'utf-8');
JSON.parse(fileContent);
return fileContent;
}
catch (e) {
throw new errors_1.InvalidFileContentsError(file, 'JSON');
}
}
}
BaseCommand.baseFlags = {
debug: core_2.Flags.boolean({
default: false,
summary: 'Whether debug output for HTTP calls and similar should be enabled.',
}),
};
exports.default = BaseCommand;
//# sourceMappingURL=base-command.js.map
;