text: "use strict";
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
      function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
      return new (P || (P = Promise))(function (resolve, reject) {
          function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
          function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
          function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
          step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
  };
  var __importDefault = (this && this.__importDefault) || function (mod) {
      return (mod && mod.__esModule) ? mod : { "default": mod };
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getVersion = exports.formatSchema = exports.getConfig = exports.getDMMF = void 0;
  const chalk_1 = __importDefault(require("chalk"));
  const execa_1 = __importDefault(require("execa"));
  const path_1 = __importDefault(require("path"));
  const temp_write_1 = __importDefault(require("temp-write"));
  const fs_1 = __importDefault(require("fs"));
  const util_1 = require("util");
  const debug_1 = __importDefault(require("@prisma/debug"));
  const resolveBinary_1 = require("./resolveBinary");
  const debug = debug_1.default('engineCommands');
  const unlink = util_1.promisify(fs_1.default.unlink);
  const MAX_BUFFER = 1000 * 1000 * 1000;
  /**
   * This annotation is used for `node-file-trace`
   * See https://github.com/zeit/node-file-trace/issues/104
   */
  path_1.default.join(__dirname, '../query-engine-darwin');
  path_1.default.join(__dirname, '../introspection-engine-darwin');
  path_1.default.join(__dirname, '../prisma-fmt-darwin');
  path_1.default.join(__dirname, '../query-engine-debian-openssl-1.0.x');
  path_1.default.join(__dirname, '../introspection-engine-debian-openssl-1.0.x');
  path_1.default.join(__dirname, '../prisma-fmt-debian-openssl-1.0.x');
  path_1.default.join(__dirname, '../query-engine-debian-openssl-1.1.x');
  path_1.default.join(__dirname, '../introspection-engine-debian-openssl-1.1.x');
  path_1.default.join(__dirname, '../prisma-fmt-debian-openssl-1.1.x');
  path_1.default.join(__dirname, '../query-engine-rhel-openssl-1.0.x');
  path_1.default.join(__dirname, '../introspection-engine-rhel-openssl-1.0.x');
  path_1.default.join(__dirname, '../prisma-fmt-rhel-openssl-1.0.x');
  path_1.default.join(__dirname, '../query-engine-rhel-openssl-1.1.x');
  path_1.default.join(__dirname, '../introspection-engine-rhel-openssl-1.1.x');
  path_1.default.join(__dirname, '../prisma-fmt-rhel-openssl-1.1.x');
  function getDMMF({ datamodel, cwd = process.cwd(), prismaPath: queryEnginePath, datamodelPath, retry = 4, enableExperimental, }) {
      return __awaiter(this, void 0, void 0, function* () {
          queryEnginePath = yield resolveBinary_1.resolveBinary('query-engine', queryEnginePath);
          let result;
          try {
              let tempDatamodelPath = datamodelPath;
              if (!tempDatamodelPath) {
                  try {
                      tempDatamodelPath = yield temp_write_1.default(datamodel);
                  }
                  catch (err) {
                      throw new Error(chalk_1.default.redBright.bold('Get DMMF ') +
                          'unable to write temp data model path');
                  }
              }
              const options = {
                  cwd,
                  env: Object.assign(Object.assign(Object.assign({}, process.env), { PRISMA_DML_PATH: tempDatamodelPath, RUST_BACKTRACE: '1' }), (process.env.NO_COLOR ? {} : { CLICOLOR_FORCE: '1' })),
                  maxBuffer: MAX_BUFFER,
              };
              const experimentalFlags = enableExperimental &&
                  Array.isArray(enableExperimental) &&
                  enableExperimental.length > 0
                  ? [`--enable-experimental=${enableExperimental.join(',')}`]
                  : [];
              const args = [...experimentalFlags, '--enable-raw-queries', 'cli', 'dmmf'];
              result = yield execa_1.default(queryEnginePath, args, options);
              if (!datamodelPath) {
                  yield unlink(tempDatamodelPath);
              }
              if (result.stdout.includes('Please wait until the') && retry > 0) {
                  debug('Retrying after "Please wait until"');
                  yield new Promise((r) => setTimeout(r, 5000));
                  return getDMMF({
                      datamodel,
                      cwd,
                      prismaPath: queryEnginePath,
                      datamodelPath,
                      retry: retry - 1,
                  });
              }
              const firstCurly = result.stdout.indexOf('{');
              const stdout = result.stdout.slice(firstCurly);
              return JSON.parse(stdout);
          }
          catch (e) {
              debug('getDMMF failed', e);
              // If this unlikely event happens, try it at least once more
              if (e.message.includes('Command failed with exit code 26 (ETXTBSY)') &&
                  retry > 0) {
                  yield new Promise((resolve) => setTimeout(resolve, 500));
                  debug('Retrying after ETXTBSY');
                  return getDMMF({
                      datamodel,
                      cwd,
                      prismaPath: queryEnginePath,
                      datamodelPath,
                      retry: retry - 1,
                  });
              }
              const output = e.stderr || e.stdout;
              if (output) {
                  let json;
                  try {
                      json = JSON.parse(output);
                  }
                  catch (e) {
                      //
                  }
                  let message = (json && json.message) || output;
                  if (message.includes('debian-openssl-1.1.x: error while loading shared libraries: libssl.so.1.1: cannot open shared object file: No such file or directory') ||
                      message.includes('debian-openssl-1.0.x: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory')) {
                      message += `\n${chalk_1.default.green(`Your linux installation misses the openssl package. You can install it like so:\n`)}${chalk_1.default.green.bold('apt-get -qy update && apt-get -qy install openssl')}`;
                  }
                  throw new Error(chalk_1.default.redBright.bold('Schema parsing\n') + message);
              }
              if (e.message.includes('in JSON at position')) {
                  throw new Error(`Problem while parsing the query engine response at ${queryEnginePath}. ${result.stdout}\n${e.stack}`);
              }
              throw new Error(e);
          }
      });
  }
  exports.getDMMF = getDMMF;
  function getConfig({ datamodel, cwd = process.cwd(), prismaPath: queryEnginePath, datamodelPath, ignoreEnvVarErrors, }) {
      return __awaiter(this, void 0, void 0, function* () {
          queryEnginePath = yield resolveBinary_1.resolveBinary('query-engine', queryEnginePath);
          let tempDatamodelPath = datamodelPath;
          if (!tempDatamodelPath) {
              try {
                  tempDatamodelPath = yield temp_write_1.default(datamodel);
              }
              catch (err) {
                  throw new Error(chalk_1.default.redBright.bold('Get DMMF ') +
                      'unable to write temp data model path');
              }
          }
          const args = ignoreEnvVarErrors ? ['--ignoreEnvVarErrors'] : [];
          try {
              const result = yield execa_1.default(queryEnginePath, ['cli', 'get-config', ...args], {
                  cwd,
                  env: Object.assign(Object.assign({}, process.env), { PRISMA_DML_PATH: tempDatamodelPath, RUST_BACKTRACE: '1' }),
                  maxBuffer: MAX_BUFFER,
              });
              if (!datamodelPath) {
                  yield unlink(tempDatamodelPath);
              }
              return JSON.parse(result.stdout);
          }
          catch (e) {
              if (e.stderr) {
                  throw new Error(chalk_1.default.redBright.bold('Get config ') + e.stderr);
              }
              if (e.stdout) {
                  throw new Error(chalk_1.default.redBright.bold('Get config ') + e.stdout);
              }
              throw new Error(chalk_1.default.redBright.bold('Get config ') + e);
          }
      });
  }
  exports.getConfig = getConfig;
  function formatSchema({ schemaPath, }) {
      return __awaiter(this, void 0, void 0, function* () {
          if (!fs_1.default.existsSync(schemaPath)) {
              throw new Error(`Schema at ${schemaPath} does not exist.`);
          }
          const prismaFmtPath = yield resolveBinary_1.resolveBinary('prisma-fmt');
          const showColors = !process.env.NO_COLOR && process.stdout.isTTY;
          const options = {
              env: Object.assign(Object.assign(Object.assign({}, process.env), { RUST_BACKTRACE: '1' }), (showColors ? { CLICOLOR_FORCE: '1' } : {})),
              maxBuffer: MAX_BUFFER,
          };
          const result = yield execa_1.default(prismaFmtPath, ['format', '-i', schemaPath], options);
          return result.stdout;
      });
  }
  exports.formatSchema = formatSchema;
  function getVersion(enginePath) {
      return __awaiter(this, void 0, void 0, function* () {
          enginePath = yield resolveBinary_1.resolveBinary('query-engine', enginePath);
          const result = yield execa_1.default(enginePath, ['--version'], {
              env: Object.assign({}, process.env),
              maxBuffer: MAX_BUFFER,
          });
          return result.stdout;
      });
  }
  exports.getVersion = getVersion;
  //# sourceMappingURL=engineCommands.js.map