text: "use strict";
  
  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.default = void 0;
  
  var _eventsource = _interopRequireDefault(require("@sanity/eventsource"));
  
  var _rxjs = require("rxjs");
  
  var _chalk = _interopRequireDefault(require("chalk"));
  
  var _datasetNamePrompt = _interopRequireDefault(require("../../actions/dataset/datasetNamePrompt"));
  
  var _validateDatasetName = _interopRequireDefault(require("../../actions/dataset/validateDatasetName"));
  
  var _debug = _interopRequireDefault(require("../../debug"));
  
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  
  function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  
  function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  
  function _iterableToArrayLimit(arr, i) { var _i = arr && (typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]); if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  
  function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  
  function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  
  var helpText = "\nOptions\n  --detach Start the copy without waiting for it to finish\n  --attach <job-id> Attach to the running copy process to show progress\n  --skip-history Don't preserve document history on copy\n\nExamples\n  sanity dataset copy\n  sanity dataset copy <source-dataset>\n  sanity dataset copy <source-dataset> <target-dataset>\n  sanity dataset copy --skip-history <source-dataset> <target-dataset>\n  sanity dataset copy --detach <source-dataset> <target-dataset>\n  sanity dataset copy --attach <job-id>\n";
  
  var progress = url => {
    return new _rxjs.Observable(observer => {
      var progressSource = new _eventsource.default(url);
  
      function onError(error) {
        progressSource.close();
        observer.error(error);
      }
  
      function onMessage(event) {
        var data = JSON.parse(event.data);
  
        if (data.state === 'failed') {
          (0, _debug.default)("Job failed. Data: ".concat(event));
          observer.error(event);
        } else if (data.state === 'completed') {
          (0, _debug.default)("Job succeeded. Data: ".concat(event));
          onComplete();
        } else {
          (0, _debug.default)("Job progressed. Data: ".concat(event));
          observer.next(data);
        }
      }
  
      function onComplete() {
        progressSource.removeEventListener('error', onError);
        progressSource.removeEventListener('channelError', onError);
        progressSource.removeEventListener('job', onMessage);
        progressSource.removeEventListener('done', onComplete);
        progressSource.close();
        observer.complete();
      }
  
      progressSource.addEventListener('error', onError);
      progressSource.addEventListener('channelError', onError);
      progressSource.addEventListener('job', onMessage);
      progressSource.addEventListener('done', onComplete);
    });
  };
  
  var followProgress = (jobId, client, output) => {
    var spinner = output.spinner({
      text: "Copy in progress: 0%"
    }).start();
    var listenUrl = client.getUrl("jobs/".concat(jobId, "/listen"));
    (0, _debug.default)("Listening to ".concat(listenUrl));
    progress(listenUrl).subscribe({
      next: event => {
        var eventProgress = event.progress ? event.progress : 0;
        spinner.text = "Copy in progress: ".concat(eventProgress, "%");
      },
      error: () => {
        spinner.fail('There was an error copying the dataset.');
      },
      complete: () => {
        spinner.succeed("Copy finished.");
      }
    });
  };
  
  var _default = {
    name: 'copy',
    group: 'dataset',
    signature: '[SOURCE_DATASET] [TARGET_DATASET]',
    helpText,
    description: 'Copies a dataset including its assets to a new dataset',
    action: function () {
      var _action = _asyncToGenerator(function* (args, context) {
        var apiClient = context.apiClient,
            output = context.output,
            prompt = context.prompt;
        var flags = args.extOptions;
        var client = apiClient();
  
        if (flags.attach) {
          var jobId = flags.attach;
  
          if (!jobId) {
            throw new Error('Please supply a jobId');
          }
  
          followProgress(jobId, client, output);
          return;
        }
  
        var _args$argsWithoutOpti = _slicedToArray(args.argsWithoutOptions, 2),
            sourceDataset = _args$argsWithoutOpti[0],
            targetDataset = _args$argsWithoutOpti[1];
  
        var shouldSkipHistory = Boolean(flags['skip-history']);
        var nameError = sourceDataset && (0, _validateDatasetName.default)(sourceDataset);
  
        if (nameError) {
          throw new Error(nameError);
        }
  
        var existingDatasets = yield client.datasets.list().then(datasets => datasets.map(ds => ds.name));
        var sourceDatasetName = yield sourceDataset || (0, _datasetNamePrompt.default)(prompt, {
          message: 'Source dataset name:'
        });
  
        if (!existingDatasets.includes(sourceDatasetName)) {
          throw new Error("Source dataset \"".concat(sourceDatasetName, "\" doesn't exist"));
        }
  
        var targetDatasetName = yield targetDataset || (0, _datasetNamePrompt.default)(prompt, {
          message: 'Target dataset name:'
        });
  
        if (existingDatasets.includes(targetDatasetName)) {
          throw new Error("Target dataset \"".concat(targetDatasetName, "\" already exists"));
        }
  
        var err = (0, _validateDatasetName.default)(targetDatasetName);
  
        if (err) {
          throw new Error(err);
        }
  
        try {
          var response = yield client.request({
            method: 'PUT',
            uri: "/datasets/".concat(sourceDatasetName, "/copy"),
            body: {
              targetDataset: targetDatasetName,
              skipHistory: shouldSkipHistory
            }
          });
          output.print("Copying dataset ".concat(_chalk.default.green(sourceDatasetName), " to ").concat(_chalk.default.green(targetDatasetName), "..."));
  
          if (flags.detach) {
            output.print("Copy initiated.");
            output.print("\nRun:\n\n    sanity dataset copy --attach ".concat(response.jobId, "\n\nto watch attach"));
            return;
          }
  
          followProgress(response.jobId, client, output);
        } catch (error) {
          if (error.statusCode) {
            output.print("".concat(_chalk.default.red("Dataset copying failed:\n".concat(error.response.body.message)), "\n"));
          } else {
            output.print("".concat(_chalk.default.red("Dataset copying failed:\n".concat(error.message)), "\n"));
          }
        }
      });
  
      function action(_x, _x2) {
        return _action.apply(this, arguments);
      }
  
      return action;
    }()
  };
  exports.default = _default;