/*** Generated by streamline 0.10.17 (callbacks) - DO NOT EDIT ***/ var __rt=require('streamline/lib/callbacks/runtime').runtime(__filename, false),__func=__rt.__func,__cb=__rt.__cb,__catch=__rt.__catch,__tryCatch=__rt.__tryCatch; var azureCommon = require("azure-common");
















var storage = require("azure-storage");
var http = require("http");
var url = require("url");
var BlobUtilities = storage.BlobUtilities;
var FileUtilities = storage.FileUtilities;
var connectionStringParser = azureCommon.ConnectionStringParser;
var flows = require("streamline/lib/util/flows");
var os = require("os");
var fs = require("fs");
var path = require("path");
var crypto = require("crypto");
var getStorageSettings = storage.StorageServiceClient.getStorageSettings;
var util = require("util");
var utils = require("./utils");
var splitDestinationUri = require("./blobUtils").splitDestinationUri;
var utilsCore = require("./utilsCore");
var profile = require("./profile");
var validation = require("./validation");
var ExponentialRetryPolicyFilter = storage.ExponentialRetryPolicyFilter;

var __ = require("underscore");
var $ = utils.getLocaleString;




var cli = null;
var logger = null;
var progress = null;
var userAgent = null;




var restFunnel = null;




var operationTimeout = null;




var StorageUtil = {};




StorageUtil.SPACE_PARAMETER = "  ";




StorageUtil.ENV_CONNECTIONSTRING_NAME = "AZURE_STORAGE_CONNECTION_STRING";
StorageUtil.ENV_SDK_ACCOUNT_NAME = "AZURE_STORAGE_ACCOUNT";
StorageUtil.ENV_SDK_ACCOUNT_KEY = "AZURE_STORAGE_ACCESS_KEY";
StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME = "azure_storage_concurrency";
StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME = "azure_storage_timeout";
StorageUtil.DEVELOPMENT_STORAGE_ACCOUNT = "devstoreaccount1";
StorageUtil.DEVELOPMENT_STORAGE_KEY = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";




StorageUtil.AccountTypeForCreating = {
  LRS: "Standard_LRS",
  ZRS: "Standard_ZRS",
  GRS: "Standard_GRS",
  RAGRS: "Standard_RAGRS",
  PLRS: "Premium_LRS"};





StorageUtil.AccountTypeForChanging = {
  LRS: "Standard_LRS",
  GRS: "Standard_GRS",
  RAGRS: "Standard_RAGRS"};





StorageUtil.AccountKind = {
  Storage: "Storage",
  BlobStorage: "BlobStorage"};





StorageUtil.AccessTier = {
  Hot: "Hot",
  Cool: "Cool"};





StorageUtil.EncryptionService = {
  Blob: "blob"};





StorageUtil.EncryptionKeySource = {
  Storage: "Microsoft.Storage"};





StorageUtil.OperationType = {
  Blob: "blob",
  Queue: "queue",
  Table: "table",
  File: "file"};





StorageUtil.AccessType = {
  Container: "container",
  Blob: "blob",
  Queue: "queue",
  Table: "table",
  Share: "share"};





StorageUtil.AccountSasService = {
  Blob: "b",
  File: "f",
  Queue: "q",
  Table: "t"};





StorageUtil.AccountSasResourceType = {
  Service: "s",
  Container: "c",
  Object: "o"};





StorageUtil.AccountSasPermission = {
  Read: "r",
  Add: "a",
  Create: "c",
  Update: "u",
  Process: "p",
  Write: "w",
  Delete: "d",
  List: "l"};





StorageUtil.ContainerPermission = {
  Read: "r",
  Add: "a",
  Create: "c",
  Write: "w",
  Delete: "d",
  List: "l"};





StorageUtil.BlobPermission = {
  Read: "r",
  Add: "a",
  Create: "c",
  Write: "w",
  Delete: "d"};





StorageUtil.TablePermission = {
  Query: "r",
  Add: "a",
  Update: "u",
  Delete: "d"};





StorageUtil.QueuePermission = {
  Read: "r",
  Add: "a",
  Update: "u",
  Process: "p"};





StorageUtil.SharePermission = {
  Read: "r",
  Create: "c",
  Write: "w",
  Delete: "d",
  List: "l"};





StorageUtil.FilePermission = {
  Read: "r",
  Create: "c",
  Write: "w",
  Delete: "d"};





StorageUtil.SasProtocol = {
  HttpsOnly: "https",
  HttpsOrHttp: "https,http"};





StorageUtil.ListContinuationTokenArgIndex = {
  Container: 1,
  Blob: 2,
  Share: 1,
  File: 2,
  Queue: 1,
  Table: 1};





StorageUtil.PolicyOperation = {
  Create: 1,
  Set: 2,
  Delete: 3};





StorageUtil.CopyTypes = {
  CopyToBlob: 1,
  CopyToFile: 2};





StorageUtil.BlobSnapshotDeletion = {
  Include: "include",
  Only: "only"};


StorageUtil.MaxPolicyCount = 5;


StorageUtil.MaxBlockBlobSize = (((50000 * 4) * 1024) * 1024);
StorageUtil.MaxAppendBlobSize = (((50000 * 4) * 1024) * 1024);


StorageUtil.MaxPageBlobSize = (((1024 * 1024) * 1024) * 1024);
StorageUtil.MaxFileSize = (((1024 * 1024) * 1024) * 1024);




StorageUtil.init = function(azureCli) {
  cli = azureCli;
  logger = cli.output;
  var cfg = utilsCore.readConfig();
  var restConcurrency = getRestConcurrency(cfg);
  http.globalAgent.maxSockets = restConcurrency;
  restFunnel = flows.funnel(restConcurrency);
  operationTimeout = getRestOperationTimeout(cfg);

  var packagePath = path.join(__dirname, "../../package.json");
  var packageInfo = JSON.parse(fs.readFileSync(packagePath));
  userAgent = util.format("%s/%s (Mode %s) ", packageInfo.name, packageInfo.version, cfg.mode);};







StorageUtil.getValidValueFromArgument = function(value, set) {
  var key = __.find(Object.keys(set), function(testValue) {
    return (testValue.toLowerCase() === value.toLowerCase()); });

  return set[key];};








StorageUtil.StorageOperation = function(type, operation) {
  this.type = type;
  this.operation = operation;};









StorageUtil.getStorageOperation = function(serviceClient, operationType, operationName) {
  var operation = new StorageUtil.StorageOperation();
  operation.type = operationType;
  operation.operation = operationName;
  operation.service = serviceClient;
  return operation;};







StorageUtil.getBlobService = function(connection) {
  var serviceSettings = getStorageServiceSettings(connection);
  var service = null;
  if ((serviceSettings === null)) {

    service = storage.createBlobService(); }
   else if (serviceSettings._usePathStyleUri) {
    service = storage.createBlobService(connection); }
   else if (serviceSettings._sasToken) {
    service = storage.createBlobServiceWithSas(serviceSettings._blobEndpoint.primaryHost, serviceSettings._sasToken); }
   else {
    service = storage.createBlobService(serviceSettings._name, serviceSettings._key, serviceSettings._blobEndpoint.primaryHost); }   ;

  return service.withFilter(new ExponentialRetryPolicyFilter());};







StorageUtil.getTableService = function(connection) {
  var serviceSettings = getStorageServiceSettings(connection);
  var service = null;
  if ((serviceSettings === null)) {

    service = storage.createTableService(); }
   else if (serviceSettings._usePathStyleUri) {
    service = storage.createTableService(connection); }
   else if (serviceSettings._sasToken) {
    service = storage.createTableServiceWithSas(serviceSettings._tableEndpoint.primaryHost, serviceSettings._sasToken); }
   else {
    service = storage.createTableService(serviceSettings._name, serviceSettings._key, serviceSettings._tableEndpoint.primaryHost); }   ;

  return service.withFilter(new ExponentialRetryPolicyFilter());};







StorageUtil.getQueueService = function(connection) {
  var serviceSettings = getStorageServiceSettings(connection);
  var service = null;
  if ((serviceSettings === null)) {

    service = storage.createQueueService(); }
   else if (serviceSettings._usePathStyleUri) {
    service = storage.createQueueService(connection); }
   else if (serviceSettings._sasToken) {
    service = storage.createQueueServiceWithSas(serviceSettings._queueEndpoint.primaryHost, serviceSettings._sasToken); }
   else {
    service = storage.createQueueService(serviceSettings._name, serviceSettings._key, serviceSettings._queueEndpoint.primaryHost); }   ;

  return service.withFilter(new ExponentialRetryPolicyFilter());};







StorageUtil.getFileService = function(connection) {
  var serviceSettings = getStorageServiceSettings(connection);
  var service = null;
  if ((serviceSettings === null)) {

    service = storage.createFileService(); }
   else if (serviceSettings._usePathStyleUri) {
    service = storage.createFileService(connection); }
   else if (serviceSettings._sasToken) {
    service = storage.createFileServiceWithSas(serviceSettings._fileEndpoint.primaryHost, serviceSettings._sasToken); }
   else {
    service = storage.createFileService(serviceSettings._name, serviceSettings._key, serviceSettings._fileEndpoint.primaryHost); }   ;

  return service.withFilter(new ExponentialRetryPolicyFilter());};





StorageUtil.normalizeSasToken = function(sasToken) {
  if (((typeof sasToken === "string") && (sasToken.charAt(0) === "?"))) {
    sasToken = sasToken.slice(1); } ;

  return sasToken;};








StorageUtil.performStorageOperation = function StorageUtil_performStorageOperation__1(storageOperation, _) { var service, operation, definedParameterCount, operationArgs, result, __arguments = arguments; var __frame = { name: "StorageUtil_performStorageOperation__1", line: 458 }; return __func(_, this, arguments, StorageUtil_performStorageOperation__1, 1, __frame, function __$StorageUtil_performStorageOperation__1() {
    if (!storageOperation) { return _(null); } ;
    service = storageOperation.service;
    if (!service) {
      return _(new Error("Service client can't be null")); } ;


    operation = (storageOperation.operation || "");

    if ((!service[operation] || !isFunction(service[operation]))) {
      return _(("Invalid operation " + operation)); } ;



    definedParameterCount = 2;
    operationArgs = Array.prototype.slice.call(__arguments).slice(definedParameterCount, __arguments.length);

    result = null; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_performStorageOperation__1() {

          return restFunnel(__cb(_, __frame, 19, 4, __then, true), function __1(_) { var __frame = { name: "__1", line: 477 }; return __func(_, this, arguments, __1, 0, __frame, function __$__1() {

              return service[operation].apply_(__cb(_, __frame, 2, 34, function ___(__0, __1) { result = __1; _(); }, true), service, operationArgs); }); }); }); })(function ___(e, __result) { __catch(function __$StorageUtil_performStorageOperation__1() { if (e) {



            StorageUtil.endProgress();
            return _(e); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$StorageUtil_performStorageOperation__1() {

        return _(null, result); }); }); });};





StorageUtil.startProgress = function(tips) {
  if ((progress !== null)) {
    StorageUtil.endProgress(); } ;

  progress = cli.interaction.progress(tips);};





StorageUtil.endProgress = function() {
  if ((progress !== null)) {
    progress.end(); } ;

  progress = null;};





StorageUtil.setOperationTimeout = function(options) {
  if (((((options.timeoutintervalInMs === undefined) && (operationTimeout !== null)) && !isNaN(operationTimeout)) && (operationTimeout > 0))) {

    options.timeoutIntervalInMs = operationTimeout; } ;};






StorageUtil.stringToContainerAccessLevel = function(str) {
  var accessType = BlobUtilities.BlobContainerPublicAccessType;
  var accessLevel = accessType.OFF;
  if (str) {
    str = str.toLowerCase();
    switch (str) {
    case "blob": accessLevel = accessType.BLOB;
      break;
    case "container":
      accessLevel = accessType.CONTAINER;
      break;
    case "off":
      accessLevel = accessType.OFF;
      break;
      default:
      if (str) {
        throw new Error(util.format("Invalid container public access level %s", str));
      } ; break;

    }; } ;


  return accessLevel;};





StorageUtil.convertFileNameToBlobName = function(name) {
  return name.replace(/\\/gim, "/");};





StorageUtil.containerAccessLevelToString = function(accessType) {
  var publicAccessType = BlobUtilities.BlobContainerPublicAccessType;
  var str = "Off";
  switch (accessType) {
  case publicAccessType.BLOB: str = "Blob";
    break;
  case publicAccessType.CONTAINER:
    str = "Container";
    break;
  case publicAccessType.OFF:
    str = "Off";
    break;
    default:
    if (accessType) {
      throw new Error(util.format("Invalid Container public access type %s", accessType));
    } ; break;

  };

  return str;};





StorageUtil.parseKvParameter = function(str) {
  if (str) {
    return connectionStringParser.parse(str); } ;};






StorageUtil.parseKvParameterInvariant = function(str) {
  var kvPairs = { };
  if (str) {
    var pairs = str.split(";");
    for (var i = 0; (i < pairs.length); i++) {
      var pair = pairs[i];
      var key = "";
      var value = "";
      var delimiter = pair.indexOf("=");
      if ((delimiter !== -1)) {
        key = pair.substring(0, delimiter);
        if ((delimiter < (pair.length - 1))) {
          value = pair.substr((delimiter + 1)); } ;

        kvPairs[key] = value; } ; }; } ;



  return kvPairs;};





StorageUtil.isNotFoundException = function(e) {
  var notFoundErrors = ["NotFound","ResourceNotFound","ContainerNotFound","BlobNotFound","QueueNotFound","TableNotFound","ShareNotFound",];
  return notFoundErrors.some(function(error) { return (e.code === error); });};





StorageUtil.isBlobExistsException = function(e) {
  return (e.code === "BlobAlreadyExists");};





StorageUtil.isFileExistsException = function(e) {
  return (e.code === "FileAlreadyExists");};





StorageUtil.isFileNotFoundException = function(e) {
  return (e.code === "ENOENT");};





StorageUtil.recursiveMkdir = function(root, specifiedPath) {
  if (utils.isWindows()) {

    specifiedPath = specifiedPath.replace(/\//g, "\\"); } ;

  var dirs = specifiedPath.split(path.sep);
  var dirPath = (root || "");
  var dirName = "";
  for (var i = 0; (i < dirs.length); i++) {
    dirName = utils.escapeFilePath(dirs[i]);
    dirPath = path.join(dirPath, dirName);
    if (!StorageUtil.doesPathExist(dirPath)) {
      fs.mkdirSync(dirPath); } ; };


  return dirPath;};


StorageUtil.doesPathExist = function(dirPath) {
  var existFunc = (fs.existsSync || path.existsSync);
  if (path) {
    return existFunc(dirPath); } ;

  return true;};





StorageUtil.getStructureFromBlobName = function(blobName) {
  var structure = { fileName: undefined, dirName: undefined };
  if ((blobName[(blobName.length - 1)] === "/")) {
    var lastIndex = blobName.lastIndexOf("/", (blobName.length - 2));
    structure.fileName = blobName.substr((lastIndex + 1));
    structure.dirName = blobName.substr(0, lastIndex); }
   else {
    structure.fileName = path.basename(blobName);
    structure.dirName = path.dirname(blobName); } ;

  return structure;};





StorageUtil.calculateFileMd5 = function(filePath, cb) {
  var stream = fs.createReadStream(filePath);
  var digest = crypto.createHash("md5");
  stream.on("data", function(d) { digest.update(d); });
  stream.on("end", function() {
    var md5 = digest.digest("base64");
    cb(null, md5); });};






StorageUtil.formatBlobProperties = function(properties, target) {
  if (!properties) { return };

  target.contentSettings = (target.contentSettings || { });

  var propertyNames = ["contentType","contentEncoding","contentLanguage","cacheControl",];
  var getPropertyIndex = function(key) {
    for (var i = 0; (i < propertyNames.length); i++) {
      if ((propertyNames[i].toLowerCase() == key.toLowerCase())) {
        return i; } ; };


    return -1; };


  var index = -1;
  for (var item in properties) {
    index = getPropertyIndex(item);
    if ((index == -1)) {
      throw new Error(util.format($("Invalid value: %s. Options are: %s"), item, propertyNames)); } ;

    target.contentSettings[propertyNames[index]] = properties[item];
    if ((item.toLowerCase() === "contenttype")) {
      target.contentSettings["contentType"] = properties[item]; } ; };};







StorageUtil.listWithContinuation = function(listFunc, storageServiceObject, continuationTokenIndexInArg) {
  var allItems = { };
  function listCallback(error, result) {
    if (error) { throw error };

    if ((result.entries instanceof Array)) {
      if (!((allItems instanceof Array))) {
        allItems = []; } ;


      allItems = allItems.concat(result.entries); }

     else {
      for (var property in result.entries) {
        if (result.entries.hasOwnProperty(property)) {
          if (!allItems[property]) {
            allItems[property] = []; } ;


          allItems[property] = allItems[property].concat(result.entries[property]); } ; }; } ;




    if (result.continuationToken) {
      callArguments[continuationTokenIndexInArg] = result.continuationToken;
      listFunc.apply(storageServiceObject, callArguments); }
     else {
      callback(error, allItems);
      allItems = null; } ; };


  var callback = arguments[(arguments.length - 1)];
  var callArguments = Array.prototype.slice.call(arguments).slice(3, (arguments.length - 1));
  callArguments.push(listCallback);
  listFunc.apply(storageServiceObject, callArguments);};





StorageUtil.getServiceClient = function(getServiceClientFunc, options) {
  var isNameDefined = (options.accountName !== undefined);
  var isKeyDefined = (options.accountKey !== undefined);
  var isSasDefined = (options.sas !== undefined);
  var isConnectionStringDefined = (options.connectionString !== undefined);
  var isAccountDefined = (isNameDefined || isKeyDefined);
  var isUserDefined = (isAccountDefined || isSasDefined);

  if ((isConnectionStringDefined && isUserDefined)) {
    throw new Error($("Please only define one of them:\n 1. --connection-string\n 2. --account-name and --account-key\n 3. --account-name and --sas")); }
   else {
    var serviceClient = null;
    if (isConnectionStringDefined) {
      serviceClient = getServiceClientFunc(options.connectionString); }
     else if (isUserDefined) {
      if (isNameDefined) {
        if ((isKeyDefined && isSasDefined)) {
          throw new Error($("Please only define --account-key or --sas when --account-name is defined")); }
         else if (isKeyDefined) {
          var connString = util.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", options.accountName, options.accountKey);
          serviceClient = getServiceClientFunc(connString); }
         else {
          serviceClient = getServiceClientFunc(options); }  ; }

       else {
        throw new Error($("Please set --account-name and --account-key or --account-name and --sas")); } ; }

     else {

      serviceClient = getServiceClientFunc(); }  ;

    if ((options.verbose === true)) {
      serviceClient.logger.level = azureCommon.Logger.LogLevels.DEBUG; } ;

    serviceClient.on("sendingRequestEvent", sendingRequestHandler);
    return serviceClient; } ;};






StorageUtil.getSpeedPrinter = function(summary) {
  var clearBuffer = new Buffer(79);
  clearBuffer.fill(" ");
  clearBuffer = clearBuffer.toString();
  var done = false;
  return function(newline) {
    if ((logger.format().json || done)) { return };
    var tips = util.format($("Percentage: %s%% (%s/%s) Average Speed: %s Elapsed Time: %s "), summary.getCompletePercent(), summary.getCompleteSize(), summary.getTotalSize(), summary.getAverageSpeed(), summary.getElapsedSeconds());

    fs.writeSync(1, (("\r" + clearBuffer) + "\r"));
    process.stdout.write(tips);
    if (newline) {
      process.stdout.write("\n");
      done = true; } ; };};







StorageUtil.embedTransferSummary = function(properties, speedSummary) {
  var extendProperties = (properties || { });
  if (speedSummary) {
    var transferSummary = {
      totalSize: speedSummary.getTotalSize(),
      totalTime: speedSummary.getElapsedSeconds(),
      averageSpeed: speedSummary.getAverageSpeed() };

    extendProperties = __.extend(properties, { transferSummary: transferSummary }); } ;

  return extendProperties;};





StorageUtil.getStorageServiceSettings = getStorageServiceSettings;




StorageUtil.getStorageOperationDefaultOption = function() {
  var option = { };
  StorageUtil.setOperationTimeout(option);
  return option;};


StorageUtil.validateAccountSasServices = function(services) {
  validateSymbols(services, StorageUtil.AccountSasService);};


StorageUtil.validateAccountSasResourceTypes = function(resourceTypes) {
  validateSymbols(resourceTypes, StorageUtil.AccountSasResourceType);};


StorageUtil.validateIPRange = function(ipRange) {
  var regex = "^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3})(-(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3})?$";
  if ((ipRange.match(regex) === null)) {
    throw new Error("Invalid ip range format"); } ;};



StorageUtil.validateAccountSasPermissions = function(permissions) {
  validateSymbols(permissions, StorageUtil.AccountSasPermission);};


StorageUtil.getAccountSharedAccessPolicy = function(services, resourceTypes, permissions, protocol, ipRange, start, expiry) {
  var sharedAccessPolicy = { };

  if (utils.stringIsNullOrEmpty(services)) {
    throw new Error($("Services is required")); } ;

  if (utils.stringIsNullOrEmpty(resourceTypes)) {
    throw new Error($("ResourceTypes is required")); } ;

  if (utils.stringIsNullOrEmpty(permissions)) {
    throw new Error($("Permissions is required")); } ;

  if (!expiry) {
    throw new Error($("Expiry is required")); } ;


  if ((start && !__.isDate(start))) {
    throw new Error($("Start is not a valid date")); } ;

  if (!__.isDate(expiry)) {
    throw new Error($("Expiry is not a valid date")); } ;


  sharedAccessPolicy = {
    AccessPolicy: {
      Expiry: expiry } };




  var sharedAccessServices = normalizeSymbols(services, getEnumValues(StorageUtil.AccountSasService));
  sharedAccessPolicy.AccessPolicy.Services = sharedAccessServices;


  var sharedAccessResourceTypes = normalizeSymbols(resourceTypes, getEnumValues(StorageUtil.AccountSasResourceType));
  sharedAccessPolicy.AccessPolicy.ResourceTypes = sharedAccessResourceTypes;


  var sharedAccessPermissions = normalizeSymbols(permissions, getEnumValues(StorageUtil.AccountSasPermission));
  sharedAccessPolicy.AccessPolicy.Permissions = sharedAccessPermissions;

  if (protocol) {
    validation.isValidEnumValue(protocol, Object.keys(StorageUtil.SasProtocol));
    sharedAccessPolicy.AccessPolicy.Protocols = StorageUtil.SasProtocol[protocol]; } ;


  if (ipRange) {
    StorageUtil.validateIPRange(ipRange);
    sharedAccessPolicy.AccessPolicy.IPAddressOrRange = ipRange; } ;



  if (start) {
    if ((start.getTime() >= expiry.getTime())) {
      throw new Error($("The expiry time of the specified access policy should be greater than start time")); } ;

    sharedAccessPolicy.AccessPolicy.Start = start; } ;


  return sharedAccessPolicy;};


StorageUtil.generateAccountSharedAccessSignature = function(options, sharedAccessPolicy) {
  var isNameDefined = (options.accountName !== undefined);
  var isKeyDefined = (options.accountKey !== undefined);
  var isConnectionStringDefined = (options.connectionString !== undefined);
  var isAccountDefined = (isNameDefined || isKeyDefined);

  var connectionStringOrAccountName;
  var accountKey;

  if ((isConnectionStringDefined && isAccountDefined)) {
    throw new Error($("Please only define either: 1. --connection-string 2. --account-name and --account-key")); } ;


  if (isConnectionStringDefined) {
    connectionStringOrAccountName = options.connectionString; }
   else if (isAccountDefined) {
    if ((isNameDefined && isKeyDefined)) {
      connectionStringOrAccountName = options.accountName;
      accountKey = options.accountKey; }
     else {
      throw new Error($("Please set --account-name and --account-key")); } ; }

   else {

    connectionStringOrAccountName = undefined;
    accountKey = undefined; }  ;


  return storage.generateAccountSharedAccessSignature(connectionStringOrAccountName, accountKey, sharedAccessPolicy);};


StorageUtil.validatePermissions = function(accessType, permissions) {
  switch (accessType) {
  case StorageUtil.AccessType.Container: validateSymbols(permissions, StorageUtil.ContainerPermission);
    break;
  case StorageUtil.AccessType.Blob:
    validateSymbols(permissions, StorageUtil.BlobPermission);
    break;
  case StorageUtil.AccessType.Table:
    validateSymbols(permissions, StorageUtil.TablePermission);
    break;
  case StorageUtil.AccessType.Queue:
    validateSymbols(permissions, StorageUtil.QueuePermission);
    break;
  case StorageUtil.AccessType.Share:
    validateSymbols(permissions, StorageUtil.SharePermission);
    break;
  case StorageUtil.AccessType.File:
    validateSymbols(permissions, StorageUtil.FilePermission);
    break;
  };};




StorageUtil.getSharedAccessPolicy = function(accessType, permissions, protocol, ipRange, start, expiry, tableField, policyId) {
  var sharedAccessPolicy = { };
  if (policyId) {
    if (((permissions || expiry) || start)) {
      throw new Error($("Permissions, start and expiry cannot be specified with a stored policy")); } ;

    sharedAccessPolicy.Id = policyId; }
   else {
    if (utils.stringIsNullOrEmpty(permissions)) {
      throw new Error($("Permissions or policy ID is required")); } ;

    if (!expiry) {
      throw new Error($("Expiry or policy ID is required")); } ;

    if ((start && !__.isDate(start))) {
      throw new Error($("Start is not a valid date")); } ;

    if (!__.isDate(expiry)) {
      throw new Error($("Expiry is not a valid date")); } ;


    sharedAccessPolicy = {
      AccessPolicy: {
        Expiry: expiry } };




    var sharedAccessPermissions = pickupValidPermission(permissions, accessType);
    sharedAccessPolicy.AccessPolicy.Permissions = sharedAccessPermissions;

    if (protocol) {
      validation.isValidEnumValue(protocol, Object.keys(StorageUtil.SasProtocol));
      sharedAccessPolicy.AccessPolicy.Protocols = StorageUtil.SasProtocol[protocol]; } ;


    if (ipRange) {
      StorageUtil.validateIPRange(ipRange);
      sharedAccessPolicy.AccessPolicy.IPAddressOrRange = ipRange; } ;



    if (start) {
      if ((start.getTime() >= expiry.getTime())) {
        throw new Error($("The expiry time of the specified access policy should be greater than start time")); } ;

      sharedAccessPolicy.AccessPolicy.Start = start; } ; } ;




  if (tableField) {
    if ((tableField.startRk && !tableField.startPk)) {
      throw new Error($("Starting partition key must accompany starting row key")); } ;

    if ((tableField.endRk && !tableField.endPk)) {
      throw new Error($("Ending partition key must accompany ending row key")); } ;


    if (tableField.startPk) {
      sharedAccessPolicy.AccessPolicy.StartPk = tableField.startPk; } ;

    if (tableField.startRk) {
      sharedAccessPolicy.AccessPolicy.StartRk = tableField.startRk; } ;

    if (tableField.endPk) {
      sharedAccessPolicy.AccessPolicy.EndPk = tableField.endPk; } ;

    if (tableField.endRk) {
      sharedAccessPolicy.AccessPolicy.EndRk = tableField.endRk; } ; } ;



  return sharedAccessPolicy;};







StorageUtil.opConcurrency = -1;





StorageUtil.threadsInOperation = 5;





StorageUtil.getStorageAccountOptions = function(options) {
  return {
    accountName: options.accountName,
    accountKey: options.accountKey,
    connectionString: options.connectionString,
    sas: options.sas };};








StorageUtil.isValidRetention = function(value) {
  return (validation.isInt(value) >= 0);};







StorageUtil.createPolicy = function StorageUtil_createPolicy__2(policySettings, _) { var __frame = { name: "StorageUtil_createPolicy__2", line: 1116 }; return __func(_, this, arguments, StorageUtil_createPolicy__2, 1, __frame, function __$StorageUtil_createPolicy__2() {
    return operateOnPolicy(policySettings, StorageUtil.PolicyOperation.Create, __cb(_, __frame, 1, 9, _, true)); });};







StorageUtil.setPolicy = function StorageUtil_setPolicy__3(policySettings, _) { var __frame = { name: "StorageUtil_setPolicy__3", line: 1125 }; return __func(_, this, arguments, StorageUtil_setPolicy__3, 1, __frame, function __$StorageUtil_setPolicy__3() {
    return operateOnPolicy(policySettings, StorageUtil.PolicyOperation.Set, __cb(_, __frame, 1, 9, _, true)); });};







StorageUtil.deletePolicy = function StorageUtil_deletePolicy__4(policySettings, _) { var __frame = { name: "StorageUtil_deletePolicy__4", line: 1134 }; return __func(_, this, arguments, StorageUtil_deletePolicy__4, 1, __frame, function __$StorageUtil_deletePolicy__4() {
    return operateOnPolicy(policySettings, StorageUtil.PolicyOperation.Delete, __cb(_, __frame, 1, 9, _, true)); });};








StorageUtil.selectPolicy = function StorageUtil_selectPolicy__5(policySettings, _) { var policies, names, index, i, result; var __frame = { name: "StorageUtil_selectPolicy__5", line: 1144 }; return __func(_, this, arguments, StorageUtil_selectPolicy__5, 1, __frame, function __$StorageUtil_selectPolicy__5() {
    policies = { };
    names = [];
    index = -1;
    StorageUtil.startProgress(policySettings.tips); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_selectPolicy__5() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_selectPolicy__5() {

                return StorageUtil.performStorageOperation(policySettings.getAclOperation, __cb(_, __frame, 6, 27, function ___(__0, __1) { policies = __1.signedIdentifiers;

                  names = Object.keys(policies);
                  for (i = 0; (i < names.length); i++) {
                    normalizePolicy(policies[names[i]], policySettings.accessType);
                    if ((policySettings.policyName && (names[i] === policySettings.policyName))) {
                      index = i;
                      break; } ; }; __then(); }, true), policySettings.resourceName, policySettings.storageOptions); }); })(function ___(e, __result) { __catch(function __$StorageUtil_selectPolicy__5() { if (e) {



                  if (e.reason) {
                    return _(new Error((util.format($("%s\rReason: %s"), e.message, e.reason)))); }
                   else {
                    return _(e); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$StorageUtil_selectPolicy__5() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_selectPolicy__5() {


            StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_selectPolicy__5() {


        if ((policySettings.policyName && (index < 0))) {
          return _(new Error(util.format($("The policy %s doesn't exist"), policySettings.policyName))); } ;


        result = { };

        if (policySettings.policyName) {
          result[names[index]] = policies[names[index]]; }
         else {
          result = policies; } ;

        return _(null, result); }); }); });};





StorageUtil.showPolicyResults = function(policies) {
  logger.table(Object.keys(policies), function(row, item) {
    var policy = policies[item];
    row.cell($("Policy Name"), item);
    row.cell($("Start"), (((policy && policy.Start)) ? policy.Start : ""));
    row.cell($("Expiry"), (((policy && policy.Expiry)) ? policy.Expiry : ""));
    row.cell($("Permissions"), (((policy && policy.Permissions)) ? policy.Permissions : "")); });};






StorageUtil.fetchBasenameAndDirname = function(filePath) {
  var result = { };
  result.basename = path.basename(filePath);
  result.dirname = path.dirname(filePath);
  if ((!result.dirname || (result.dirname === "."))) {
    result.dirname = ""; } ;


  if (!result.basename) {
    result.basename = ""; } ;


  return result;};





StorageUtil.normalizePath = function(filePath) {
  var result = path.join("", __.without(filePath.replace("\\", "/").split("/"), "").join("/"));
  if ((result === ".")) {
    result = ""; } ;


  return result;};








function operateOnPolicy(policySettings, operation, _) { var policies, newPolicy; var __frame = { name: "operateOnPolicy", line: 1233 }; return __func(_, this, arguments, operateOnPolicy, 2, __frame, function __$operateOnPolicy() {
    policies = { };
    StorageUtil.startProgress(policySettings.tips); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$operateOnPolicy() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$operateOnPolicy() {

                return StorageUtil.performStorageOperation(policySettings.getAclOperation, __cb(_, __frame, 4, 27, function ___(__0, __1) { policies = __1.signedIdentifiers;

                  newPolicy = generatePolicy(policySettings.policyName, policySettings.policyOptions.start, policySettings.policyOptions.expiry, policySettings.policyOptions.permissions);
                  modifyPolicySet(newPolicy, policies, policySettings.accessType, operation);
                  return StorageUtil.performStorageOperation(policySettings.setAclOperation, __cb(_, __frame, 8, 16, __then, true), policySettings.resourceName, policies, policySettings.storageOptions); }, true), policySettings.resourceName, policySettings.storageOptions); }); })(function ___(e, __result) { __catch(function __$operateOnPolicy() { if (e) {

                  if (e.reason) {
                    return _(new Error((util.format($("%s\rReason: %s"), e.message, e.reason)))); }
                   else {
                    return _(e); } ; __then(); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$operateOnPolicy() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$operateOnPolicy() {


            StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$operateOnPolicy() {

        return _(null, policies); }); }); });};





function generatePolicy(policyName, start, expiry, permissions) {
  var policy = { };
  policy[policyName] = { };


  policy[policyName].Start = (start ? (((start === StorageUtil.SPACE_PARAMETER) ? StorageUtil.SPACE_PARAMETER : utils.parseDateTime(start))) : "");
  policy[policyName].Expiry = (expiry ? (((expiry === StorageUtil.SPACE_PARAMETER) ? StorageUtil.SPACE_PARAMETER : utils.parseDateTime(expiry))) : "");

  if (((((start && expiry) && __.isDate(policy[policyName].Start)) && __.isDate(policy[policyName].Expiry)) && (policy[policyName].Start.getTime() >= policy[policyName].Expiry.getTime()))) {
    throw new Error($("The expiry time of the specified access policy should be greater than start time")); } ;



  if ((permissions === StorageUtil.SPACE_PARAMETER)) {
    policy[policyName].Permissions = StorageUtil.SPACE_PARAMETER; }
   else {
    var sharedAccessPermissions = removeRedundantSymbol(permissions);
    if (!utils.stringIsNullOrEmpty(sharedAccessPermissions)) {
      policy[policyName].Permissions = sharedAccessPermissions; }
     else {
      policy[policyName].Permissions = " "; } ; } ;



  return policy;};





function normalizePolicy(policy, accessType) {
  if (!policy.Start) {
    policy.Start = ""; } ;

  if (!policy.Expiry) {
    policy.Expiry = ""; } ;

  if (!policy.Permissions) {
    policy.Permissions = " "; }
   else {
    policy.Permissions = pickupValidPermission(policy.Permissions, accessType); } ;};






function modifyPolicySet(newPolicy, existingPolicies, accessType, operation) {
  var index = -1;
  var names = Object.keys(existingPolicies);
  var newPolicyName = Object.keys(newPolicy)[0];
  newPolicy = newPolicy[newPolicyName];

  for (var i = 0; (i < names.length); i++) {
    normalizePolicy(existingPolicies[names[i]], accessType);
    if ((newPolicyName === names[i])) {
      index = i; } ; };



  var nameOfPolicyToOperate = names[index];
  if ((operation === StorageUtil.PolicyOperation.Create)) {
    if ((index >= 0)) {
      throw new Error(util.format($("The policy %s already exists"), newPolicyName)); }
     else if ((names.length >= StorageUtil.MaxPolicyCount)) {
      throw new Error(util.format($("A maximum of %s access policies may be set"), StorageUtil.MaxPolicyCount)); }
     else {
      existingPolicies[newPolicyName] = newPolicy; }  ; }

   else if ((operation === StorageUtil.PolicyOperation.Set)) {
    if ((index >= 0)) {
      if (__.isDate(newPolicy.Start)) {
        existingPolicies[nameOfPolicyToOperate].Start = newPolicy.Start; }
       else if ((newPolicy.Start === StorageUtil.SPACE_PARAMETER)) {
        existingPolicies[nameOfPolicyToOperate].Start = ""; }  ;

      if (__.isDate(newPolicy.Expiry)) {
        existingPolicies[nameOfPolicyToOperate].Expiry = newPolicy.Expiry; }
       else if ((newPolicy.Expiry === StorageUtil.SPACE_PARAMETER)) {
        existingPolicies[nameOfPolicyToOperate].Expiry = ""; }  ;

      if ((newPolicy.Permissions === StorageUtil.SPACE_PARAMETER)) {
        existingPolicies[nameOfPolicyToOperate].Permissions = " ";
        existingPolicies[nameOfPolicyToOperate].Permission = " "; }
       else if ((newPolicy.Permissions != " ")) {
        existingPolicies[nameOfPolicyToOperate].Permissions = newPolicy.Permissions;

        existingPolicies[nameOfPolicyToOperate].Permission = newPolicy.Permissions; }  ; }

     else {
      throw new Error(util.format($("The policy %s doesn't exist"), newPolicyName)); } ; }

   else if ((operation === StorageUtil.PolicyOperation.Delete)) {
    if ((index >= 0)) {
      delete existingPolicies[nameOfPolicyToOperate]; }
     else {
      throw new Error(util.format($("The policy %s doesn't exist"), newPolicyName)); } ; }   ;};




function getEnumValues(enumObj) {
  var values = [];
  for (var prop in enumObj) {
    values.push(enumObj[prop]); };

  return values;};






function pickupValidPermission(permissions, accessType) {
  var input = permissions.toLowerCase();

  var permissionValues = function(type) {
    switch (type) {
    case StorageUtil.AccessType.Container: return getEnumValues(StorageUtil.ContainerPermission);
    case StorageUtil.AccessType.Blob:
      return getEnumValues(StorageUtil.BlobPermission);
    case StorageUtil.AccessType.Table:
      return getEnumValues(StorageUtil.TablePermission);
    case StorageUtil.AccessType.Queue:
      return getEnumValues(StorageUtil.QueuePermission);
    case StorageUtil.AccessType.Share:
      return getEnumValues(StorageUtil.SharePermission);
    case StorageUtil.AccessType.File:
      return getEnumValues(StorageUtil.FilePermission);
    }; };



  var allowedPermissions = permissionValues(accessType);

  return normalizeSymbols(input, allowedPermissions);};


function normalizeSymbols(symbols, allowOps) {
  var output = "";
  for (var index = 0; (index < allowOps.length); index++) {
    if ((symbols.indexOf(allowOps[index]) != -1)) {
      output += allowOps[index]; } ; };



  return output;};





function removeRedundantSymbol(symbols) {
  var result = "";
  var length = (symbols ? symbols.length : 0);
  for (var index = 0; (index < length); index++) {
    var symbol = symbols[index].toLowerCase();
    if ((-1 == result.indexOf(symbol))) {
      result += symbol; } ; };


  return result;};








function validateSymbols(symbols, allowOps) {
  if ((symbols === StorageUtil.SPACE_PARAMETER)) {
    return; } ;


  var values = getEnumValues(allowOps);
  for (var index = 0; (index < symbols.length); index++) {
    var symbol = symbols[index];
    validation.isValidEnumValue(symbol, values); };};








function isFunction(func) {
  return (typeof func === "function");};







function getStorageServiceSettings(connection) {
  var connectionString;

  if ((typeof connection === "string")) {
    connectionString = adjustConnectionStringWithEnvironment(connection); }
   else if (connection) {
    var options = connection;
    if (options.connectionString) {
      connectionString = adjustConnectionStringWithEnvironment(options.connectionString); }
     else {
      if ((options.accountName && options.accountKey)) {
        connectionString = getFullConnectionString(options.accountName, options.accountKey); }
       else {
        var sas = (options.sas || options.sourceSas);
        sas = StorageUtil.normalizeSasToken(sas);
        if ((options.accountName && sas)) {
          return getStorageServiceSettingWithSAS(options.accountName, sas); } ; } ; } ; }  ;





  if (!connectionString) {
    connectionString = adjustConnectionStringWithEnvironment(process.env[StorageUtil.ENV_CONNECTIONSTRING_NAME]); } ;

  if (!connectionString) {
    if ((!process.env[StorageUtil.ENV_SDK_ACCOUNT_NAME] || !process.env[StorageUtil.ENV_SDK_ACCOUNT_KEY])) {
      throw new Error($("Please set the storage account parameters or one of the following two environment variables to use the storage command.\n  1. AZURE_STORAGE_CONNECTION_STRING\n  2. AZURE_STORAGE_ACCOUNT and AZURE_STORAGE_ACCESS_KEY")); }
     else {
      connectionString = getFullConnectionString(process.env[StorageUtil.ENV_SDK_ACCOUNT_NAME], process.env[StorageUtil.ENV_SDK_ACCOUNT_KEY]); } ; } ;


  return getStorageSettings(connectionString);};





function getStorageServiceEndpointSuffix() {
  var uri;


  if ((__.keys(profile.current.subscriptions).length > 0)) {
    uri = utils.createStorageClient(profile.current.getSubscription()).baseUri; }
   else {
    uri = profile.current.environments.AzureCloud.storageEndpointSuffix;
    return uri.substring((uri.indexOf(".") + 1), uri.length); } ;


  var urlObj = url.parse(uri);
  if ((urlObj.host && validation.isURL(urlObj.host))) {
    return urlObj.host; }
   else {
    return uri.substring((uri.indexOf(".") + 1), uri.length); } ;};






function getFullConnectionString(accountName, accountKey, protocol) {
  if (((accountName === StorageUtil.DEVELOPMENT_STORAGE_ACCOUNT) && (accountKey === StorageUtil.DEVELOPMENT_STORAGE_KEY))) {
    return storage.generateDevelopmentStorageCredentials(); } ;


  var endpointSuffix = getStorageServiceEndpointSuffix();
  var getPrimaryEndpoint = function(type) {
    return getEndpoint(protocol, accountName, type, endpointSuffix).primaryHost; };

  var template = "DefaultEndpointsProtocol=%s;AccountName=%s;AccountKey=%s;BlobEndpoint=%s;TableEndpoint=%s;QueueEndpoint=%s;FileEndpoint=%s";
  var blobEndpoint = getPrimaryEndpoint(StorageUtil.OperationType.Blob);
  var tableEndpoint = getPrimaryEndpoint(StorageUtil.OperationType.Table);
  var queueEndpoint = getPrimaryEndpoint(StorageUtil.OperationType.Queue);
  var fileEndpoint = getPrimaryEndpoint(StorageUtil.OperationType.File);

  protocol = (protocol || "https");
  return util.format(template, protocol, accountName, accountKey, blobEndpoint, tableEndpoint, queueEndpoint, fileEndpoint);};





function adjustConnectionStringWithEnvironment(connectionString) {
  if ((typeof connectionString !== "string")) {
    return connectionString; } ;


  if (getStorageSettings(connectionString)._usePathStyleUri) {
    return connectionString; } ;


  if ((connectionString.indexOf("Endpoint=") !== -1)) {
    return connectionString; } ;


  var accountName;
  var accountKey;
  var protocol;
  var pairs = connectionString.split(";");
  for (var index = 0; (index < pairs.length); index++) {
    var pair = pairs[index];
    if ((pair.length === 0)) {
      continue; } ;


    if ((pair.indexOf("AccountName=") !== -1)) {
      accountName = pair.substring((pair.indexOf("=") + 1)); }
     else if ((pair.indexOf("AccountKey=") !== -1)) {
      accountKey = pair.substring((pair.indexOf("=") + 1)); }
     else if ((pair.indexOf("DefaultEndpointsProtocol=") !== -1)) {
      protocol = pair.substring((pair.indexOf("=") + 1)); }   ;


    if (((accountName && accountKey) && protocol)) {
      break; } ; };



  return getFullConnectionString(accountName, accountKey, protocol);};








function getStorageServiceSettingWithSAS(accountName, sasToken) {
  var endpointSuffix = getStorageServiceEndpointSuffix();
  var getEndpointLite = function(type) {
    return getEndpoint(null, accountName, type, endpointSuffix); };


  var serviceSettings = { };
  serviceSettings._name = accountName;
  serviceSettings._sasToken = sasToken;
  serviceSettings._blobEndpoint = getEndpointLite(StorageUtil.OperationType.Blob);
  serviceSettings._tableEndpoint = getEndpointLite(StorageUtil.OperationType.Table);
  serviceSettings._queueEndpoint = getEndpointLite(StorageUtil.OperationType.Queue);
  serviceSettings._fileEndpoint = getEndpointLite(StorageUtil.OperationType.File);

  return serviceSettings;};










function getEndpoint(protocol, accountName, type, endpointSuffix) {
  protocol = (protocol || "https:");
  if ((protocol.lastIndexOf(":") !== (protocol.length - 1))) {
    protocol += ":"; } ;


  var host = { };
  if (validation.isURL(endpointSuffix)) {
    host.primaryHost = ((((protocol + "//") + endpointSuffix) + "/") + accountName); }
   else {
    host.primaryHost = ((((((protocol + "//") + accountName) + ".") + type) + ".") + endpointSuffix); } ;


  return host;};





StorageUtil.acquireLease = function StorageUtil_acquireLease__6(serviceClient, leaseOptions, _) { var leaseResult; var __frame = { name: "StorageUtil_acquireLease__6", line: 1624 }; return __func(_, this, arguments, StorageUtil_acquireLease__6, 2, __frame, function __$StorageUtil_acquireLease__6() {


    return cli.interaction.promptIfNotGiven($("Container name: "), leaseOptions.container, __cb(_, __frame, 3, 43, function ___(__0, __1) { leaseOptions.container = __1; return (function __$StorageUtil_acquireLease__6(__then) {

        if (leaseOptions.forBlob) {
          return cli.interaction.promptIfNotGiven($("Blob name: "), leaseOptions.blob, __cb(_, __frame, 6, 40, function ___(__0, __2) { leaseOptions.blob = __2; __then(); }, true)); } else { __then(); } ; })(function __$StorageUtil_acquireLease__6() {


        if (leaseOptions.proposedLeaseId) {
          validation.isUUID(leaseOptions.proposedLeaseId); } ; return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_acquireLease__6() {



              StorageUtil.startProgress((leaseOptions.tips || ""));
              return StorageUtil.performStorageOperation(leaseOptions.operation, __cb(_, __frame, 15, 30, function ___(__0, __3) { leaseResult = __3; _(null, null, true); }, true), leaseOptions.container, leaseOptions.blob, leaseOptions); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_acquireLease__6() {

                StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_acquireLease__6() {


            cli.interaction.formatOutput(leaseResult, function(outputData) {
              var output = [outputData,];
              logger.table(output, function(row, item) {
                row.cell($("Container"), item.container);
                if (leaseOptions.forBlob) {
                  row.cell($("Blob"), item.blob); } ;

                row.cell($("Lease ID"), item.id);
                row.cell($("Etag"), item.etag);
                row.cell($("Last Modified"), item.lastModified); }); }); _(); }); }); }); }, true)); });};







StorageUtil.renewLease = function StorageUtil_renewLease__7(serviceClient, leaseOptions, _) { var leaseResult; var __frame = { name: "StorageUtil_renewLease__7", line: 1661 }; return __func(_, this, arguments, StorageUtil_renewLease__7, 2, __frame, function __$StorageUtil_renewLease__7() {


    return cli.interaction.promptIfNotGiven($("Container name: "), leaseOptions.container, __cb(_, __frame, 3, 43, function ___(__0, __1) { leaseOptions.container = __1; return (function __$StorageUtil_renewLease__7(__then) {

        if (leaseOptions.forBlob) {
          return cli.interaction.promptIfNotGiven($("Blob name: "), leaseOptions.blob, __cb(_, __frame, 6, 40, function ___(__0, __2) { leaseOptions.blob = __2; __then(); }, true)); } else { __then(); } ; })(function __$StorageUtil_renewLease__7() {


        return cli.interaction.promptIfNotGiven($("Lease ID: "), leaseOptions.leaseId, __cb(_, __frame, 9, 41, function ___(__0, __3) { leaseOptions.leaseId = __3;
          validation.isUUID(leaseOptions.leaseId); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_renewLease__7() {


                StorageUtil.startProgress((leaseOptions.tips || ""));
                return StorageUtil.performStorageOperation(leaseOptions.operation, __cb(_, __frame, 14, 30, function ___(__0, __4) { leaseResult = __4; _(null, null, true); }, true), leaseOptions.container, leaseOptions.blob, leaseOptions.leaseId, leaseOptions); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_renewLease__7() {

                  StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_renewLease__7() {


              cli.interaction.formatOutput(leaseResult, function(outputData) {
                var output = [outputData,];
                logger.table(output, function(row, item) {
                  row.cell($("Container"), item.container);
                  if (leaseOptions.forBlob) {
                    row.cell($("Blob"), item.blob); } ;

                  row.cell($("Lease ID"), item.id);
                  row.cell($("Etag"), item.etag);
                  row.cell($("Last Modified"), item.lastModified); }); }); _(); }); }); }, true)); }); }, true)); });};







StorageUtil.changeLease = function StorageUtil_changeLease__8(serviceClient, leaseOptions, _) { var leaseResult; var __frame = { name: "StorageUtil_changeLease__8", line: 1697 }; return __func(_, this, arguments, StorageUtil_changeLease__8, 2, __frame, function __$StorageUtil_changeLease__8() {


    return cli.interaction.promptIfNotGiven($("Container name: "), leaseOptions.container, __cb(_, __frame, 3, 43, function ___(__0, __1) { leaseOptions.container = __1; return (function __$StorageUtil_changeLease__8(__then) {

        if (leaseOptions.forBlob) {
          return cli.interaction.promptIfNotGiven($("Blob name: "), leaseOptions.blob, __cb(_, __frame, 6, 40, function ___(__0, __2) { leaseOptions.blob = __2; __then(); }, true)); } else { __then(); } ; })(function __$StorageUtil_changeLease__8() {


        return cli.interaction.promptIfNotGiven($("Lease ID: "), leaseOptions.leaseId, __cb(_, __frame, 9, 41, function ___(__0, __3) { leaseOptions.leaseId = __3;
          validation.isUUID(leaseOptions.leaseId);

          return cli.interaction.promptIfNotGiven($("Proposed lease ID: "), leaseOptions.proposedId, __cb(_, __frame, 12, 44, function ___(__0, __4) { leaseOptions.proposedId = __4;
            validation.isUUID(leaseOptions.proposedId); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_changeLease__8() {


                  StorageUtil.startProgress((leaseOptions.tips || ""));
                  return StorageUtil.performStorageOperation(leaseOptions.operation, __cb(_, __frame, 17, 30, function ___(__0, __5) { leaseResult = __5; _(null, null, true); }, true), leaseOptions.container, leaseOptions.blob, leaseOptions.leaseId, leaseOptions.proposedId, leaseOptions); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_changeLease__8() {

                    StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_changeLease__8() {


                cli.interaction.formatOutput(leaseResult, function(outputData) {
                  var output = [outputData,];
                  logger.table(output, function(row, item) {
                    row.cell($("Container"), item.container);
                    if (leaseOptions.forBlob) {
                      row.cell($("Blob"), item.blob); } ;

                    row.cell($("Lease ID"), item.id);
                    row.cell($("Etag"), item.etag);
                    row.cell($("Last Modified"), item.lastModified); }); }); _(); }); }); }, true)); }, true)); }); }, true)); });};







StorageUtil.releaseLease = function StorageUtil_releaseLease__9(serviceClient, leaseOptions, _) { var leaseResult; var __frame = { name: "StorageUtil_releaseLease__9", line: 1736 }; return __func(_, this, arguments, StorageUtil_releaseLease__9, 2, __frame, function __$StorageUtil_releaseLease__9() {


    return cli.interaction.promptIfNotGiven($("Container name: "), leaseOptions.container, __cb(_, __frame, 3, 43, function ___(__0, __1) { leaseOptions.container = __1; return (function __$StorageUtil_releaseLease__9(__then) {

        if (leaseOptions.forBlob) {
          return cli.interaction.promptIfNotGiven($("Blob name: "), leaseOptions.blob, __cb(_, __frame, 6, 40, function ___(__0, __2) { leaseOptions.blob = __2; __then(); }, true)); } else { __then(); } ; })(function __$StorageUtil_releaseLease__9() {


        return cli.interaction.promptIfNotGiven($("Lease ID: "), leaseOptions.leaseId, __cb(_, __frame, 9, 41, function ___(__0, __3) { leaseOptions.leaseId = __3;
          validation.isUUID(leaseOptions.leaseId); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_releaseLease__9() {


                StorageUtil.startProgress((leaseOptions.tips || ""));
                return StorageUtil.performStorageOperation(leaseOptions.operation, __cb(_, __frame, 14, 30, function ___(__0, __4) { leaseResult = __4; _(null, null, true); }, true), leaseOptions.container, leaseOptions.blob, leaseOptions.leaseId, leaseOptions); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_releaseLease__9() {

                  StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_releaseLease__9() {


              cli.interaction.formatOutput(leaseResult, function(outputData) {
                var output = [outputData,];
                logger.table(output, function(row, item) {
                  row.cell($("Container"), item.container);
                  if (leaseOptions.forBlob) {
                    row.cell($("Blob"), item.blob); } ;

                  row.cell($("Etag"), item.etag);
                  row.cell($("Last Modified"), item.lastModified); }); }); _(); }); }); }, true)); }); }, true)); });};







StorageUtil.breakLease = function StorageUtil_breakLease__10(serviceClient, leaseOptions, _) { var leaseResult; var __frame = { name: "StorageUtil_breakLease__10", line: 1771 }; return __func(_, this, arguments, StorageUtil_breakLease__10, 2, __frame, function __$StorageUtil_breakLease__10() {


    return cli.interaction.promptIfNotGiven($("Container name: "), leaseOptions.container, __cb(_, __frame, 3, 43, function ___(__0, __1) { leaseOptions.container = __1; return (function __$StorageUtil_breakLease__10(__then) {

        if (leaseOptions.forBlob) {
          return cli.interaction.promptIfNotGiven($("Blob name: "), leaseOptions.blob, __cb(_, __frame, 6, 40, function ___(__0, __2) { leaseOptions.blob = __2; __then(); }, true)); } else { __then(); } ; })(function __$StorageUtil_breakLease__10() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_breakLease__10() {



              StorageUtil.startProgress((leaseOptions.tips || ""));
              return StorageUtil.performStorageOperation(leaseOptions.operation, __cb(_, __frame, 11, 30, function ___(__0, __3) { leaseResult = __3; _(null, null, true); }, true), leaseOptions.container, leaseOptions.blob, leaseOptions); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_breakLease__10() {

                StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_breakLease__10() {


            cli.interaction.formatOutput(leaseResult, function(outputData) {
              var output = [outputData,];
              logger.table(output, function(row, item) {
                row.cell($("Container"), item.container);
                if (leaseOptions.forBlob) {
                  row.cell($("Blob"), item.blob); } ;

                row.cell($("Remaining Time"), item.time);
                row.cell($("Etag"), item.etag);
                row.cell($("Last Modified"), item.lastModified); }); }); _(); }); }); }); }, true)); });};







StorageUtil.startAsyncCopy = function StorageUtil_startAsyncCopy__11(startCopyParams, destContainerOrShare, options, _) { var isCopyToBlob, source, sourceContainerOrShare, sourceBlobOrFile, embeddedSas, embeddedQueryParameterOtherThanSas, sourceResource, index, sasToken, destBlobOrFile, destOption, destServiceClient, startOperation, tips, copyOp, retry, error, filePath, result; var __frame = { name: "StorageUtil_startAsyncCopy__11", line: 1804 }; return __func(_, this, arguments, StorageUtil_startAsyncCopy__11, 3, __frame, function __$StorageUtil_startAsyncCopy__11() {
    isCopyToBlob = isCopyDestinationBlob(startCopyParams.type);


    return getSourceUri(startCopyParams.copyType, options, __cb(_, __frame, 4, 15, function ___(__0, __2) { source = __2;
      sourceContainerOrShare = (options.isSourceBlobDefined ? options.sourceContainer : ((options.isSourceFileDefined ? options.sourceShare : undefined)));

      sourceBlobOrFile = (options.isSourceBlobDefined ? options.sourceBlob : ((options.isSourceFileDefined ? options.sourcePath : undefined)));



      embeddedSas = false;
      embeddedQueryParameterOtherThanSas = false;
      sourceResource = splitDestinationUri(source);
      sourceResource.containerOrShare = sourceResource.container;
      sourceResource.blobOrFilePath = sourceResource.blobName;

      if (!sourceContainerOrShare) {
        sourceContainerOrShare = sourceResource.containerOrShare; } ;


      if (!sourceBlobOrFile) {
        if (!sourceResource.blobOrFilePath) {
          if (options.isSourceBlobDefined) {
            return _(new Error($("The source blob is invalid"))); } else {
            if (options.isSourceFileDefined) {
              return _(new Error($("The source file is invalid"))); } ; } ; }

         else {

          index = sourceResource.blobOrFilePath.lastIndexOf("?");
          if ((index !== -1)) {
            embeddedSas = (sourceResource.blobOrFilePath.lastIndexOf("sv=") > index);
            if (!embeddedSas) {
              embeddedQueryParameterOtherThanSas = true; } ;

            sourceResource.blobOrFilePath = sourceResource.blobOrFilePath.substring(0, index); } ;

          sourceBlobOrFile = decodeURIComponent(sourceResource.blobOrFilePath); } ; }

       else {
        if ((sourceResource.blobOrFilePath.lastIndexOf("?") !== -1)) {
          embeddedQueryParameterOtherThanSas = true; } ; } ;




      return getSourceSASToken(startCopyParams, sourceContainerOrShare, sourceBlobOrFile, embeddedSas, options, __cb(_, __frame, 47, 17, function ___(__0, __3) { sasToken = __3;
        if (sasToken) {
          if (embeddedQueryParameterOtherThanSas) {
            source += (("&" + sasToken)); }
           else {
            source += (("?" + sasToken)); } ; } ;





        if (isCopyToBlob) {
          destBlobOrFile = (options.destBlob ? options.destBlob : sourceBlobOrFile); }
         else {
          if (options.destPath) {
            destBlobOrFile = options.destPath; }
           else {
            return _(new Error($("--dest-path is required when copying to a file"))); } ; } ;


        return cli.interaction.promptIfNotGiven((isCopyToBlob ? $("Destination container name: ") : $("Destination share name: ")), destContainerOrShare, __cb(_, __frame, 67, 41, function ___(__0, __4) { destContainerOrShare = __4;
          if (!destContainerOrShare) {
            if (isCopyToBlob) {
              return _(new Error($("The destination container name is required"))); }
             else {
              return _(new Error($("The destination share name is required"))); } ; } ;




          destOption = getDestAccountOptions(options);
          destServiceClient = StorageUtil.getServiceClient((isCopyToBlob ? StorageUtil.getBlobService : StorageUtil.getFileService), options);
          startOperation = startCopyParams.getStartOperation(destServiceClient);
          tips = util.format((isCopyToBlob ? $("Start copying blob %s") : $("Start copying file %s")), source);



          StorageUtil.startProgress(tips); return (function ___(__break) { var __more; var __loop = __cb(_, __frame, 0, 0, function __$StorageUtil_startAsyncCopy__11() { __more = false;
              var __13 = ((retry === true) || (retry === undefined)); if (__13) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_startAsyncCopy__11() { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_startAsyncCopy__11() {


                            if ((((retry === undefined) && !options.quiet) && isCopyToBlob)) {
                              startOperation.options.accessConditions = { "if-none-match": "*" }; }
                             else {
                              startOperation.options.accessConditions = { }; } ; return (function __$StorageUtil_startAsyncCopy__11(__then) {


                              if (isCopyToBlob) {
                                retry = false;
                                return StorageUtil.performStorageOperation(startOperation.operation, __cb(_, __frame, 96, 29, function ___(__0, __7) { copyOp = __7; __then(); }, true), source, destContainerOrShare, destBlobOrFile, startOperation.options); } else { return (function __$StorageUtil_startAsyncCopy__11(_) {

                                  var __1 = ((retry === undefined) && !options.quiet); if (!__1) { return _(null, __1); } ; return startCopyParams.checkExistenceOperation(destContainerOrShare, destBlobOrFile, destOption, __cb(_, __frame, 98, 69, _, true)); })(__cb(_, __frame, -1803, 17, function ___(__0, __8) { return (function __$StorageUtil_startAsyncCopy__11(__then) { if (__8) {
                                      error = new Error();
                                      error.code = "FileAlreadyExists";
                                      return _(error); } else { __then(); } ; })(function __$StorageUtil_startAsyncCopy__11() {


                                    retry = false;
                                    filePath = StorageUtil.normalizePath(destBlobOrFile);
                                    result = StorageUtil.fetchBasenameAndDirname(filePath);
                                    return StorageUtil.performStorageOperation(startOperation.operation, __cb(_, __frame, 107, 29, function ___(__0, __9) { copyOp = __9; __then(); }, true), source, destContainerOrShare, result.dirname, result.basename, startOperation.options); }); }, true)); } ; })(__then); }); })(function ___(e, __result) { __catch(function __$StorageUtil_startAsyncCopy__11() { if (e) { return (function __$StorageUtil_startAsyncCopy__11(__then) {


                                if (isCopyToBlob) { return (function __$StorageUtil_startAsyncCopy__11(__then) {
                                    if (StorageUtil.isBlobExistsException(e)) {
                                      return cli.interaction.confirm(util.format($("Do you want to overwrite the existing blob %s in the container %s? (Y/N) "), destBlobOrFile, destContainerOrShare), __cb(_, __frame, 112, 34, function ___(__0, __5) { retry = __5;
                                        e.message = util.format($("The blob %s in the container %s already exists "), destBlobOrFile, destContainerOrShare); __then(); }, true)); } else { __then(); } ; })(__then); } else { return (function __$StorageUtil_startAsyncCopy__11(__then) {


                                    if (StorageUtil.isFileExistsException(e)) {
                                      return cli.interaction.confirm(util.format($("Do you want to overwrite the existing file %s in the share %s? (Y/N) "), destBlobOrFile, destContainerOrShare), __cb(_, __frame, 117, 34, function ___(__0, __6) { retry = __6;
                                        e.message = util.format($("The file %s in the share %s already exists "), destBlobOrFile, destContainerOrShare); __then(); }, true)); } else { __then(); } ; })(__then); } ; })(function __$StorageUtil_startAsyncCopy__11() {


                                if (!retry) {
                                  return _(e); } ; __then(); }); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$StorageUtil_startAsyncCopy__11() { _(null, null, true); }); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_startAsyncCopy__11() {


                        if (!retry) {
                          StorageUtil.endProgress(); } ; __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_startAsyncCopy__11() { while (__more) { __loop(); }; __more = true; }); }); } else { __break(); } ; }); do { __loop(); } while (__more); __more = true; })(function __$StorageUtil_startAsyncCopy__11() {




            cli.interaction.formatOutput(copyOp, function(outputData) {
              var output = [outputData,];
              logger.table(output, function(row, item) {
                row.cell($("Copy ID"), item.copy.id);
                row.cell($("Status"), item.copy.status); }); }); _(); }); }, true)); }, true)); }, true)); });};







StorageUtil.showAsyncCopy = function StorageUtil_showAsyncCopy__12(showCopyParams, containerOrShare, blobOrFilePath, options, _) { var isCopyToBlob, destOption, blobOrFileProps; var __frame = { name: "StorageUtil_showAsyncCopy__12", line: 1947 }; return __func(_, this, arguments, StorageUtil_showAsyncCopy__12, 4, __frame, function __$StorageUtil_showAsyncCopy__12() {
    isCopyToBlob = isCopyDestinationBlob(showCopyParams.type);

    return cli.interaction.promptIfNotGiven((isCopyToBlob ? $("Destination container: ") : $("Destination share: ")), containerOrShare, __cb(_, __frame, 3, 37, function ___(__0, __1) { containerOrShare = __1;
      return cli.interaction.promptIfNotGiven((isCopyToBlob ? $("Destination blob: ") : $("Destination file path: ")), blobOrFilePath, __cb(_, __frame, 4, 35, function ___(__0, __2) { blobOrFilePath = __2;

        destOption = getDestAccountOptions(options);
        return showCopyParams.getProperties(containerOrShare, blobOrFilePath, destOption, __cb(_, __frame, 7, 39, function ___(__0, __3) { blobOrFileProps = __3;

          if (((blobOrFileProps.copy === undefined) || (blobOrFileProps.copy.id === undefined))) {
            return _(new Error((isCopyToBlob ? $("Can not find copy task on the specified blob") : $("Can not find copy task on the specified file")))); }
           else {
            cli.interaction.formatOutput(blobOrFileProps, function(outputData) {
              var output = [outputData,];
              logger.table(output, function(row, item) {
                row.cell($("Copy ID"), item.copy.id);
                row.cell($("Progress"), item.copy.progress);
                row.cell($("Status"), item.copy.status);
                if (item.copy.statusDescription) {
                  row.cell($("Description"), item.copy.statusDescription); } ; }); }); } ; _(); }, true)); }, true)); }, true)); });};









StorageUtil.stopAsyncCopy = function StorageUtil_stopAsyncCopy__13(stopCopyParam, containerOrShare, blobOrFilePath, copyid, options, _) { var isCopyToBlob, serviceClient, stopOperation, tips, stopOp, filePath, result; var __frame = { name: "StorageUtil_stopAsyncCopy__13", line: 1976 }; return __func(_, this, arguments, StorageUtil_stopAsyncCopy__13, 5, __frame, function __$StorageUtil_stopAsyncCopy__13() {
    isCopyToBlob = isCopyDestinationBlob(stopCopyParam.type);

    return cli.interaction.promptIfNotGiven((isCopyToBlob ? $("Destination container: ") : $("Destination share: ")), containerOrShare, __cb(_, __frame, 3, 37, function ___(__0, __1) { containerOrShare = __1;
      return cli.interaction.promptIfNotGiven((isCopyToBlob ? $("Destination blob: ") : $("Destination file path: ")), blobOrFilePath, __cb(_, __frame, 4, 35, function ___(__0, __2) { blobOrFilePath = __2;
        return cli.interaction.promptIfNotGiven($("Copy ID: "), copyid, __cb(_, __frame, 5, 27, function ___(__0, __3) { copyid = __3;


          serviceClient = StorageUtil.getServiceClient((isCopyToBlob ? StorageUtil.getBlobService : StorageUtil.getFileService), options);
          stopOperation = stopCopyParam.getStopOperation(serviceClient);

          if (isCopyToBlob) {
            tips = util.format($("Stop copying blob %s in container %s of copy id %s"), blobOrFilePath, containerOrShare, copyid); }
           else {
            tips = util.format($("Stop copying file %s in share %s of copy id %s"), blobOrFilePath, containerOrShare, copyid); } ;



          StorageUtil.startProgress(tips); return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$StorageUtil_stopAsyncCopy__13() { return (function __$StorageUtil_stopAsyncCopy__13(__then) {

                  if (isCopyToBlob) {
                    return StorageUtil.performStorageOperation(stopOperation.operation, __cb(_, __frame, 21, 27, function ___(__0, __4) { stopOp = __4; __then(); }, true), containerOrShare, blobOrFilePath, copyid, stopOperation.options); } else {

                    filePath = StorageUtil.normalizePath(blobOrFilePath);
                    result = StorageUtil.fetchBasenameAndDirname(filePath);
                    return StorageUtil.performStorageOperation(stopOperation.operation, __cb(_, __frame, 25, 27, function ___(__0, __5) { stopOp = __5; __then(); }, true), containerOrShare, result.dirname, result.basename, copyid, stopOperation.options); } ; })(function __$StorageUtil_stopAsyncCopy__13() { _(null, null, true); }); }); })(function ___(__e, __r, __cont) { (function ___(__then) { __tryCatch(_, function __$StorageUtil_stopAsyncCopy__13() {


                  StorageUtil.endProgress(); __then(); }); })(function ___() { __tryCatch(_, function ___() { if (__cont) { __then(); } else { _(__e, __r); }; }); }); }); })(function ___() { __tryCatch(_, function __$StorageUtil_stopAsyncCopy__13() {


              if (isCopyToBlob) {
                logger.info(util.format($("Copying blob %s to container %s has been stopped successfully"), blobOrFilePath, containerOrShare)); }
               else {
                logger.info(util.format($("Copying file %s to share %s has been stopped successfully"), blobOrFilePath, containerOrShare)); } ; _(); }); }); }, true)); }, true)); }, true)); });};






StorageUtil.getStartCopyParameters = function(copyType, sourceUri, options) {
  options.type = copyType;

  checkCopyOptions(sourceUri, options);

  var getStartOperation = function(serviceClient) {
    var operationInfo = { };
    if ((copyType == StorageUtil.CopyTypes.CopyToBlob)) {
      operationInfo.operation = StorageUtil.getStorageOperation(serviceClient, StorageUtil.OperationType.Blob, "startCopyBlob"); }
     else {
      operationInfo.operation = StorageUtil.getStorageOperation(serviceClient, StorageUtil.OperationType.File, "startCopyFile"); } ;

    operationInfo.options = StorageUtil.getStorageOperationDefaultOption();
    operationInfo.options.sourceLeaseId = options.sourceLease;
    operationInfo.options.leaseId = options.destLease;
    return operationInfo; };


  var getAclOperation = function(serviceClient) {
    var operationInfo = { };
    if (options.isSourceBlobDefined) {
      operationInfo.operation = StorageUtil.getStorageOperation(serviceClient, StorageUtil.OperationType.Blob, "getContainerAcl"); }
     else {
      operationInfo.operation = StorageUtil.getStorageOperation(serviceClient, StorageUtil.OperationType.File, "getShareAcl"); } ;

    operationInfo.options = StorageUtil.getStorageOperationDefaultOption();
    return operationInfo; };


  var startCopyParameters = {
    type: copyType,
    getStartOperation: getStartOperation,
    getAclOperation: getAclOperation,
    checkExistenceOperation: null };


  return startCopyParameters;};





function checkCopyOptions(sourceUri, options) {
  options.sourceUri = sourceUri;
  options.isSourceUriDefined = sourceUri;
  options.isSourceBlobDefined = (options.sourceContainer || options.sourceBlob);
  options.isSourceFileDefined = (options.sourceShare || options.sourcePath);

  var wrongOption = (((options.isSourceUriDefined && ((options.isSourceBlobDefined || options.isSourceFileDefined)))) || ((options.isSourceBlobDefined && options.isSourceFileDefined)));
  if (wrongOption) {
    throw new Error($("Please only define one of them: 1. --source-uri. 2. --source-container and --source-blob. 3. --source-share and --source--path")); } ;};






function getDestAccountOptions(options) {
  var isNameDefined = (options.destAccountName !== undefined);
  var isKeyDefined = (options.destAccountKey !== undefined);
  var isSasDefined = (options.destSas !== undefined);
  var isConnectionStringDefined = (options.destConnectionString !== undefined);
  var isAccountDefined = (isNameDefined || isKeyDefined);
  var isUserDefined = (isAccountDefined || isSasDefined);
  var destOptions = options;

  if ((isConnectionStringDefined && isUserDefined)) {
    throw new Error($("Please only define one of them: 1. --dest-connection-string. 2. --dest-account-name and --dest-account-key. 3. --dest-account-name and --dest-sas")); }
   else {
    if (isConnectionStringDefined) {
      destOptions.connectionString = options.destConnectionString; }
     else if (isUserDefined) {
      if (isNameDefined) {
        if ((isSasDefined && isKeyDefined)) {
          throw new Error($("Please only define --dest-account-key or --dest-sas when --dest-account-name is defined")); }
         else if (isKeyDefined) {
          destOptions.connectionString = util.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s", options.destAccountName, options.destAccountKey); }
         else {
          destOptions.accountName = options.destAccountName;
          destOptions.sas = options.destSas;
          delete destOptions.accountKey;
          delete destOptions.connectionString; }  ; }

       else {
        throw new Error($("Please set --dest-account-name and --dest-account-key or --dest-account-name and --dest-sas")); } ; }  ;




    if (destOptions.connectionString) {
      delete destOptions.accountName;
      delete destOptions.accountKey; } ; } ;



  return destOptions;};





function getSourceUri(type, options, _) { var isSourceDefined, source, host, settings, sourceContainerOrShare, sourceBlobOrFilePath, encode; var __frame = { name: "getSourceUri", line: 2118 }; return __func(_, this, arguments, getSourceUri, 2, __frame, function __$getSourceUri() {
    if (options.isSourceUriDefined) {
      return _(null, options.sourceUri); } ;


    isSourceDefined = (options.isSourceBlobDefined || options.isSourceFileDefined); return (function __$getSourceUri(__then) {


      if (!isSourceDefined) {
        return cli.interaction.promptIfNotGiven($("Source URI: "), source, __cb(_, __frame, 9, 29, function ___(__0, __1) { source = __1; __then(); }, true)); } else {


        settings = getStorageServiceSettings(options); return (function __$getSourceUri(__then) {

          if (options.isSourceBlobDefined) {
            host = settings._blobEndpoint.primaryHost;
            if (!host) {
              return _(new Error($("The blob endpoint is invalid"))); } ; return (function __$getSourceUri(__then) {


              if (!options.sourceContainer) {
                return cli.interaction.promptIfNotGiven($("Source container: "), options.sourceContainer, __cb(_, __frame, 21, 50, function ___(__0, __2) { options.sourceContainer = __2; __then(); }, true)); } else { return (function __$getSourceUri(__then) {
                  if (!options.sourceBlob) {
                    return cli.interaction.promptIfNotGiven($("Source blob: "), options.sourceBlob, __cb(_, __frame, 23, 45, function ___(__0, __3) { options.sourceBlob = __3; __then(); }, true)); } else { __then(); } ; })(__then); } ; })(__then); } else { return (function __$getSourceUri(__then) {

              if (options.isSourceFileDefined) {
                host = settings._fileEndpoint.primaryHost;
                if (!host) {
                  return _(new Error($("The file endpoint is invalid"))); } ; return (function __$getSourceUri(__then) {


                  if (!options.sourceShare) {
                    return cli.interaction.promptIfNotGiven($("Source share: "), options.sourceShare, __cb(_, __frame, 32, 46, function ___(__0, __4) { options.sourceShare = __4; __then(); }, true)); } else { return (function __$getSourceUri(__then) {
                      if (!options.sourceBlob) {
                        return cli.interaction.promptIfNotGiven($("Source file path: "), options.sourcePath, __cb(_, __frame, 34, 45, function ___(__0, __5) { options.sourcePath = __5; __then(); }, true)); } else { __then(); } ; })(__then); } ; })(__then); } else { __then(); } ; })(__then); } ; })(function __$getSourceUri() {



          if ((host.lastIndexOf("/") !== (host.length - 1))) {
            source = (host + "/"); }
           else {
            source = host; } ;


          sourceContainerOrShare = (options.isSourceBlobDefined ? options.sourceContainer : options.sourceShare);
          sourceBlobOrFilePath = (options.isSourceBlobDefined ? options.sourceBlob : options.sourcePath);
          if ((sourceContainerOrShare !== "$root")) {
            source += ((sourceContainerOrShare + "/")); } ;


          encode = function(name) {
            var value = encodeURIComponent(name);
            value = value.replace(/%2F/g, "/");
            value = value.replace(/%5C/g, "/");
            value = value.replace(/\+/g, "%20");
            return value; };


          if ((sourceBlobOrFilePath[0] === "/")) {
            sourceBlobOrFilePath = sourceBlobOrFilePath.slice(1); } ;


          source += encode(sourceBlobOrFilePath);

          if (options.snapshot) {
            source += ("?snapshot=" + encode(options.snapshot)); } ; __then(); }); } ; })(function __$getSourceUri() {


      return _(null, source); }); });};





function getSourceSASToken(getSourceSASParams, sourceContainerOrShare, sourceBlobOrFilePath, embeddedSas, options, _) { var sasToken, isNameDefined, isKeyDefined, isConnectionStringDefined, sourcebServiceClient, aclOperation, permission, criteria, sharedAccessPolicy, filePath, result; var __frame = { name: "getSourceSASToken", line: 2192 }; return __func(_, this, arguments, getSourceSASToken, 5, __frame, function __$getSourceSASToken() {
    sasToken = (embeddedSas ? undefined : ((options.sourceSas || options.sasToken))); return (function __$getSourceSASToken(__then) {
      if (sasToken) {
        isNameDefined = (options.accountName !== undefined);
        isKeyDefined = (options.accountKey !== undefined);
        isConnectionStringDefined = (options.connectionString !== undefined);
        if ((isConnectionStringDefined || ((isNameDefined && isKeyDefined)))) {
          return _(new Error($("Please only define one of them: 1. --connection-string. 2 --account-name and --account-key 3. --account-name and --source-sas"))); } ;

        sasToken = StorageUtil.normalizeSasToken(sasToken); __then(); } else { return (function __$getSourceSASToken(__then) {
          if ((!embeddedSas && !options.isSourceUriDefined)) { return (function ___(__then) { (function ___(_) { __tryCatch(_, function __$getSourceSASToken() {


                  sourcebServiceClient = StorageUtil.getServiceClient((options.isSourceBlobDefined ? StorageUtil.getBlobService : StorageUtil.getFileService), options); __then(); }); })(function ___(e, __result) { __catch(function __$getSourceSASToken() { if (e) {


                    return _(null, sasToken); } else { _(null, __result); } ; }, _); }); })(function ___() { __tryCatch(_, function __$getSourceSASToken() {


                aclOperation = getSourceSASParams.getAclOperation(sourcebServiceClient);
                return StorageUtil.performStorageOperation(aclOperation.operation, __cb(_, __frame, 20, 33, function ___(__0, __1) { permission = __1;

                  criteria = (options.isSourceBlobDefined ? BlobUtilities.BlobContainerPublicAccessType.OFF : FileUtilities.SharePublicAccessType.OFF);
                  if ((criteria == permission.publicAccessLevel)) {

                    sharedAccessPolicy = {
                      AccessPolicy: {
                        Permissions: BlobUtilities.SharedAccessPermissions.READ,
                        Expiry: azureCommon.date.daysFromNow(7) } };



                    if (options.isSourceBlobDefined) {
                      sasToken = sourcebServiceClient.generateSharedAccessSignature(sourceContainerOrShare, sourceBlobOrFilePath, sharedAccessPolicy); }
                     else {
                      filePath = StorageUtil.normalizePath(sourceBlobOrFilePath);
                      result = StorageUtil.fetchBasenameAndDirname(filePath);
                      sasToken = sourcebServiceClient.generateSharedAccessSignature(sourceContainerOrShare, result.dirname, result.basename, sharedAccessPolicy); } ;

                    if (!sasToken) {
                      return _(new Error($("The source blob or file is not accessible"))); } ; } ; __then(); }, true), sourceContainerOrShare, aclOperation.options); }); }); } else { __then(); } ; })(__then); } ; })(function __$getSourceSASToken() {



      return _(null, sasToken); }); });};


function isCopyDestinationBlob(type) {
  return (type === StorageUtil.CopyTypes.CopyToBlob);};





function getRestOperationTimeout(cfg) {
  var radix = 10;
  var definedTimeout = parseInt(cfg[StorageUtil.OPERATION_TIMEOUT_CONFIG_KEY_NAME], radix);
  if ((isNaN(definedTimeout) || (definedTimeout <= 0))) {
    return null; }
   else {
    return definedTimeout; } ;};






function getRestConcurrency(cfg) {
  var radix = 10;
  var definedConcurrency = parseInt(cfg[StorageUtil.CONCURRENTCY_CONFIG_KEY_NAME], radix);
  if ((isNaN(definedConcurrency) || (definedConcurrency === 0))) {
    return getDefaultRestConcurrency(); }
   else {
    return definedConcurrency; } ;};






function getDefaultRestConcurrency() {
  var cpuCount = os.cpus().length;

  var asyncTasksPerCoreMultiplier = 1;
  return (cpuCount * asyncTasksPerCoreMultiplier);};





function sendingRequestHandler(webresource) {
  var headerName = "user-agent";
  var originalUserAgent = webresource.headers[headerName];


  if ((originalUserAgent.indexOf(userAgent) === -1)) {
    webresource.withHeader(headerName, (userAgent + originalUserAgent)); } ;};



module.exports = StorageUtil;
