text: "use strict";
  /*---------------------------------------------------------------------------------------------
   *  Copyright (c) Microsoft Corporation. All rights reserved.
   *  Licensed under the MIT License. See License.txt in the project root for license information.
   *--------------------------------------------------------------------------------------------*/
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.fileExists = exports.directoryExists = exports.fetchJSON = exports.fetch = exports.downloadAndUnzipVSCode = void 0;
  const fs_1 = require("fs");
  const path = require("path");
  const https = require("https");
  const http = require("http");
  const createHttpsProxyAgent = require("https-proxy-agent");
  const createHttpProxyAgent = require("http-proxy-agent");
  const url_1 = require("url");
  const decompress = require("decompress");
  const decompressTargz = require("decompress-targz");
  const extensionRoot = process.cwd();
  const vscodeTestDir = path.resolve(extensionRoot, '.vscode-test-web');
  async function getLatestVersion(quality) {
      const update = await fetchJSON(`https://update.code.visualstudio.com/api/update/web-standalone/${quality}/latest`);
      return update;
  }
  const reset = '\x1b[G\x1b[0K';
  async function download(downloadUrl, destination, message) {
      process.stdout.write(message);
      return new Promise((resolve, reject) => {
          const httpLibrary = downloadUrl.startsWith('https') ? https : http;
          httpLibrary.get(downloadUrl, getAgent(downloadUrl), res => {
              const total = Number(res.headers['content-length']);
              let received = 0;
              let timeout;
              const outStream = (0, fs_1.createWriteStream)(destination);
              outStream.on('close', () => resolve(destination));
              outStream.on('error', reject);
              res.on('data', chunk => {
                  if (!timeout) {
                      timeout = setTimeout(() => {
                          process.stdout.write(`${reset}${message}: ${received}/${total} (${(received / total * 100).toFixed()}%)`);
                          timeout = undefined;
                      }, 100);
                  }
                  received += chunk.length;
              });
              res.on('end', () => {
                  if (timeout) {
                      clearTimeout(timeout);
                  }
                  process.stdout.write(`${reset}${message}: complete\n`);
              });
              res.on('error', reject);
              res.pipe(outStream);
          });
      });
  }
  async function unzip(source, destination, message) {
      process.stdout.write(message);
      if (!(0, fs_1.existsSync)(destination)) {
          await fs_1.promises.mkdir(destination, { recursive: true });
      }
      await decompress(source, destination, {
          plugins: [
              decompressTargz()
          ],
          strip: 1
      });
      process.stdout.write(`${reset}${message}: complete\n`);
  }
  async function downloadAndUnzipVSCode(quality) {
      const info = await getLatestVersion(quality);
      const folderName = `vscode-web-${quality}-${info.version}`;
      const downloadedPath = path.resolve(vscodeTestDir, folderName);
      if ((0, fs_1.existsSync)(downloadedPath) && (0, fs_1.existsSync)(path.join(downloadedPath, 'version'))) {
          return { type: 'static', location: downloadedPath, quality, version: info.version };
      }
      if ((0, fs_1.existsSync)(vscodeTestDir)) {
          await fs_1.promises.rmdir(vscodeTestDir, { recursive: true, maxRetries: 5 });
      }
      await fs_1.promises.mkdir(vscodeTestDir, { recursive: true });
      const productName = `VS Code ${quality === 'stable' ? 'Stable' : 'Insiders'}`;
      const tmpArchiveName = `vscode-web-${quality}-${info.version}-tmp`;
      try {
          await download(info.url, tmpArchiveName, `Downloading ${productName}`);
          await unzip(tmpArchiveName, downloadedPath, `Unpacking ${productName}`);
          await fs_1.promises.writeFile(path.join(downloadedPath, 'version'), folderName);
      }
      catch (err) {
          console.error(err);
          throw Error(`Failed to download and unpack ${productName}`);
      }
      finally {
          try {
              fs_1.promises.unlink(tmpArchiveName);
          }
          catch (e) {
              // ignore
          }
      }
      return { type: 'static', location: downloadedPath, quality, version: info.version };
  }
  exports.downloadAndUnzipVSCode = downloadAndUnzipVSCode;
  async function fetch(api) {
      return new Promise((resolve, reject) => {
          const httpLibrary = api.startsWith('https') ? https : http;
          httpLibrary.get(api, getAgent(api), res => {
              if (res.statusCode !== 200) {
                  reject('Failed to get content from ');
              }
              let data = '';
              res.on('data', chunk => {
                  data += chunk;
              });
              res.on('end', () => {
                  resolve(data);
              });
              res.on('error', err => {
                  reject(err);
              });
          });
      });
  }
  exports.fetch = fetch;
  async function fetchJSON(api) {
      const data = await fetch(api);
      try {
          return JSON.parse(data);
      }
      catch (err) {
          throw new Error(`Failed to parse response from ${api}`);
      }
  }
  exports.fetchJSON = fetchJSON;
  let PROXY_AGENT = undefined;
  let HTTPS_PROXY_AGENT = undefined;
  if (process.env.npm_config_proxy) {
      PROXY_AGENT = createHttpProxyAgent(process.env.npm_config_proxy);
      HTTPS_PROXY_AGENT = createHttpsProxyAgent(process.env.npm_config_proxy);
  }
  if (process.env.npm_config_https_proxy) {
      HTTPS_PROXY_AGENT = createHttpsProxyAgent(process.env.npm_config_https_proxy);
  }
  function getAgent(url) {
      const parsed = new url_1.URL(url);
      const options = {};
      if (PROXY_AGENT && parsed.protocol.startsWith('http:')) {
          options.agent = PROXY_AGENT;
      }
      if (HTTPS_PROXY_AGENT && parsed.protocol.startsWith('https:')) {
          options.agent = HTTPS_PROXY_AGENT;
      }
      return options;
  }
  async function directoryExists(path) {
      try {
          const stats = await fs_1.promises.stat(path);
          return stats.isDirectory();
      }
      catch {
          return false;
      }
  }
  exports.directoryExists = directoryExists;
  async function fileExists(path) {
      try {
          const stats = await fs_1.promises.stat(path);
          return stats.isFile();
      }
      catch {
          return false;
      }
  }
  exports.fileExists = fileExists;
  