UNPKG

@graphql-hive/cli

Version:

A CLI util to manage and control your GraphQL Hive

214 lines • 8.2 kB
"use strict"; 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 graphql_1 = require("graphql"); const core_1 = require("@graphql-hive/core"); const core_2 = require("@oclif/core"); const config_1 = require("./helpers/config"); 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.log(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 message custom error message in case of no value * @param env an env var name */ ensure({ key, args, legacyFlagName, defaultValue, message, env, }) { if (args[key] != null) { return args[key]; } if (legacyFlagName && args[legacyFlagName] != null) { return args[legacyFlagName]; } // eslint-disable-next-line no-process-env if (env && process.env[env]) { // eslint-disable-next-line no-process-env return process.env[env]; } const userConfigValue = this._userConfig.get(key); if (userConfigValue != null) { return userConfigValue; } if (defaultValue) { return defaultValue; } if (message) { throw new core_2.Errors.CLIError(message); } throw new core_2.Errors.CLIError(`Missing "${String(key)}"`); } 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 { async request(args) { const 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) { console.info(...args); } }, error: (...args) => { console.error(...args); }, }, headers: requestHeaders, timeout: args.timeout, }); if (!response.ok) { throw new Error(`Invalid status code for HTTP call: ${response.status}`); } const jsonData = (await response.json()); if (jsonData.errors && jsonData.errors.length > 0) { throw new ClientError(`Failed to execute GraphQL operation: ${jsonData.errors .map(e => e.message) .join('\n')}`, { errors: jsonData.errors, headers: response.headers, }); } return jsonData.data; }, }; } handleFetchError(error) { var _a, _b, _c, _d, _e; if (typeof error === 'string') { return this.error(error); } if (error instanceof Error) { if (isClientError(error)) { const errors = (_a = error.response) === null || _a === void 0 ? void 0 : _a.errors; if (Array.isArray(errors) && errors.length > 0) { return this.error(errors[0].message, { ref: this.cleanRequestId((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.headers) === null || _c === void 0 ? void 0 : _c.get('x-request-id')), }); } return this.error(error.message, { ref: this.cleanRequestId((_e = (_d = error.response) === null || _d === void 0 ? void 0 : _d.headers) === null || _e === void 0 ? void 0 : _e.get('x-request-id')), }); } return this.error(error); } return this.error(JSON.stringify(error)); } 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))))); } } } BaseCommand.baseFlags = { debug: core_2.Flags.boolean({ default: false, summary: 'Whether debug output for HTTP calls and similar should be enabled.', }), }; exports.default = BaseCommand; class ClientError extends Error { constructor(message, response) { super(message); this.response = response; } } function isClientError(error) { return error instanceof ClientError; } //# sourceMappingURL=base-command.js.map