VICE / ModuleTests / Azure / node_modules / @azure / storage-queue / dist / index.js
index.js
Raw
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var coreHttp = require('@azure/core-http');
var crypto = require('crypto');
var logger$1 = require('@azure/logger');
var abortController = require('@azure/abort-controller');
var os = require('os');
var coreTracing = require('@azure/core-tracing');
var tslib = require('tslib');
require('@azure/core-paging');

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value
 * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the
 * values are set, this should be serialized with toString and set as the permissions field on an
 * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but
 * the order of the permissions is particular and this class guarantees correctness.
 */
class AccountSASPermissions {
    constructor() {
        /**
         * Permission to read resources granted.
         */
        this.read = false;
        /**
         * Permission to write resources granted.
         */
        this.write = false;
        /**
         * Permission to delete queues and messages granted.
         */
        this.delete = false;
        /**
         * Permission to list queues granted.
         */
        this.list = false;
        /**
         * Permission to add messages, table entities, and append to blobs granted.
         */
        this.add = false;
        /**
         * Permission to create queues, blobs and files granted.
         */
        this.create = false;
        /**
         * Permissions to update messages and table entities granted.
         */
        this.update = false;
        /**
         * Permission to get and delete messages granted.
         */
        this.process = false;
    }
    /**
     * Parse initializes the AccountSASPermissions fields from a string.
     *
     * @param permissions -
     */
    static parse(permissions) {
        const accountSASPermissions = new AccountSASPermissions();
        for (const c of permissions) {
            switch (c) {
                case "r":
                    accountSASPermissions.read = true;
                    break;
                case "w":
                    accountSASPermissions.write = true;
                    break;
                case "d":
                    accountSASPermissions.delete = true;
                    break;
                case "l":
                    accountSASPermissions.list = true;
                    break;
                case "a":
                    accountSASPermissions.add = true;
                    break;
                case "c":
                    accountSASPermissions.create = true;
                    break;
                case "u":
                    accountSASPermissions.update = true;
                    break;
                case "p":
                    accountSASPermissions.process = true;
                    break;
                default:
                    throw new RangeError(`Invalid permission character: ${c}`);
            }
        }
        return accountSASPermissions;
    }
    /**
     * Produces the SAS permissions string for an Azure Storage account.
     * Call this method to set AccountSASSignatureValues Permissions field.
     *
     * Using this method will guarantee the resource types are in
     * an order accepted by the service.
     *
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
     *
     */
    toString() {
        // The order of the characters should be as specified here to ensure correctness:
        // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
        // Use a string array instead of string concatenating += operator for performance
        const permissions = [];
        if (this.read) {
            permissions.push("r");
        }
        if (this.write) {
            permissions.push("w");
        }
        if (this.delete) {
            permissions.push("d");
        }
        if (this.list) {
            permissions.push("l");
        }
        if (this.add) {
            permissions.push("a");
        }
        if (this.create) {
            permissions.push("c");
        }
        if (this.update) {
            permissions.push("u");
        }
        if (this.process) {
            permissions.push("p");
        }
        return permissions.join("");
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value
 * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the
 * values are set, this should be serialized with toString and set as the resources field on an
 * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but
 * the order of the resources is particular and this class guarantees correctness.
 */
class AccountSASResourceTypes {
    constructor() {
        /**
         * Permission to access service level APIs granted.
         */
        this.service = false;
        /**
         * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted.
         */
        this.container = false;
        /**
         * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted.
         */
        this.object = false;
    }
    /**
     * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an
     * Error if it encounters a character that does not correspond to a valid resource type.
     *
     * @param resourceTypes -
     */
    static parse(resourceTypes) {
        const accountSASResourceTypes = new AccountSASResourceTypes();
        for (const c of resourceTypes) {
            switch (c) {
                case "s":
                    accountSASResourceTypes.service = true;
                    break;
                case "c":
                    accountSASResourceTypes.container = true;
                    break;
                case "o":
                    accountSASResourceTypes.object = true;
                    break;
                default:
                    throw new RangeError(`Invalid resource type: ${c}`);
            }
        }
        return accountSASResourceTypes;
    }
    /**
     * Converts the given resource types to a string.
     *
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
     *
     */
    toString() {
        const resourceTypes = [];
        if (this.service) {
            resourceTypes.push("s");
        }
        if (this.container) {
            resourceTypes.push("c");
        }
        if (this.object) {
            resourceTypes.push("o");
        }
        return resourceTypes.join("");
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value
 * to true means that any SAS which uses these permissions will grant access to that service. Once all the
 * values are set, this should be serialized with toString and set as the services field on an
 * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but
 * the order of the services is particular and this class guarantees correctness.
 */
class AccountSASServices {
    constructor() {
        /**
         * Permission to access blob resources granted.
         */
        this.blob = false;
        /**
         * Permission to access file resources granted.
         */
        this.file = false;
        /**
         * Permission to access queue resources granted.
         */
        this.queue = false;
        /**
         * Permission to access table resources granted.
         */
        this.table = false;
    }
    /**
     * Creates an {@link AccountSASServices} from the specified services string. This method will throw an
     * Error if it encounters a character that does not correspond to a valid service.
     *
     * @param services -
     */
    static parse(services) {
        const accountSASServices = new AccountSASServices();
        for (const c of services) {
            switch (c) {
                case "b":
                    accountSASServices.blob = true;
                    break;
                case "f":
                    accountSASServices.file = true;
                    break;
                case "q":
                    accountSASServices.queue = true;
                    break;
                case "t":
                    accountSASServices.table = true;
                    break;
                default:
                    throw new RangeError(`Invalid service character: ${c}`);
            }
        }
        return accountSASServices;
    }
    /**
     * Converts the given services to a string.
     *
     */
    toString() {
        const services = [];
        if (this.blob) {
            services.push("b");
        }
        if (this.table) {
            services.push("t");
        }
        if (this.queue) {
            services.push("q");
        }
        if (this.file) {
            services.push("f");
        }
        return services.join("");
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Generate SasIPRange format string. For example:
 *
 * "8.8.8.8" or "1.1.1.1-255.255.255.255"
 *
 * @param ipRange -
 */
function ipRangeToString(ipRange) {
    return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start;
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
const SDK_VERSION = "12.7.0";
const SERVICE_VERSION = "2020-10-02";
/**
 * The OAuth scope to use with Azure Storage.
 */
const StorageOAuthScopes = "https://storage.azure.com/.default";
const URLConstants = {
    Parameters: {
        FORCE_BROWSER_NO_CACHE: "_",
        SIGNATURE: "sig",
        TIMEOUT: "timeout"
    }
};
const HeaderConstants = {
    AUTHORIZATION: "authorization",
    AUTHORIZATION_SCHEME: "Bearer",
    CONTENT_ENCODING: "content-encoding",
    CONTENT_LANGUAGE: "content-language",
    CONTENT_LENGTH: "content-length",
    CONTENT_MD5: "content-md5",
    CONTENT_TYPE: "content-type",
    COOKIE: "Cookie",
    DATE: "date",
    IF_MATCH: "if-match",
    IF_MODIFIED_SINCE: "if-modified-since",
    IF_NONE_MATCH: "if-none-match",
    IF_UNMODIFIED_SINCE: "if-unmodified-since",
    PREFIX_FOR_STORAGE: "x-ms-",
    RANGE: "Range",
    USER_AGENT: "User-Agent",
    X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id",
    X_MS_COPY_SOURCE: "x-ms-copy-source",
    X_MS_DATE: "x-ms-date"
};
const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;
  AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;
  QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;`;
const StorageQueueLoggingAllowedHeaderNames = [
    "Access-Control-Allow-Origin",
    "Cache-Control",
    "Content-Length",
    "Content-Type",
    "Date",
    "Request-Id",
    "traceparent",
    "Transfer-Encoding",
    "User-Agent",
    "x-ms-client-request-id",
    "x-ms-date",
    "x-ms-error-code",
    "x-ms-request-id",
    "x-ms-return-client-request-id",
    "x-ms-version",
    "x-ms-approximate-messages-count",
    "x-ms-popreceipt",
    "x-ms-time-next-visible"
];
const StorageQueueLoggingAllowedQueryParameters = [
    "comp",
    "maxresults",
    "rscc",
    "rscd",
    "rsce",
    "rscl",
    "rsct",
    "se",
    "si",
    "sip",
    "sp",
    "spr",
    "sr",
    "srt",
    "ss",
    "st",
    "sv",
    "include",
    "marker",
    "prefix",
    "messagettl",
    "numofmessages",
    "peekonly",
    "popreceipt",
    "visibilitytimeout"
];

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const packageName = "azure-storage-queue";
const packageVersion = "12.7.0";
class StorageClientContext extends coreHttp.ServiceClient {
    /**
     * Initializes a new instance of the StorageClientContext class.
     * @param url The URL of the service account, queue or message that is the target of the desired
     *            operation.
     * @param options The parameter options
     */
    constructor(url, options) {
        if (url === undefined) {
            throw new Error("'url' cannot be null");
        }
        // Initializing default values for options
        if (!options) {
            options = {};
        }
        if (!options.userAgent) {
            const defaultUserAgent = coreHttp.getDefaultUserAgentValue();
            options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`;
        }
        super(undefined, options);
        this.requestContentType = "application/json; charset=utf-8";
        this.baseUri = options.endpoint || "{url}";
        // Parameter assignments
        this.url = url;
        // Assigning values to Constant parameters
        this.version = options.version || "2020-10-02";
    }
}

/**
 * Append a string to URL path. Will remove duplicated "/" in front of the string
 * when URL path ends with a "/".
 *
 * @param url - Source URL string
 * @param name - String to be appended to URL
 * @returns An updated URL string
 */
function appendToURLPath(url, name) {
    const urlParsed = coreHttp.URLBuilder.parse(url);
    let path = urlParsed.getPath();
    path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name;
    urlParsed.setPath(path);
    return urlParsed.toString();
}
/**
 * Set URL parameter name and value. If name exists in URL parameters, old value
 * will be replaced by name key. If not provide value, the parameter will be deleted.
 *
 * @param url - Source URL string
 * @param name - Parameter name
 * @param value - Parameter value
 * @returns An updated URL string
 */
function setURLParameter(url, name, value) {
    const urlParsed = coreHttp.URLBuilder.parse(url);
    urlParsed.setQueryParameter(name, value);
    return urlParsed.toString();
}
/**
 * Set URL host.
 *
 * @param url - Source URL string
 * @param host - New host string
 * @returns An updated URL string
 */
function setURLHost(url, host) {
    const urlParsed = coreHttp.URLBuilder.parse(url);
    urlParsed.setHost(host);
    return urlParsed.toString();
}
/**
 * Gets URL path from an URL string.
 *
 * @param url - Source URL string
 * @returns The path part of the given URL string.
 */
function getURLPath(url) {
    const urlParsed = coreHttp.URLBuilder.parse(url);
    return urlParsed.getPath();
}
/**
 * Gets URL query key value pairs from an URL string.
 *
 * @param url -
 * @returns query key value string pairs from the given URL string.
 */
function getURLQueries(url) {
    let queryString = coreHttp.URLBuilder.parse(url).getQuery();
    if (!queryString) {
        return {};
    }
    queryString = queryString.trim();
    queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString;
    let querySubStrings = queryString.split("&");
    querySubStrings = querySubStrings.filter((value) => {
        const indexOfEqual = value.indexOf("=");
        const lastIndexOfEqual = value.lastIndexOf("=");
        return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1);
    });
    const queries = {};
    for (const querySubString of querySubStrings) {
        const splitResults = querySubString.split("=");
        const key = splitResults[0];
        const value = splitResults[1];
        queries[key] = value;
    }
    return queries;
}
function getProxyUriFromDevConnString(connectionString) {
    // Development Connection String
    // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key
    let proxyUri = "";
    if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) {
        // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri
        const matchCredentials = connectionString.split(";");
        for (const element of matchCredentials) {
            if (element.trim().startsWith("DevelopmentStorageProxyUri=")) {
                proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1];
            }
        }
    }
    return proxyUri;
}
/**
 *
 * @param connectionString - Account connection string.
 * @param argument - property to get value from the connection string.
 * @returns Value of the property specified in argument.
 */
function getValueInConnString(connectionString, argument) {
    const elements = connectionString.split(";");
    for (const element of elements) {
        if (element.trim().startsWith(argument)) {
            return element.trim().match(argument + "=(.*)")[1];
        }
    }
    return "";
}
/**
 * Extracts the parts of an Azure Storage account connection string.
 *
 * @param connectionString - Connection string.
 * @returns String key value pairs of the storage account's url and credentials.
 */
function extractConnectionStringParts(connectionString) {
    let proxyUri = "";
    if (connectionString.startsWith("UseDevelopmentStorage=true")) {
        // Development connection string
        proxyUri = getProxyUriFromDevConnString(connectionString);
        connectionString = DevelopmentConnectionString;
    }
    // Matching QueueEndpoint in the Account connection string
    let queueEndpoint = getValueInConnString(connectionString, "QueueEndpoint");
    // Slicing off '/' at the end if exists
    // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end)
    queueEndpoint = queueEndpoint.endsWith("/") ? queueEndpoint.slice(0, -1) : queueEndpoint;
    if (connectionString.search("DefaultEndpointsProtocol=") !== -1 &&
        connectionString.search("AccountKey=") !== -1) {
        // Account connection string
        let defaultEndpointsProtocol = "";
        let accountName = "";
        let accountKey = Buffer.from("accountKey", "base64");
        let endpointSuffix = "";
        // Get account name and key
        accountName = getValueInConnString(connectionString, "AccountName");
        accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64");
        if (!queueEndpoint) {
            // QueueEndpoint is not present in the Account connection string
            // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.queue.${endpointSuffix}`
            defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol");
            const protocol = defaultEndpointsProtocol.toLowerCase();
            if (protocol !== "https" && protocol !== "http") {
                throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'");
            }
            endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix");
            if (!endpointSuffix) {
                throw new Error("Invalid EndpointSuffix in the provided Connection String");
            }
            queueEndpoint = `${defaultEndpointsProtocol}://${accountName}.queue.${endpointSuffix}`;
        }
        if (!accountName) {
            throw new Error("Invalid AccountName in the provided Connection String");
        }
        else if (accountKey.length === 0) {
            throw new Error("Invalid AccountKey in the provided Connection String");
        }
        return {
            kind: "AccountConnString",
            url: queueEndpoint,
            accountName,
            accountKey,
            proxyUri
        };
    }
    else {
        // SAS connection string
        const accountSas = getValueInConnString(connectionString, "SharedAccessSignature");
        const accountName = getAccountNameFromUrl(queueEndpoint);
        if (!queueEndpoint) {
            throw new Error("Invalid QueueEndpoint in the provided SAS Connection String");
        }
        else if (!accountSas) {
            throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String");
        }
        return { kind: "SASConnString", url: queueEndpoint, accountName, accountSas };
    }
}
/**
 * Rounds a date off to seconds.
 *
 * @param date -
 * @param withMilliseconds - If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned;
 *                                          If false, YYYY-MM-DDThh:mm:ssZ will be returned.
 * @returns Date string in ISO8061 format, with or without 7 milliseconds component
 */
function truncatedISO8061Date(date, withMilliseconds = true) {
    // Date.toISOString() will return like "2018-10-29T06:34:36.139Z"
    const dateString = date.toISOString();
    return withMilliseconds
        ? dateString.substring(0, dateString.length - 1) + "0000" + "Z"
        : dateString.substring(0, dateString.length - 5) + "Z";
}
/**
 * Delay specified time interval.
 *
 * @param timeInMs -
 * @param aborter -
 * @param abortError -
 */
async function delay(timeInMs, aborter, abortError) {
    return new Promise((resolve, reject) => {
        /* eslint-disable-next-line prefer-const*/
        let timeout;
        const abortHandler = () => {
            if (timeout !== undefined) {
                clearTimeout(timeout);
            }
            reject(abortError);
        };
        const resolveHandler = () => {
            if (aborter !== undefined) {
                aborter.removeEventListener("abort", abortHandler);
            }
            resolve();
        };
        timeout = setTimeout(resolveHandler, timeInMs);
        if (aborter !== undefined) {
            aborter.addEventListener("abort", abortHandler);
        }
    });
}
/**
 * Extracts account name from the url
 * @param url - url to extract the account name from
 * @returns with the account name
 */
function getAccountNameFromUrl(url) {
    const parsedUrl = coreHttp.URLBuilder.parse(url);
    let accountName;
    try {
        if (parsedUrl.getHost().split(".")[1] === "queue") {
            // `${defaultEndpointsProtocol}://${accountName}.queue.${endpointSuffix}`;
            accountName = parsedUrl.getHost().split(".")[0];
        }
        else if (isIpEndpointStyle(parsedUrl)) {
            // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/
            // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/
            // .getPath() -> /devstoreaccount1/
            accountName = parsedUrl.getPath().split("/")[1];
        }
        else {
            // Custom domain case: "https://customdomain.com/containername/blob".
            accountName = "";
        }
        return accountName;
    }
    catch (error) {
        throw new Error("Unable to extract accountName with provided information.");
    }
}
function isIpEndpointStyle(parsedUrl) {
    if (parsedUrl.getHost() === undefined) {
        return false;
    }
    const host = parsedUrl.getHost() + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort());
    // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'.
    // Case 2: localhost(:port), use broad regex to match port part.
    // Case 3: Ipv4, use broad regex which just check if host contains Ipv4.
    // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html.
    return /^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host);
}
/**
 * Gets a new StorageClientContext
 * @param url - Url used for the StorageClientContext
 * @param pipeline - a pipeline containing HTTP request policies
 * @returns new StorageClientContext
 */
function getStorageClientContext(url, pipeline) {
    const storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions());
    // Override protocol layer's default content-type
    storageClientContext.requestContentType = undefined;
    return storageClientContext;
}
/**
 * Append a string to URL query.
 *
 * @param url - Source URL string.
 * @param queryParts - String to be appended to the URL query.
 * @returns An updated URL string.
 */
function appendToURLQuery(url, queryParts) {
    const urlParsed = coreHttp.URLBuilder.parse(url);
    let query = urlParsed.getQuery();
    if (query) {
        query += "&" + queryParts;
    }
    else {
        query = queryParts;
    }
    urlParsed.setQuery(query);
    return urlParsed.toString();
}

// Copyright (c) Microsoft Corporation.
(function (SASProtocol) {
    /**
     * Protocol that allows HTTPS only
     */
    SASProtocol["Https"] = "https";
    /**
     * Protocol that allows both HTTPS and HTTP
     */
    SASProtocol["HttpsAndHttp"] = "https,http";
})(exports.SASProtocol || (exports.SASProtocol = {}));
/**
 * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly
 * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link QueueSASSignatureValues}
 * types. Once generated, it can be encoded into a {@link String} and appended to a URL directly (though caution should
 * be taken here in case there are existing query parameters, which might affect the appropriate means of appending
 * these query parameters).
 *
 * NOTE: Instances of this class are immutable.
 */
class SASQueryParameters {
    /**
     * Creates an instance of SASQueryParameters.
     *
     * @param version - Representing the storage version
     * @param signature - Representing the signature for the SAS token
     * @param permissions - Representing the storage permissions
     * @param services - Representing the storage services being accessed (only for Account SAS)
     * @param resourceTypes - Representing the storage resource types being accessed (only for Account SAS)
     * @param protocol - Representing the allowed HTTP protocol(s)
     * @param startsOn - Representing the start time for this SAS token
     * @param expiresOn - Representing the expiry time for this SAS token
     * @param ipRange - Representing the range of valid IP addresses for this SAS token
     * @param identifier - Representing the signed identifier (only for Service SAS)
     * @param resource - Representing the storage queue (only for Service SAS)
     */
    constructor(version, signature, permissions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource) {
        this.version = version;
        this.services = services;
        this.resourceTypes = resourceTypes;
        this.expiresOn = expiresOn;
        this.permissions = permissions;
        this.protocol = protocol;
        this.startsOn = startsOn;
        this.ipRangeInner = ipRange;
        this.identifier = identifier;
        this.resource = resource;
        this.signature = signature;
    }
    /**
     * Optional. IP range allowed for this SAS.
     *
     * @readonly
     */
    get ipRange() {
        if (this.ipRangeInner) {
            return {
                end: this.ipRangeInner.end,
                start: this.ipRangeInner.start
            };
        }
        return undefined;
    }
    /**
     * Encodes all SAS query parameters into a string that can be appended to a URL.
     *
     */
    toString() {
        const params = ["sv", "ss", "srt", "spr", "st", "se", "sip", "si", "sr", "sp", "sig"];
        const queries = [];
        for (const param of params) {
            switch (param) {
                case "sv":
                    this.tryAppendQueryParameter(queries, param, this.version);
                    break;
                case "ss":
                    this.tryAppendQueryParameter(queries, param, this.services);
                    break;
                case "srt":
                    this.tryAppendQueryParameter(queries, param, this.resourceTypes);
                    break;
                case "spr":
                    this.tryAppendQueryParameter(queries, param, this.protocol);
                    break;
                case "st":
                    this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined);
                    break;
                case "se":
                    this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined);
                    break;
                case "sip":
                    this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined);
                    break;
                case "si":
                    this.tryAppendQueryParameter(queries, param, this.identifier);
                    break;
                case "sr":
                    this.tryAppendQueryParameter(queries, param, this.resource);
                    break;
                case "sp":
                    this.tryAppendQueryParameter(queries, param, this.permissions);
                    break;
                case "sig":
                    this.tryAppendQueryParameter(queries, param, this.signature);
                    break;
            }
        }
        return queries.join("&");
    }
    /**
     * A private helper method used to filter and append query key/value pairs into an array.
     *
     * @param queries -
     * @param key -
     * @param value -
     */
    tryAppendQueryParameter(queries, key, value) {
        if (!value) {
            return;
        }
        key = encodeURIComponent(key);
        value = encodeURIComponent(value);
        if (key.length > 0 && value.length > 0) {
            queries.push(`${key}=${value}`);
        }
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual
 * REST request.
 *
 * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas
 *
 * @param accountSASSignatureValues - SAS Signature values of the account
 * @param sharedKeyCredential - Shared key credential.
 */
function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) {
    const version = accountSASSignatureValues.version
        ? accountSASSignatureValues.version
        : SERVICE_VERSION;
    const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()).toString();
    const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString();
    const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString();
    const stringToSign = [
        sharedKeyCredential.accountName,
        parsedPermissions,
        parsedServices,
        parsedResourceTypes,
        accountSASSignatureValues.startsOn
            ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false)
            : "",
        truncatedISO8061Date(accountSASSignatureValues.expiresOn, false),
        accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "",
        accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "",
        version,
        "" // Account SAS requires an additional newline character
    ].join("\n");
    const signature = sharedKeyCredential.computeHMACSHA256(stringToSign);
    return new SASQueryParameters(version, signature, parsedPermissions, parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange);
}

// Copyright (c) Microsoft Corporation.
/**
 * Credential policy used to sign HTTP(S) requests before sending. This is an
 * abstract class.
 */
class CredentialPolicy extends coreHttp.BaseRequestPolicy {
    /**
     * Sends out request.
     *
     * @param request -
     */
    sendRequest(request) {
        return this._nextPolicy.sendRequest(this.signRequest(request));
    }
    /**
     * Child classes must implement this method with request signing. This method
     * will be executed in {@link sendRequest}.
     *
     * @param request -
     */
    signRequest(request) {
        // Child classes must override this method with request signing. This method
        // will be executed in sendRequest().
        return request;
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources
 * or for use with Shared Access Signatures (SAS).
 */
class AnonymousCredentialPolicy extends CredentialPolicy {
    /**
     * Creates an instance of AnonymousCredentialPolicy.
     * @param nextPolicy -
     * @param options -
     */
    // The base class has a protected constructor. Adding a public one to enable constructing of this class.
    /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
    constructor(nextPolicy, options) {
        super(nextPolicy, options);
    }
}

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * Credential is an abstract class for Azure Storage HTTP requests signing. This
 * class will host an credentialPolicyCreator factory which generates CredentialPolicy.
 */
class Credential {
    /**
     * Creates a RequestPolicy object.
     *
     * @param _nextPolicy -
     * @param _options -
     */
    create(_nextPolicy, _options) {
        throw new Error("Method should be implemented in children classes.");
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * AnonymousCredential provides a {@link CredentialPolicyCreator} member used to create
 * {@link AnonymousCredentialPolicy} objects. {@link AnonymousCredentialPolicy} is used with
 * HTTP(S) requests that read public resources or for use with Shared Access
 * Signatures (SAS).
 */
class AnonymousCredential extends Credential {
    /**
     * Creates an {@link AnonymousCredentialPolicy} object.
     *
     * @param nextPolicy -
     * @param options -
     */
    create(nextPolicy, options) {
        return new AnonymousCredentialPolicy(nextPolicy, options);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key.
 */
class StorageSharedKeyCredentialPolicy extends CredentialPolicy {
    /**
     * Creates an instance of StorageSharedKeyCredentialPolicy.
     * @param nextPolicy -
     * @param options -
     * @param factory -
     */
    constructor(nextPolicy, options, factory) {
        super(nextPolicy, options);
        this.factory = factory;
    }
    /**
     * Signs request.
     *
     * @param request -
     */
    signRequest(request) {
        request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString());
        if (request.body && typeof request.body === "string" && request.body.length > 0) {
            request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body));
        }
        const stringToSign = [
            request.method.toUpperCase(),
            this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE),
            this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING),
            this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH),
            this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5),
            this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE),
            this.getHeaderValueToSign(request, HeaderConstants.DATE),
            this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE),
            this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH),
            this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH),
            this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE),
            this.getHeaderValueToSign(request, HeaderConstants.RANGE)
        ].join("\n") +
            "\n" +
            this.getCanonicalizedHeadersString(request) +
            this.getCanonicalizedResourceString(request);
        const signature = this.factory.computeHMACSHA256(stringToSign);
        request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`);
        // console.log(`[URL]:${request.url}`);
        // console.log(`[HEADERS]:${request.headers.toString()}`);
        // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`);
        // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`);
        return request;
    }
    /**
     * Retrieve header value according to shared key sign rules.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
     *
     * @param request -
     * @param headerName -
     */
    getHeaderValueToSign(request, headerName) {
        const value = request.headers.get(headerName);
        if (!value) {
            return "";
        }
        // When using version 2015-02-21 or later, if Content-Length is zero, then
        // set the Content-Length part of the StringToSign to an empty string.
        // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key
        if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") {
            return "";
        }
        return value;
    }
    /**
     * To construct the CanonicalizedHeaders portion of the signature string, follow these steps:
     * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
     * 2. Convert each HTTP header name to lowercase.
     * 3. Sort the headers lexicographically by header name, in ascending order.
     *    Each header may appear only once in the string.
     * 4. Replace any linear whitespace in the header value with a single space.
     * 5. Trim any whitespace around the colon in the header.
     * 6. Finally, append a new-line character to each canonicalized header in the resulting list.
     *    Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
     *
     * @param request -
     */
    getCanonicalizedHeadersString(request) {
        let headersArray = request.headers.headersArray().filter((value) => {
            return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE);
        });
        headersArray.sort((a, b) => {
            return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
        });
        // Remove duplicate headers
        headersArray = headersArray.filter((value, index, array) => {
            if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) {
                return false;
            }
            return true;
        });
        let canonicalizedHeadersStringToSign = "";
        headersArray.forEach((header) => {
            canonicalizedHeadersStringToSign += `${header.name
                .toLowerCase()
                .trimRight()}:${header.value.trimLeft()}\n`;
        });
        return canonicalizedHeadersStringToSign;
    }
    /**
     * Retrieves the webResource canonicalized resource string.
     *
     * @param request -
     */
    getCanonicalizedResourceString(request) {
        const path = encodeURI(getURLPath(request.url) || "/");
        let canonicalizedResourceString = "";
        canonicalizedResourceString += `/${this.factory.accountName}${path}`;
        const queries = getURLQueries(request.url);
        const lowercaseQueries = {};
        if (queries) {
            const queryKeys = [];
            for (const key in queries) {
                if (Object.prototype.hasOwnProperty.call(queries, key)) {
                    const lowercaseKey = key.toLowerCase();
                    lowercaseQueries[lowercaseKey] = queries[key];
                    queryKeys.push(lowercaseKey);
                }
            }
            queryKeys.sort();
            for (const key of queryKeys) {
                canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`;
            }
        }
        return canonicalizedResourceString;
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * StorageSharedKeyCredential for account key authorization of Azure Storage service.
 */
class StorageSharedKeyCredential extends Credential {
    /**
     * Creates an instance of StorageSharedKeyCredential.
     * @param accountName -
     * @param accountKey -
     */
    constructor(accountName, accountKey) {
        super();
        this.accountName = accountName;
        this.accountKey = Buffer.from(accountKey, "base64");
    }
    /**
     * Creates a {@link StorageSharedKeyCredentialPolicy} object.
     *
     * @param nextPolicy -
     * @param options -
     */
    create(nextPolicy, options) {
        return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this);
    }
    /**
     * Generates a hash signature for an HTTP request or for a SAS.
     *
     * @param stringToSign -
     */
    computeHMACSHA256(stringToSign) {
        return crypto.createHmac("sha256", this.accountKey)
            .update(stringToSign, "utf8")
            .digest("base64");
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * The `@azure/logger` configuration for this package.
 */
const logger = logger$1.createClientLogger("storage-queue");

// Copyright (c) Microsoft Corporation.
/**
 * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including:
 *
 * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'.
 * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL
 * thus avoid the browser cache.
 *
 * 2. Remove cookie header for security
 *
 * 3. Remove content-length header to avoid browsers warning
 */
class StorageBrowserPolicy extends coreHttp.BaseRequestPolicy {
    /**
     * Creates an instance of StorageBrowserPolicy.
     * @param nextPolicy -
     * @param options -
     */
    // The base class has a protected constructor. Adding a public one to enable constructing of this class.
    /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/
    constructor(nextPolicy, options) {
        super(nextPolicy, options);
    }
    /**
     * Sends out request.
     *
     * @param request -
     */
    async sendRequest(request) {
        {
            return this._nextPolicy.sendRequest(request);
        }
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * StorageBrowserPolicyFactory is a factory class helping generating {@link StorageBrowserPolicy} objects.
 */
class StorageBrowserPolicyFactory {
    /**
     * Creates a StorageBrowserPolicyFactory object.
     *
     * @param nextPolicy -
     * @param options -
     */
    create(nextPolicy, options) {
        return new StorageBrowserPolicy(nextPolicy, options);
    }
}

// Copyright (c) Microsoft Corporation.
(function (StorageRetryPolicyType) {
    /**
     * Exponential retry. Retry time delay grows exponentially.
     */
    StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL";
    /**
     * Linear retry. Retry time delay grows linearly.
     */
    StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED";
})(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {}));
// Default values of StorageRetryOptions
const DEFAULT_RETRY_OPTIONS = {
    maxRetryDelayInMs: 120 * 1000,
    maxTries: 4,
    retryDelayInMs: 4 * 1000,
    retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL,
    secondaryHost: "",
    tryTimeoutInMs: 30 * 1000 // https://docs.microsoft.com/en-us/rest/api/storageservices/setting-timeouts-for-queue-service-operations
};
const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted.");
/**
 * Retry policy with exponential retry and linear retry implemented.
 */
class StorageRetryPolicy extends coreHttp.BaseRequestPolicy {
    /**
     * Creates an instance of RetryPolicy.
     *
     * @param nextPolicy -
     * @param options -
     * @param retryOptions -
     */
    constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) {
        super(nextPolicy, options);
        // Initialize retry options
        this.retryOptions = {
            retryPolicyType: retryOptions.retryPolicyType
                ? retryOptions.retryPolicyType
                : DEFAULT_RETRY_OPTIONS.retryPolicyType,
            maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1
                ? Math.floor(retryOptions.maxTries)
                : DEFAULT_RETRY_OPTIONS.maxTries,
            tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0
                ? retryOptions.tryTimeoutInMs
                : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs,
            retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0
                ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs
                    ? retryOptions.maxRetryDelayInMs
                    : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs)
                : DEFAULT_RETRY_OPTIONS.retryDelayInMs,
            maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0
                ? retryOptions.maxRetryDelayInMs
                : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs,
            secondaryHost: retryOptions.secondaryHost
                ? retryOptions.secondaryHost
                : DEFAULT_RETRY_OPTIONS.secondaryHost
        };
    }
    /**
     * Sends request.
     *
     * @param request -
     */
    async sendRequest(request) {
        return this.attemptSendRequest(request, false, 1);
    }
    /**
     * Decide and perform next retry. Won't mutate request parameter.
     *
     * @param request -
     * @param response -
     * @param secondaryHas404 -  If attempt was against the secondary & it returned a StatusNotFound (404), then
     *                                   the resource was not found. This may be due to replication delay. So, in this
     *                                   case, we'll never try the secondary again for this operation.
     * @param attempt -           How many retries has been attempted to performed, starting from 1, which includes
     *                                   the attempt will be performed by this method call.
     */
    async attemptSendRequest(request, secondaryHas404, attempt) {
        const newRequest = request.clone();
        const isPrimaryRetry = secondaryHas404 ||
            !this.retryOptions.secondaryHost ||
            !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") ||
            attempt % 2 === 1;
        if (!isPrimaryRetry) {
            newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost);
        }
        // Set the server-side timeout query parameter "timeout=[seconds]"
        newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString());
        let response;
        try {
            logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`);
            response = await this._nextPolicy.sendRequest(newRequest);
            if (!this.shouldRetry(isPrimaryRetry, attempt, response)) {
                return response;
            }
            secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404);
        }
        catch (err) {
            logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`);
            if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) {
                throw err;
            }
        }
        await this.delay(isPrimaryRetry, attempt, request.abortSignal);
        return this.attemptSendRequest(request, secondaryHas404, ++attempt);
    }
    /**
     * Decide whether to retry according to last HTTP response and retry counters.
     *
     * @param isPrimaryRetry -
     * @param attempt -
     * @param response -
     * @param err -
     */
    shouldRetry(isPrimaryRetry, attempt, response, err) {
        if (attempt >= this.retryOptions.maxTries) {
            logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions
                .maxTries}, no further try.`);
            return false;
        }
        // Handle network failures, you may need to customize the list when you implement
        // your own http client
        const retriableErrors = [
            "ETIMEDOUT",
            "ESOCKETTIMEDOUT",
            "ECONNREFUSED",
            "ECONNRESET",
            "ENOENT",
            "ENOTFOUND",
            "TIMEOUT",
            "EPIPE",
            "REQUEST_SEND_ERROR" // For default xhr based http client provided in ms-rest-js
        ];
        if (err) {
            for (const retriableError of retriableErrors) {
                if (err.name.toUpperCase().includes(retriableError) ||
                    err.message.toUpperCase().includes(retriableError) ||
                    (err.code && err.code.toString().toUpperCase() === retriableError)) {
                    logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`);
                    return true;
                }
            }
        }
        // If attempt was against the secondary & it returned a StatusNotFound (404), then
        // the resource was not found. This may be due to replication delay. So, in this
        // case, we'll never try the secondary again for this operation.
        if (response || err) {
            const statusCode = response ? response.status : err ? err.statusCode : 0;
            if (!isPrimaryRetry && statusCode === 404) {
                logger.info(`RetryPolicy: Secondary access with 404, will retry.`);
                return true;
            }
            // Server internal error or server timeout
            if (statusCode === 503 || statusCode === 500) {
                logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`);
                return true;
            }
        }
        if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith(`Error "Error: Unclosed root tag`))) {
            logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry.");
            return true;
        }
        return false;
    }
    /**
     * Delay a calculated time between retries.
     *
     * @param isPrimaryRetry -
     * @param attempt -
     * @param abortSignal -
     */
    async delay(isPrimaryRetry, attempt, abortSignal) {
        let delayTimeInMs = 0;
        if (isPrimaryRetry) {
            switch (this.retryOptions.retryPolicyType) {
                case exports.StorageRetryPolicyType.EXPONENTIAL:
                    delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs);
                    break;
                case exports.StorageRetryPolicyType.FIXED:
                    delayTimeInMs = this.retryOptions.retryDelayInMs;
                    break;
            }
        }
        else {
            delayTimeInMs = Math.random() * 1000;
        }
        logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`);
        return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects.
 */
class StorageRetryPolicyFactory {
    /**
     * Creates an instance of StorageRetryPolicyFactory.
     * @param retryOptions -
     */
    constructor(retryOptions) {
        this.retryOptions = retryOptions;
    }
    /**
     * Creates a {@link StorageRetryPolicy} object.
     *
     * @param nextPolicy -
     * @param options -
     */
    create(nextPolicy, options) {
        return new StorageRetryPolicy(nextPolicy, options, this.retryOptions);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * TelemetryPolicy is a policy used to tag user-agent header for every requests.
 */
class TelemetryPolicy extends coreHttp.BaseRequestPolicy {
    /**
     * Creates an instance of TelemetryPolicy.
     * @param nextPolicy -
     * @param options -
     * @param telemetry -
     */
    constructor(nextPolicy, options, telemetry) {
        super(nextPolicy, options);
        this.telemetry = telemetry;
    }
    /**
     * Sends out request.
     *
     * @param request -
     */
    async sendRequest(request) {
        {
            if (!request.headers) {
                request.headers = new coreHttp.HttpHeaders();
            }
            if (!request.headers.get(HeaderConstants.USER_AGENT)) {
                request.headers.set(HeaderConstants.USER_AGENT, this.telemetry);
            }
        }
        return this._nextPolicy.sendRequest(request);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects.
 */
class TelemetryPolicyFactory {
    /**
     * Creates an instance of TelemetryPolicyFactory.
     * @param telemetry -
     */
    constructor(telemetry) {
        const userAgentInfo = [];
        {
            if (telemetry) {
                const telemetryString = telemetry.userAgentPrefix || "";
                if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) {
                    userAgentInfo.push(telemetryString);
                }
            }
            // e.g. azsdk-js-storagequeue/11.0.0
            const libInfo = `azsdk-js-storagequeue/${SDK_VERSION}`;
            if (userAgentInfo.indexOf(libInfo) === -1) {
                userAgentInfo.push(libInfo);
            }
            // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299)
            const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`;
            if (userAgentInfo.indexOf(runtimeInfo) === -1) {
                userAgentInfo.push(runtimeInfo);
            }
        }
        this.telemetryString = userAgentInfo.join(" ");
    }
    /**
     * Creates a {@link TelemetryPolicy} object.
     *
     * @param nextPolicy -
     * @param options -
     */
    create(nextPolicy, options) {
        return new TelemetryPolicy(nextPolicy, options, this.telemetryString);
    }
}

// Copyright (c) Microsoft Corporation.
const _defaultHttpClient = new coreHttp.DefaultHttpClient();
function getCachedDefaultHttpClient() {
    return _defaultHttpClient;
}

// Copyright (c) Microsoft Corporation.
/**
 * A Pipeline class containing HTTP request policies.
 * You can create a default Pipeline by calling newPipeline().
 * Or you can create a Pipeline with your own policies by the constructor of Pipeline.
 * Refer to newPipeline() and provided policies as reference before
 * implementing your customized Pipeline.
 */
class Pipeline {
    /**
     * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface.
     *
     * @param factories -
     * @param options -
     */
    constructor(factories, options = {}) {
        this.factories = factories;
        // when options.httpClient is not specified, passing in a DefaultHttpClient instance to
        // avoid each client creating its own http client.
        this.options = Object.assign(Object.assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() });
    }
    /**
     * Transfers Pipeline object to ServiceClientOptions object which required by
     * ServiceClient constructor.
     *
     * @returns The ServiceClientOptions object from this Pipeline.
     */
    toServiceClientOptions() {
        return {
            httpClient: this.options.httpClient,
            requestPolicyFactories: this.factories
        };
    }
}
/**
 * Creates a new Pipeline object with Credential provided.
 *
 * @param credential -  Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used.
 * @param pipelineOptions - Options.
 * @returns A new Pipeline object.
 */
function newPipeline(credential, pipelineOptions = {}) {
    if (credential === undefined) {
        credential = new AnonymousCredential();
    }
    // Order is important. Closer to the API at the top & closer to the network at the bottom.
    // The credential's policy factory must appear close to the wire so it can sign any
    // changes made by other factories (like UniqueRequestIDPolicyFactory)
    const telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions);
    const factories = [
        coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }),
        coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions),
        telemetryPolicy,
        coreHttp.generateClientRequestIdPolicy(),
        new StorageBrowserPolicyFactory(),
        new StorageRetryPolicyFactory(pipelineOptions.retryOptions),
        coreHttp.deserializationPolicy(),
        coreHttp.logPolicy({
            logger: logger.info,
            allowedHeaderNames: StorageQueueLoggingAllowedHeaderNames,
            allowedQueryParameters: StorageQueueLoggingAllowedQueryParameters
        })
    ];
    {
        // ProxyPolicy is only available in Node.js runtime, not in browsers
        factories.push(coreHttp.proxyPolicy(pipelineOptions.proxyOptions));
    }
    factories.push(coreHttp.isTokenCredential(credential)
        ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes)
        : credential);
    return new Pipeline(factories, pipelineOptions);
}

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const QueueServiceProperties = {
    serializedName: "QueueServiceProperties",
    xmlName: "StorageServiceProperties",
    type: {
        name: "Composite",
        className: "QueueServiceProperties",
        modelProperties: {
            queueAnalyticsLogging: {
                serializedName: "Logging",
                xmlName: "Logging",
                type: {
                    name: "Composite",
                    className: "Logging"
                }
            },
            hourMetrics: {
                serializedName: "HourMetrics",
                xmlName: "HourMetrics",
                type: {
                    name: "Composite",
                    className: "Metrics"
                }
            },
            minuteMetrics: {
                serializedName: "MinuteMetrics",
                xmlName: "MinuteMetrics",
                type: {
                    name: "Composite",
                    className: "Metrics"
                }
            },
            cors: {
                serializedName: "Cors",
                xmlName: "Cors",
                xmlIsWrapped: true,
                xmlElementName: "CorsRule",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "CorsRule"
                        }
                    }
                }
            }
        }
    }
};
const Logging = {
    serializedName: "Logging",
    type: {
        name: "Composite",
        className: "Logging",
        modelProperties: {
            version: {
                serializedName: "Version",
                required: true,
                xmlName: "Version",
                type: {
                    name: "String"
                }
            },
            deleteProperty: {
                serializedName: "Delete",
                required: true,
                xmlName: "Delete",
                type: {
                    name: "Boolean"
                }
            },
            read: {
                serializedName: "Read",
                required: true,
                xmlName: "Read",
                type: {
                    name: "Boolean"
                }
            },
            write: {
                serializedName: "Write",
                required: true,
                xmlName: "Write",
                type: {
                    name: "Boolean"
                }
            },
            retentionPolicy: {
                serializedName: "RetentionPolicy",
                xmlName: "RetentionPolicy",
                type: {
                    name: "Composite",
                    className: "RetentionPolicy"
                }
            }
        }
    }
};
const RetentionPolicy = {
    serializedName: "RetentionPolicy",
    type: {
        name: "Composite",
        className: "RetentionPolicy",
        modelProperties: {
            enabled: {
                serializedName: "Enabled",
                required: true,
                xmlName: "Enabled",
                type: {
                    name: "Boolean"
                }
            },
            days: {
                constraints: {
                    InclusiveMinimum: 1
                },
                serializedName: "Days",
                xmlName: "Days",
                type: {
                    name: "Number"
                }
            }
        }
    }
};
const Metrics = {
    serializedName: "Metrics",
    type: {
        name: "Composite",
        className: "Metrics",
        modelProperties: {
            version: {
                serializedName: "Version",
                xmlName: "Version",
                type: {
                    name: "String"
                }
            },
            enabled: {
                serializedName: "Enabled",
                required: true,
                xmlName: "Enabled",
                type: {
                    name: "Boolean"
                }
            },
            includeAPIs: {
                serializedName: "IncludeAPIs",
                xmlName: "IncludeAPIs",
                type: {
                    name: "Boolean"
                }
            },
            retentionPolicy: {
                serializedName: "RetentionPolicy",
                xmlName: "RetentionPolicy",
                type: {
                    name: "Composite",
                    className: "RetentionPolicy"
                }
            }
        }
    }
};
const CorsRule = {
    serializedName: "CorsRule",
    type: {
        name: "Composite",
        className: "CorsRule",
        modelProperties: {
            allowedOrigins: {
                serializedName: "AllowedOrigins",
                required: true,
                xmlName: "AllowedOrigins",
                type: {
                    name: "String"
                }
            },
            allowedMethods: {
                serializedName: "AllowedMethods",
                required: true,
                xmlName: "AllowedMethods",
                type: {
                    name: "String"
                }
            },
            allowedHeaders: {
                serializedName: "AllowedHeaders",
                required: true,
                xmlName: "AllowedHeaders",
                type: {
                    name: "String"
                }
            },
            exposedHeaders: {
                serializedName: "ExposedHeaders",
                required: true,
                xmlName: "ExposedHeaders",
                type: {
                    name: "String"
                }
            },
            maxAgeInSeconds: {
                constraints: {
                    InclusiveMinimum: 0
                },
                serializedName: "MaxAgeInSeconds",
                required: true,
                xmlName: "MaxAgeInSeconds",
                type: {
                    name: "Number"
                }
            }
        }
    }
};
const StorageError = {
    serializedName: "StorageError",
    type: {
        name: "Composite",
        className: "StorageError",
        modelProperties: {
            message: {
                serializedName: "Message",
                xmlName: "Message",
                type: {
                    name: "String"
                }
            },
            code: {
                serializedName: "Code",
                xmlName: "Code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueServiceStatistics = {
    serializedName: "QueueServiceStatistics",
    xmlName: "StorageServiceStats",
    type: {
        name: "Composite",
        className: "QueueServiceStatistics",
        modelProperties: {
            geoReplication: {
                serializedName: "GeoReplication",
                xmlName: "GeoReplication",
                type: {
                    name: "Composite",
                    className: "GeoReplication"
                }
            }
        }
    }
};
const GeoReplication = {
    serializedName: "GeoReplication",
    type: {
        name: "Composite",
        className: "GeoReplication",
        modelProperties: {
            status: {
                serializedName: "Status",
                required: true,
                xmlName: "Status",
                type: {
                    name: "Enum",
                    allowedValues: ["live", "bootstrap", "unavailable"]
                }
            },
            lastSyncOn: {
                serializedName: "LastSyncTime",
                required: true,
                xmlName: "LastSyncTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            }
        }
    }
};
const ListQueuesSegmentResponse = {
    serializedName: "ListQueuesSegmentResponse",
    xmlName: "EnumerationResults",
    type: {
        name: "Composite",
        className: "ListQueuesSegmentResponse",
        modelProperties: {
            serviceEndpoint: {
                serializedName: "ServiceEndpoint",
                required: true,
                xmlName: "ServiceEndpoint",
                xmlIsAttribute: true,
                type: {
                    name: "String"
                }
            },
            prefix: {
                serializedName: "Prefix",
                required: true,
                xmlName: "Prefix",
                type: {
                    name: "String"
                }
            },
            marker: {
                serializedName: "Marker",
                xmlName: "Marker",
                type: {
                    name: "String"
                }
            },
            maxPageSize: {
                serializedName: "MaxResults",
                required: true,
                xmlName: "MaxResults",
                type: {
                    name: "Number"
                }
            },
            queueItems: {
                serializedName: "QueueItems",
                xmlName: "Queues",
                xmlIsWrapped: true,
                xmlElementName: "Queue",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "QueueItem"
                        }
                    }
                }
            },
            continuationToken: {
                serializedName: "NextMarker",
                required: true,
                xmlName: "NextMarker",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueItem = {
    serializedName: "QueueItem",
    xmlName: "Queue",
    type: {
        name: "Composite",
        className: "QueueItem",
        modelProperties: {
            name: {
                serializedName: "Name",
                required: true,
                xmlName: "Name",
                type: {
                    name: "String"
                }
            },
            metadata: {
                serializedName: "Metadata",
                xmlName: "Metadata",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            }
        }
    }
};
const SignedIdentifier = {
    serializedName: "SignedIdentifier",
    type: {
        name: "Composite",
        className: "SignedIdentifier",
        modelProperties: {
            id: {
                serializedName: "Id",
                required: true,
                xmlName: "Id",
                type: {
                    name: "String"
                }
            },
            accessPolicy: {
                serializedName: "AccessPolicy",
                xmlName: "AccessPolicy",
                type: {
                    name: "Composite",
                    className: "AccessPolicy"
                }
            }
        }
    }
};
const AccessPolicy = {
    serializedName: "AccessPolicy",
    type: {
        name: "Composite",
        className: "AccessPolicy",
        modelProperties: {
            startsOn: {
                serializedName: "Start",
                xmlName: "Start",
                type: {
                    name: "String"
                }
            },
            expiresOn: {
                serializedName: "Expiry",
                xmlName: "Expiry",
                type: {
                    name: "String"
                }
            },
            permissions: {
                serializedName: "Permission",
                xmlName: "Permission",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const DequeuedMessageItem = {
    serializedName: "DequeuedMessageItem",
    xmlName: "QueueMessage",
    xmlIsWrapped: true,
    type: {
        name: "Composite",
        className: "DequeuedMessageItem",
        modelProperties: {
            messageId: {
                serializedName: "MessageId",
                required: true,
                xmlName: "MessageId",
                type: {
                    name: "String"
                }
            },
            insertedOn: {
                serializedName: "InsertionTime",
                required: true,
                xmlName: "InsertionTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            expiresOn: {
                serializedName: "ExpirationTime",
                required: true,
                xmlName: "ExpirationTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            popReceipt: {
                serializedName: "PopReceipt",
                required: true,
                xmlName: "PopReceipt",
                type: {
                    name: "String"
                }
            },
            nextVisibleOn: {
                serializedName: "TimeNextVisible",
                required: true,
                xmlName: "TimeNextVisible",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            dequeueCount: {
                serializedName: "DequeueCount",
                required: true,
                xmlName: "DequeueCount",
                type: {
                    name: "Number"
                }
            },
            messageText: {
                serializedName: "MessageText",
                required: true,
                xmlName: "MessageText",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueMessage = {
    serializedName: "QueueMessage",
    type: {
        name: "Composite",
        className: "QueueMessage",
        modelProperties: {
            messageText: {
                serializedName: "MessageText",
                required: true,
                xmlName: "MessageText",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const EnqueuedMessage = {
    serializedName: "EnqueuedMessage",
    xmlName: "QueueMessage",
    xmlIsWrapped: true,
    type: {
        name: "Composite",
        className: "EnqueuedMessage",
        modelProperties: {
            messageId: {
                serializedName: "MessageId",
                required: true,
                xmlName: "MessageId",
                type: {
                    name: "String"
                }
            },
            insertedOn: {
                serializedName: "InsertionTime",
                required: true,
                xmlName: "InsertionTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            expiresOn: {
                serializedName: "ExpirationTime",
                required: true,
                xmlName: "ExpirationTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            popReceipt: {
                serializedName: "PopReceipt",
                required: true,
                xmlName: "PopReceipt",
                type: {
                    name: "String"
                }
            },
            nextVisibleOn: {
                serializedName: "TimeNextVisible",
                required: true,
                xmlName: "TimeNextVisible",
                type: {
                    name: "DateTimeRfc1123"
                }
            }
        }
    }
};
const PeekedMessageItem = {
    serializedName: "PeekedMessageItem",
    xmlName: "QueueMessage",
    xmlIsWrapped: true,
    type: {
        name: "Composite",
        className: "PeekedMessageItem",
        modelProperties: {
            messageId: {
                serializedName: "MessageId",
                required: true,
                xmlName: "MessageId",
                type: {
                    name: "String"
                }
            },
            insertedOn: {
                serializedName: "InsertionTime",
                required: true,
                xmlName: "InsertionTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            expiresOn: {
                serializedName: "ExpirationTime",
                required: true,
                xmlName: "ExpirationTime",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            dequeueCount: {
                serializedName: "DequeueCount",
                required: true,
                xmlName: "DequeueCount",
                type: {
                    name: "Number"
                }
            },
            messageText: {
                serializedName: "MessageText",
                required: true,
                xmlName: "MessageText",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceSetPropertiesHeaders = {
    serializedName: "Service_setPropertiesHeaders",
    type: {
        name: "Composite",
        className: "ServiceSetPropertiesHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceSetPropertiesExceptionHeaders = {
    serializedName: "Service_setPropertiesExceptionHeaders",
    type: {
        name: "Composite",
        className: "ServiceSetPropertiesExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceGetPropertiesHeaders = {
    serializedName: "Service_getPropertiesHeaders",
    type: {
        name: "Composite",
        className: "ServiceGetPropertiesHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceGetPropertiesExceptionHeaders = {
    serializedName: "Service_getPropertiesExceptionHeaders",
    type: {
        name: "Composite",
        className: "ServiceGetPropertiesExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceGetStatisticsHeaders = {
    serializedName: "Service_getStatisticsHeaders",
    type: {
        name: "Composite",
        className: "ServiceGetStatisticsHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceGetStatisticsExceptionHeaders = {
    serializedName: "Service_getStatisticsExceptionHeaders",
    type: {
        name: "Composite",
        className: "ServiceGetStatisticsExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceListQueuesSegmentHeaders = {
    serializedName: "Service_listQueuesSegmentHeaders",
    type: {
        name: "Composite",
        className: "ServiceListQueuesSegmentHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const ServiceListQueuesSegmentExceptionHeaders = {
    serializedName: "Service_listQueuesSegmentExceptionHeaders",
    type: {
        name: "Composite",
        className: "ServiceListQueuesSegmentExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueCreateHeaders = {
    serializedName: "Queue_createHeaders",
    type: {
        name: "Composite",
        className: "QueueCreateHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueCreateExceptionHeaders = {
    serializedName: "Queue_createExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueCreateExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueDeleteHeaders = {
    serializedName: "Queue_deleteHeaders",
    type: {
        name: "Composite",
        className: "QueueDeleteHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueDeleteExceptionHeaders = {
    serializedName: "Queue_deleteExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueDeleteExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueGetPropertiesHeaders = {
    serializedName: "Queue_getPropertiesHeaders",
    type: {
        name: "Composite",
        className: "QueueGetPropertiesHeaders",
        modelProperties: {
            metadata: {
                serializedName: "x-ms-meta",
                xmlName: "x-ms-meta",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                },
                headerCollectionPrefix: "x-ms-meta-"
            },
            approximateMessagesCount: {
                serializedName: "x-ms-approximate-messages-count",
                xmlName: "x-ms-approximate-messages-count",
                type: {
                    name: "Number"
                }
            },
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueGetPropertiesExceptionHeaders = {
    serializedName: "Queue_getPropertiesExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueGetPropertiesExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueSetMetadataHeaders = {
    serializedName: "Queue_setMetadataHeaders",
    type: {
        name: "Composite",
        className: "QueueSetMetadataHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueSetMetadataExceptionHeaders = {
    serializedName: "Queue_setMetadataExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueSetMetadataExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueGetAccessPolicyHeaders = {
    serializedName: "Queue_getAccessPolicyHeaders",
    type: {
        name: "Composite",
        className: "QueueGetAccessPolicyHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueGetAccessPolicyExceptionHeaders = {
    serializedName: "Queue_getAccessPolicyExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueGetAccessPolicyExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueSetAccessPolicyHeaders = {
    serializedName: "Queue_setAccessPolicyHeaders",
    type: {
        name: "Composite",
        className: "QueueSetAccessPolicyHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const QueueSetAccessPolicyExceptionHeaders = {
    serializedName: "Queue_setAccessPolicyExceptionHeaders",
    type: {
        name: "Composite",
        className: "QueueSetAccessPolicyExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesDequeueHeaders = {
    serializedName: "Messages_dequeueHeaders",
    type: {
        name: "Composite",
        className: "MessagesDequeueHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesDequeueExceptionHeaders = {
    serializedName: "Messages_dequeueExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessagesDequeueExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesClearHeaders = {
    serializedName: "Messages_clearHeaders",
    type: {
        name: "Composite",
        className: "MessagesClearHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesClearExceptionHeaders = {
    serializedName: "Messages_clearExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessagesClearExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesEnqueueHeaders = {
    serializedName: "Messages_enqueueHeaders",
    type: {
        name: "Composite",
        className: "MessagesEnqueueHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesEnqueueExceptionHeaders = {
    serializedName: "Messages_enqueueExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessagesEnqueueExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesPeekHeaders = {
    serializedName: "Messages_peekHeaders",
    type: {
        name: "Composite",
        className: "MessagesPeekHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessagesPeekExceptionHeaders = {
    serializedName: "Messages_peekExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessagesPeekExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessageIdUpdateHeaders = {
    serializedName: "MessageId_updateHeaders",
    type: {
        name: "Composite",
        className: "MessageIdUpdateHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            popReceipt: {
                serializedName: "x-ms-popreceipt",
                xmlName: "x-ms-popreceipt",
                type: {
                    name: "String"
                }
            },
            nextVisibleOn: {
                serializedName: "x-ms-time-next-visible",
                xmlName: "x-ms-time-next-visible",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessageIdUpdateExceptionHeaders = {
    serializedName: "MessageId_updateExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessageIdUpdateExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessageIdDeleteHeaders = {
    serializedName: "MessageId_deleteHeaders",
    type: {
        name: "Composite",
        className: "MessageIdDeleteHeaders",
        modelProperties: {
            requestId: {
                serializedName: "x-ms-request-id",
                xmlName: "x-ms-request-id",
                type: {
                    name: "String"
                }
            },
            version: {
                serializedName: "x-ms-version",
                xmlName: "x-ms-version",
                type: {
                    name: "String"
                }
            },
            date: {
                serializedName: "date",
                xmlName: "date",
                type: {
                    name: "DateTimeRfc1123"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            },
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const MessageIdDeleteExceptionHeaders = {
    serializedName: "MessageId_deleteExceptionHeaders",
    type: {
        name: "Composite",
        className: "MessageIdDeleteExceptionHeaders",
        modelProperties: {
            errorCode: {
                serializedName: "x-ms-error-code",
                xmlName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            },
            clientRequestId: {
                serializedName: "x-ms-client-request-id",
                xmlName: "x-ms-client-request-id",
                type: {
                    name: "String"
                }
            }
        }
    }
};

var Mappers = /*#__PURE__*/Object.freeze({
    __proto__: null,
    QueueServiceProperties: QueueServiceProperties,
    Logging: Logging,
    RetentionPolicy: RetentionPolicy,
    Metrics: Metrics,
    CorsRule: CorsRule,
    StorageError: StorageError,
    QueueServiceStatistics: QueueServiceStatistics,
    GeoReplication: GeoReplication,
    ListQueuesSegmentResponse: ListQueuesSegmentResponse,
    QueueItem: QueueItem,
    SignedIdentifier: SignedIdentifier,
    AccessPolicy: AccessPolicy,
    DequeuedMessageItem: DequeuedMessageItem,
    QueueMessage: QueueMessage,
    EnqueuedMessage: EnqueuedMessage,
    PeekedMessageItem: PeekedMessageItem,
    ServiceSetPropertiesHeaders: ServiceSetPropertiesHeaders,
    ServiceSetPropertiesExceptionHeaders: ServiceSetPropertiesExceptionHeaders,
    ServiceGetPropertiesHeaders: ServiceGetPropertiesHeaders,
    ServiceGetPropertiesExceptionHeaders: ServiceGetPropertiesExceptionHeaders,
    ServiceGetStatisticsHeaders: ServiceGetStatisticsHeaders,
    ServiceGetStatisticsExceptionHeaders: ServiceGetStatisticsExceptionHeaders,
    ServiceListQueuesSegmentHeaders: ServiceListQueuesSegmentHeaders,
    ServiceListQueuesSegmentExceptionHeaders: ServiceListQueuesSegmentExceptionHeaders,
    QueueCreateHeaders: QueueCreateHeaders,
    QueueCreateExceptionHeaders: QueueCreateExceptionHeaders,
    QueueDeleteHeaders: QueueDeleteHeaders,
    QueueDeleteExceptionHeaders: QueueDeleteExceptionHeaders,
    QueueGetPropertiesHeaders: QueueGetPropertiesHeaders,
    QueueGetPropertiesExceptionHeaders: QueueGetPropertiesExceptionHeaders,
    QueueSetMetadataHeaders: QueueSetMetadataHeaders,
    QueueSetMetadataExceptionHeaders: QueueSetMetadataExceptionHeaders,
    QueueGetAccessPolicyHeaders: QueueGetAccessPolicyHeaders,
    QueueGetAccessPolicyExceptionHeaders: QueueGetAccessPolicyExceptionHeaders,
    QueueSetAccessPolicyHeaders: QueueSetAccessPolicyHeaders,
    QueueSetAccessPolicyExceptionHeaders: QueueSetAccessPolicyExceptionHeaders,
    MessagesDequeueHeaders: MessagesDequeueHeaders,
    MessagesDequeueExceptionHeaders: MessagesDequeueExceptionHeaders,
    MessagesClearHeaders: MessagesClearHeaders,
    MessagesClearExceptionHeaders: MessagesClearExceptionHeaders,
    MessagesEnqueueHeaders: MessagesEnqueueHeaders,
    MessagesEnqueueExceptionHeaders: MessagesEnqueueExceptionHeaders,
    MessagesPeekHeaders: MessagesPeekHeaders,
    MessagesPeekExceptionHeaders: MessagesPeekExceptionHeaders,
    MessageIdUpdateHeaders: MessageIdUpdateHeaders,
    MessageIdUpdateExceptionHeaders: MessageIdUpdateExceptionHeaders,
    MessageIdDeleteHeaders: MessageIdDeleteHeaders,
    MessageIdDeleteExceptionHeaders: MessageIdDeleteExceptionHeaders
});

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const contentType = {
    parameterPath: ["options", "contentType"],
    mapper: {
        defaultValue: "application/xml",
        isConstant: true,
        serializedName: "Content-Type",
        type: {
            name: "String"
        }
    }
};
const properties = {
    parameterPath: "properties",
    mapper: QueueServiceProperties
};
const accept = {
    parameterPath: "accept",
    mapper: {
        defaultValue: "application/xml",
        isConstant: true,
        serializedName: "Accept",
        type: {
            name: "String"
        }
    }
};
const url = {
    parameterPath: "url",
    mapper: {
        serializedName: "url",
        required: true,
        xmlName: "url",
        type: {
            name: "String"
        }
    },
    skipEncoding: true
};
const restype = {
    parameterPath: "restype",
    mapper: {
        defaultValue: "service",
        isConstant: true,
        serializedName: "restype",
        type: {
            name: "String"
        }
    }
};
const comp = {
    parameterPath: "comp",
    mapper: {
        defaultValue: "properties",
        isConstant: true,
        serializedName: "comp",
        type: {
            name: "String"
        }
    }
};
const timeoutInSeconds = {
    parameterPath: ["options", "timeoutInSeconds"],
    mapper: {
        constraints: {
            InclusiveMinimum: 0
        },
        serializedName: "timeout",
        xmlName: "timeout",
        type: {
            name: "Number"
        }
    }
};
const version = {
    parameterPath: "version",
    mapper: {
        defaultValue: "2020-10-02",
        isConstant: true,
        serializedName: "x-ms-version",
        type: {
            name: "String"
        }
    }
};
const requestId = {
    parameterPath: ["options", "requestId"],
    mapper: {
        serializedName: "x-ms-client-request-id",
        xmlName: "x-ms-client-request-id",
        type: {
            name: "String"
        }
    }
};
const accept1 = {
    parameterPath: "accept",
    mapper: {
        defaultValue: "application/xml",
        isConstant: true,
        serializedName: "Accept",
        type: {
            name: "String"
        }
    }
};
const comp1 = {
    parameterPath: "comp",
    mapper: {
        defaultValue: "stats",
        isConstant: true,
        serializedName: "comp",
        type: {
            name: "String"
        }
    }
};
const comp2 = {
    parameterPath: "comp",
    mapper: {
        defaultValue: "list",
        isConstant: true,
        serializedName: "comp",
        type: {
            name: "String"
        }
    }
};
const prefix = {
    parameterPath: ["options", "prefix"],
    mapper: {
        serializedName: "prefix",
        xmlName: "prefix",
        type: {
            name: "String"
        }
    }
};
const marker = {
    parameterPath: ["options", "marker"],
    mapper: {
        serializedName: "marker",
        xmlName: "marker",
        type: {
            name: "String"
        }
    }
};
const maxPageSize = {
    parameterPath: ["options", "maxPageSize"],
    mapper: {
        constraints: {
            InclusiveMinimum: 1
        },
        serializedName: "maxresults",
        xmlName: "maxresults",
        type: {
            name: "Number"
        }
    }
};
const include = {
    parameterPath: ["options", "include"],
    mapper: {
        serializedName: "include",
        xmlName: "include",
        xmlElementName: "ListQueuesIncludeType",
        type: {
            name: "Sequence",
            element: {
                defaultValue: "metadata",
                isConstant: true,
                type: {
                    name: "String"
                }
            }
        }
    },
    collectionFormat: coreHttp.QueryCollectionFormat.Csv
};
const metadata = {
    parameterPath: ["options", "metadata"],
    mapper: {
        serializedName: "x-ms-meta",
        xmlName: "x-ms-meta",
        type: {
            name: "Dictionary",
            value: { type: { name: "String" } }
        },
        headerCollectionPrefix: "x-ms-meta-"
    }
};
const comp3 = {
    parameterPath: "comp",
    mapper: {
        defaultValue: "metadata",
        isConstant: true,
        serializedName: "comp",
        type: {
            name: "String"
        }
    }
};
const comp4 = {
    parameterPath: "comp",
    mapper: {
        defaultValue: "acl",
        isConstant: true,
        serializedName: "comp",
        type: {
            name: "String"
        }
    }
};
const queueAcl = {
    parameterPath: ["options", "queueAcl"],
    mapper: {
        serializedName: "queueAcl",
        xmlName: "SignedIdentifiers",
        xmlIsWrapped: true,
        xmlElementName: "SignedIdentifier",
        type: {
            name: "Sequence",
            element: {
                type: {
                    name: "Composite",
                    className: "SignedIdentifier"
                }
            }
        }
    }
};
const numberOfMessages = {
    parameterPath: ["options", "numberOfMessages"],
    mapper: {
        constraints: {
            InclusiveMinimum: 1
        },
        serializedName: "numofmessages",
        xmlName: "numofmessages",
        type: {
            name: "Number"
        }
    }
};
const visibilityTimeout = {
    parameterPath: ["options", "visibilityTimeout"],
    mapper: {
        constraints: {
            InclusiveMaximum: 604800,
            InclusiveMinimum: 0
        },
        serializedName: "visibilitytimeout",
        xmlName: "visibilitytimeout",
        type: {
            name: "Number"
        }
    }
};
const queueMessage = {
    parameterPath: "queueMessage",
    mapper: QueueMessage
};
const messageTimeToLive = {
    parameterPath: ["options", "messageTimeToLive"],
    mapper: {
        constraints: {
            InclusiveMinimum: -1
        },
        serializedName: "messagettl",
        xmlName: "messagettl",
        type: {
            name: "Number"
        }
    }
};
const peekonly = {
    parameterPath: "peekonly",
    mapper: {
        defaultValue: "true",
        isConstant: true,
        serializedName: "peekonly",
        type: {
            name: "String"
        }
    }
};
const queueMessage1 = {
    parameterPath: ["options", "queueMessage"],
    mapper: QueueMessage
};
const popReceipt = {
    parameterPath: "popReceipt",
    mapper: {
        serializedName: "popreceipt",
        required: true,
        xmlName: "popreceipt",
        type: {
            name: "String"
        }
    }
};
const visibilityTimeout1 = {
    parameterPath: "visibilityTimeout",
    mapper: {
        constraints: {
            InclusiveMaximum: 604800,
            InclusiveMinimum: 0
        },
        serializedName: "visibilitytimeout",
        required: true,
        xmlName: "visibilitytimeout",
        type: {
            name: "Number"
        }
    }
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Class representing a Service. */
class Service {
    /**
     * Initialize a new instance of the class Service class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * Sets properties for a storage account's Queue service endpoint, including properties for Storage
     * Analytics and CORS (Cross-Origin Resource Sharing) rules
     * @param properties The StorageService properties.
     * @param options The options parameters.
     */
    setProperties(properties, options) {
        const operationArguments = {
            properties,
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, setPropertiesOperationSpec);
    }
    /**
     * gets the properties of a storage account's Queue service, including properties for Storage Analytics
     * and CORS (Cross-Origin Resource Sharing) rules.
     * @param options The options parameters.
     */
    getProperties(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec);
    }
    /**
     * Retrieves statistics related to replication for the Queue service. It is only available on the
     * secondary location endpoint when read-access geo-redundant replication is enabled for the storage
     * account.
     * @param options The options parameters.
     */
    getStatistics(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, getStatisticsOperationSpec);
    }
    /**
     * The List Queues Segment operation returns a list of the queues under the specified account
     * @param options The options parameters.
     */
    listQueuesSegment(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, listQueuesSegmentOperationSpec);
    }
}
// Operation Specifications
const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true);
const setPropertiesOperationSpec = {
    path: "/",
    httpMethod: "PUT",
    responses: {
        202: {
            headersMapper: ServiceSetPropertiesHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: ServiceSetPropertiesExceptionHeaders
        }
    },
    requestBody: properties,
    queryParameters: [
        restype,
        comp,
        timeoutInSeconds
    ],
    urlParameters: [url],
    headerParameters: [
        contentType,
        accept,
        version,
        requestId
    ],
    isXML: true,
    contentType: "application/xml; charset=utf-8",
    mediaType: "xml",
    serializer: xmlSerializer
};
const getPropertiesOperationSpec = {
    path: "/",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: QueueServiceProperties,
            headersMapper: ServiceGetPropertiesHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: ServiceGetPropertiesExceptionHeaders
        }
    },
    queryParameters: [
        restype,
        comp,
        timeoutInSeconds
    ],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer
};
const getStatisticsOperationSpec = {
    path: "/",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: QueueServiceStatistics,
            headersMapper: ServiceGetStatisticsHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: ServiceGetStatisticsExceptionHeaders
        }
    },
    queryParameters: [
        restype,
        timeoutInSeconds,
        comp1
    ],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer
};
const listQueuesSegmentOperationSpec = {
    path: "/",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: ListQueuesSegmentResponse,
            headersMapper: ServiceListQueuesSegmentHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: ServiceListQueuesSegmentExceptionHeaders
        }
    },
    queryParameters: [
        timeoutInSeconds,
        comp2,
        prefix,
        marker,
        maxPageSize,
        include
    ],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Class representing a Queue. */
class Queue {
    /**
     * Initialize a new instance of the class Queue class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * creates a new queue under the given account.
     * @param options The options parameters.
     */
    create(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, createOperationSpec);
    }
    /**
     * operation permanently deletes the specified queue
     * @param options The options parameters.
     */
    delete(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, deleteOperationSpec);
    }
    /**
     * Retrieves user-defined metadata and queue properties on the specified queue. Metadata is associated
     * with the queue as name-values pairs.
     * @param options The options parameters.
     */
    getProperties(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$1);
    }
    /**
     * sets user-defined metadata on the specified queue. Metadata is associated with the queue as
     * name-value pairs.
     * @param options The options parameters.
     */
    setMetadata(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec);
    }
    /**
     * returns details about any stored access policies specified on the queue that may be used with Shared
     * Access Signatures.
     * @param options The options parameters.
     */
    getAccessPolicy(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, getAccessPolicyOperationSpec);
    }
    /**
     * sets stored access policies for the queue that may be used with Shared Access Signatures
     * @param options The options parameters.
     */
    setAccessPolicy(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, setAccessPolicyOperationSpec);
    }
}
// Operation Specifications
const xmlSerializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ true);
const createOperationSpec = {
    path: "/{queueName}",
    httpMethod: "PUT",
    responses: {
        201: {
            headersMapper: QueueCreateHeaders
        },
        204: {
            headersMapper: QueueCreateHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueCreateExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1,
        metadata
    ],
    isXML: true,
    serializer: xmlSerializer$1
};
const deleteOperationSpec = {
    path: "/{queueName}",
    httpMethod: "DELETE",
    responses: {
        204: {
            headersMapper: QueueDeleteHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueDeleteExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$1
};
const getPropertiesOperationSpec$1 = {
    path: "/{queueName}",
    httpMethod: "GET",
    responses: {
        200: {
            headersMapper: QueueGetPropertiesHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueGetPropertiesExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds, comp3],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$1
};
const setMetadataOperationSpec = {
    path: "/{queueName}",
    httpMethod: "PUT",
    responses: {
        204: {
            headersMapper: QueueSetMetadataHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueSetMetadataExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds, comp3],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1,
        metadata
    ],
    isXML: true,
    serializer: xmlSerializer$1
};
const getAccessPolicyOperationSpec = {
    path: "/{queueName}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: {
                type: {
                    name: "Sequence",
                    element: {
                        type: { name: "Composite", className: "SignedIdentifier" }
                    }
                },
                serializedName: "SignedIdentifiers",
                xmlName: "SignedIdentifiers",
                xmlIsWrapped: true,
                xmlElementName: "SignedIdentifier"
            },
            headersMapper: QueueGetAccessPolicyHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueGetAccessPolicyExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds, comp4],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$1
};
const setAccessPolicyOperationSpec = {
    path: "/{queueName}",
    httpMethod: "PUT",
    responses: {
        204: {
            headersMapper: QueueSetAccessPolicyHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: QueueSetAccessPolicyExceptionHeaders
        }
    },
    requestBody: queueAcl,
    queryParameters: [timeoutInSeconds, comp4],
    urlParameters: [url],
    headerParameters: [
        contentType,
        accept,
        version,
        requestId
    ],
    isXML: true,
    contentType: "application/xml; charset=utf-8",
    mediaType: "xml",
    serializer: xmlSerializer$1
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Class representing a Messages. */
class Messages {
    /**
     * Initialize a new instance of the class Messages class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * The Dequeue operation retrieves one or more messages from the front of the queue.
     * @param options The options parameters.
     */
    dequeue(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, dequeueOperationSpec);
    }
    /**
     * The Clear operation deletes all messages from the specified queue.
     * @param options The options parameters.
     */
    clear(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, clearOperationSpec);
    }
    /**
     * The Enqueue operation adds a new message to the back of the message queue. A visibility timeout can
     * also be specified to make the message invisible until the visibility timeout expires. A message must
     * be in a format that can be included in an XML request with UTF-8 encoding. The encoded message can
     * be up to 64 KB in size for versions 2011-08-18 and newer, or 8 KB in size for previous versions.
     * @param queueMessage A Message object which can be stored in a Queue
     * @param options The options parameters.
     */
    enqueue(queueMessage, options) {
        const operationArguments = {
            queueMessage,
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, enqueueOperationSpec);
    }
    /**
     * The Peek operation retrieves one or more messages from the front of the queue, but does not alter
     * the visibility of the message.
     * @param options The options parameters.
     */
    peek(options) {
        const operationArguments = {
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, peekOperationSpec);
    }
}
// Operation Specifications
const xmlSerializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ true);
const dequeueOperationSpec = {
    path: "/{queueName}/messages",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: {
                type: {
                    name: "Sequence",
                    element: {
                        type: { name: "Composite", className: "DequeuedMessageItem" }
                    }
                },
                serializedName: "DequeuedMessagesList",
                xmlName: "QueueMessagesList",
                xmlIsWrapped: true,
                xmlElementName: "QueueMessage"
            },
            headersMapper: MessagesDequeueHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessagesDequeueExceptionHeaders
        }
    },
    queryParameters: [
        timeoutInSeconds,
        numberOfMessages,
        visibilityTimeout
    ],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$2
};
const clearOperationSpec = {
    path: "/{queueName}/messages",
    httpMethod: "DELETE",
    responses: {
        204: {
            headersMapper: MessagesClearHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessagesClearExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$2
};
const enqueueOperationSpec = {
    path: "/{queueName}/messages",
    httpMethod: "POST",
    responses: {
        201: {
            bodyMapper: {
                type: {
                    name: "Sequence",
                    element: { type: { name: "Composite", className: "EnqueuedMessage" } }
                },
                serializedName: "EnqueuedMessageList",
                xmlName: "QueueMessagesList",
                xmlIsWrapped: true,
                xmlElementName: "QueueMessage"
            },
            headersMapper: MessagesEnqueueHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessagesEnqueueExceptionHeaders
        }
    },
    requestBody: queueMessage,
    queryParameters: [
        timeoutInSeconds,
        visibilityTimeout,
        messageTimeToLive
    ],
    urlParameters: [url],
    headerParameters: [
        contentType,
        accept,
        version,
        requestId
    ],
    isXML: true,
    contentType: "application/xml; charset=utf-8",
    mediaType: "xml",
    serializer: xmlSerializer$2
};
const peekOperationSpec = {
    path: "/{queueName}/messages",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: {
                type: {
                    name: "Sequence",
                    element: {
                        type: { name: "Composite", className: "PeekedMessageItem" }
                    }
                },
                serializedName: "PeekedMessagesList",
                xmlName: "QueueMessagesList",
                xmlIsWrapped: true,
                xmlElementName: "QueueMessage"
            },
            headersMapper: MessagesPeekHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessagesPeekExceptionHeaders
        }
    },
    queryParameters: [
        timeoutInSeconds,
        numberOfMessages,
        peekonly
    ],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$2
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Class representing a MessageId. */
class MessageId {
    /**
     * Initialize a new instance of the class MessageId class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * The Update operation was introduced with version 2011-08-18 of the Queue service API. The Update
     * Message operation updates the visibility timeout of a message. You can also use this operation to
     * update the contents of a message. A message must be in a format that can be included in an XML
     * request with UTF-8 encoding, and the encoded message can be up to 64KB in size.
     * @param popReceipt Required. Specifies the valid pop receipt value returned from an earlier call to
     *                   the Get Messages or Update Message operation.
     * @param visibilityTimeout Optional. Specifies the new visibility timeout value, in seconds, relative
     *                          to server time. The default value is 30 seconds. A specified value must be larger than or equal to 1
     *                          second, and cannot be larger than 7 days, or larger than 2 hours on REST protocol versions prior to
     *                          version 2011-08-18. The visibility timeout of a message can be set to a value later than the expiry
     *                          time.
     * @param options The options parameters.
     */
    update(popReceipt, visibilityTimeout, options) {
        const operationArguments = {
            popReceipt,
            visibilityTimeout,
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, updateOperationSpec);
    }
    /**
     * The Delete operation deletes the specified message.
     * @param popReceipt Required. Specifies the valid pop receipt value returned from an earlier call to
     *                   the Get Messages or Update Message operation.
     * @param options The options parameters.
     */
    delete(popReceipt, options) {
        const operationArguments = {
            popReceipt,
            options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
        };
        return this.client.sendOperationRequest(operationArguments, deleteOperationSpec$1);
    }
}
// Operation Specifications
const xmlSerializer$3 = new coreHttp.Serializer(Mappers, /* isXml */ true);
const updateOperationSpec = {
    path: "/{queueName}/messages/{messageid}",
    httpMethod: "PUT",
    responses: {
        204: {
            headersMapper: MessageIdUpdateHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessageIdUpdateExceptionHeaders
        }
    },
    requestBody: queueMessage1,
    queryParameters: [
        timeoutInSeconds,
        popReceipt,
        visibilityTimeout1
    ],
    urlParameters: [url],
    headerParameters: [
        contentType,
        accept,
        version,
        requestId
    ],
    isXML: true,
    contentType: "application/xml; charset=utf-8",
    mediaType: "xml",
    serializer: xmlSerializer$3
};
const deleteOperationSpec$1 = {
    path: "/{queueName}/messages/{messageid}",
    httpMethod: "DELETE",
    responses: {
        204: {
            headersMapper: MessageIdDeleteHeaders
        },
        default: {
            bodyMapper: StorageError,
            headersMapper: MessageIdDeleteExceptionHeaders
        }
    },
    queryParameters: [timeoutInSeconds, popReceipt],
    urlParameters: [url],
    headerParameters: [
        version,
        requestId,
        accept1
    ],
    isXML: true,
    serializer: xmlSerializer$3
};

// Copyright (c) Microsoft Corporation.
/**
 * A StorageClient represents a based client class for {@link QueueServiceClient}, {@link QueueClient} and etc.
 */
class StorageClient {
    /**
     * Creates an instance of StorageClient.
     * @param url -
     * @param pipeline -
     */
    constructor(url, pipeline) {
        this.url = url;
        this.accountName = getAccountNameFromUrl(url);
        this.pipeline = pipeline;
        this.storageClientContext = getStorageClientContext(url, pipeline);
        // Retrieve credential from the pipeline.
        this.credential = new AnonymousCredential();
        for (const factory of this.pipeline.factories) {
            if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) ||
                factory instanceof AnonymousCredential) {
                this.credential = factory;
                break;
            }
            else {
                try {
                    const authPolicy = factory.create();
                    if (authPolicy.constructor.name === "BearerTokenAuthenticationPolicy") {
                        this.credential = factory;
                        break;
                    }
                }
                catch (err) {
                    // ignore errors in creating policy, the client instance may still work without the policy.
                }
            }
        }
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * Creates a span using the global tracer.
 * @internal
 */
const createSpan = coreTracing.createSpanFunction({
    packagePrefix: "Azure.Storage.Queue",
    namespace: "Microsoft.Storage"
});

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a Queue. Setting
 * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all
 * the values are set, this should be serialized with toString and set as the permissions field on a
 * {@link QueueSASSignatureValues} object. It is possible to construct the permissions string without this class, but
 * the order of the permissions is particular and this class guarantees correctness.
 */
class QueueSASPermissions {
    constructor() {
        /**
         * Specifies Read access granted.
         */
        this.read = false;
        /**
         * Specifies Add access granted.
         */
        this.add = false;
        /**
         * Specifies Update access granted.
         */
        this.update = false;
        /**
         * Specifies Process access granted.
         */
        this.process = false;
    }
    /**
     * Creates a {@link QueueSASPermissions} from the specified permissions string. This method will throw an
     * Error if it encounters a character that does not correspond to a valid permission.
     *
     * @param permissions -
     */
    static parse(permissions) {
        const queueSASPermissions = new QueueSASPermissions();
        for (const char of permissions) {
            switch (char) {
                case "r":
                    queueSASPermissions.read = true;
                    break;
                case "a":
                    queueSASPermissions.add = true;
                    break;
                case "u":
                    queueSASPermissions.update = true;
                    break;
                case "p":
                    queueSASPermissions.process = true;
                    break;
                default:
                    throw new RangeError(`Invalid permission: ${char}`);
            }
        }
        return queueSASPermissions;
    }
    /**
     * Converts the given permissions to a string. Using this method will guarantee the permissions are in an
     * order accepted by the service.
     *
     * @returns A string which represents the QueueSASPermissions
     */
    toString() {
        const permissions = [];
        if (this.read) {
            permissions.push("r");
        }
        if (this.add) {
            permissions.push("a");
        }
        if (this.update) {
            permissions.push("u");
        }
        if (this.process) {
            permissions.push("p");
        }
        return permissions.join("");
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * ONLY AVAILABLE IN NODE.JS RUNTIME.
 *
 * Creates an instance of SASQueryParameters.
 *
 * Only accepts required settings needed to create a SAS. For optional settings please
 * set corresponding properties directly, such as permissions, startsOn and identifier.
 *
 * WARNING: When identifier is not provided, permissions and expiresOn are required.
 * You MUST assign value to identifier or expiresOn & permissions manually if you initial with
 * this constructor.
 *
 * @param queueSASSignatureValues -
 * @param sharedKeyCredential -
 */
function generateQueueSASQueryParameters(queueSASSignatureValues, sharedKeyCredential) {
    if (!queueSASSignatureValues.identifier &&
        !(queueSASSignatureValues.permissions && queueSASSignatureValues.expiresOn)) {
        throw new RangeError("Must provide 'permissions' and 'expiresOn' for Queue SAS generation when 'identifier' is not provided.");
    }
    const version = queueSASSignatureValues.version
        ? queueSASSignatureValues.version
        : SERVICE_VERSION;
    let verifiedPermissions;
    // Calling parse and toString guarantees the proper ordering and throws on invalid characters.
    if (queueSASSignatureValues.permissions) {
        verifiedPermissions = QueueSASPermissions.parse(queueSASSignatureValues.permissions.toString()).toString();
    }
    // Signature is generated on the un-url-encoded values.
    const stringToSign = [
        verifiedPermissions ? verifiedPermissions : "",
        queueSASSignatureValues.startsOn
            ? truncatedISO8061Date(queueSASSignatureValues.startsOn, false)
            : "",
        queueSASSignatureValues.expiresOn
            ? truncatedISO8061Date(queueSASSignatureValues.expiresOn, false)
            : "",
        getCanonicalName(sharedKeyCredential.accountName, queueSASSignatureValues.queueName),
        queueSASSignatureValues.identifier,
        queueSASSignatureValues.ipRange ? ipRangeToString(queueSASSignatureValues.ipRange) : "",
        queueSASSignatureValues.protocol ? queueSASSignatureValues.protocol : "",
        version
    ].join("\n");
    const signature = sharedKeyCredential.computeHMACSHA256(stringToSign);
    return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, queueSASSignatureValues.protocol, queueSASSignatureValues.startsOn, queueSASSignatureValues.expiresOn, queueSASSignatureValues.ipRange, queueSASSignatureValues.identifier);
}
function getCanonicalName(accountName, queueName) {
    // Queue: "/queue/account/queueName"
    return `/queue/${accountName}/${queueName}`;
}

// Copyright (c) Microsoft Corporation.
/**
 * A QueueClient represents a URL to an Azure Storage Queue's messages allowing you to manipulate its messages.
 */
class QueueClient extends StorageClient {
    constructor(urlOrConnectionString, credentialOrPipelineOrQueueName, 
    // Legacy, no way to fix the eslint error without breaking. Disable the rule for this line.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */
    options) {
        options = options || {};
        let pipeline;
        let url;
        if (credentialOrPipelineOrQueueName instanceof Pipeline) {
            // (url: string, pipeline: Pipeline)
            url = urlOrConnectionString;
            pipeline = credentialOrPipelineOrQueueName;
        }
        else if ((coreHttp.isNode && credentialOrPipelineOrQueueName instanceof StorageSharedKeyCredential) ||
            credentialOrPipelineOrQueueName instanceof AnonymousCredential ||
            coreHttp.isTokenCredential(credentialOrPipelineOrQueueName)) {
            // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
            url = urlOrConnectionString;
            pipeline = newPipeline(credentialOrPipelineOrQueueName, options);
        }
        else if (!credentialOrPipelineOrQueueName &&
            typeof credentialOrPipelineOrQueueName !== "string") {
            // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions)
            // The second paramter is undefined. Use anonymous credential.
            url = urlOrConnectionString;
            pipeline = newPipeline(new AnonymousCredential(), options);
        }
        else if (credentialOrPipelineOrQueueName &&
            typeof credentialOrPipelineOrQueueName === "string") {
            // (connectionString: string, containerName: string, queueName: string, options?: StoragePipelineOptions)
            const extractedCreds = extractConnectionStringParts(urlOrConnectionString);
            if (extractedCreds.kind === "AccountConnString") {
                {
                    const queueName = credentialOrPipelineOrQueueName;
                    const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
                    url = appendToURLPath(extractedCreds.url, queueName);
                    options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri);
                    pipeline = newPipeline(sharedKeyCredential, options);
                }
            }
            else if (extractedCreds.kind === "SASConnString") {
                const queueName = credentialOrPipelineOrQueueName;
                url = appendToURLPath(extractedCreds.url, queueName) + "?" + extractedCreds.accountSas;
                pipeline = newPipeline(new AnonymousCredential(), options);
            }
            else {
                throw new Error("Connection string must be either an Account connection string or a SAS connection string");
            }
        }
        else {
            throw new Error("Expecting non-empty strings for queueName parameter");
        }
        super(url, pipeline);
        this._name = this.getQueueNameFromUrl();
        this.queueContext = new Queue(this.storageClientContext);
        // MessagesContext
        // Build the url with "messages"
        const partsOfUrl = this.url.split("?");
        this._messagesUrl = partsOfUrl[1]
            ? appendToURLPath(partsOfUrl[0], "messages") + "?" + partsOfUrl[1]
            : appendToURLPath(partsOfUrl[0], "messages");
        this.messagesContext = new Messages(getStorageClientContext(this._messagesUrl, this.pipeline));
    }
    /**
     * The name of the queue.
     */
    get name() {
        return this._name;
    }
    getMessageIdContext(messageId) {
        // Build the url with messageId
        const partsOfUrl = this._messagesUrl.split("?");
        const urlWithMessageId = partsOfUrl[1]
            ? appendToURLPath(partsOfUrl[0], messageId) + "?" + partsOfUrl[1]
            : appendToURLPath(partsOfUrl[0], messageId);
        return new MessageId(getStorageClientContext(urlWithMessageId, this.pipeline));
    }
    /**
     * Creates a new queue under the specified account.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-queue4
     *
     * @param options - Options to Queue create operation.
     * @returns Response data for the Queue create operation.
     *
     * Example usage:
     *
     * ```js
     * const queueClient = queueServiceClient.getQueueClient("<new queue name>");
     * const createQueueResponse = await queueClient.create();
     * ```
     */
    async create(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-create", options);
        try {
            return await this.queueContext.create(Object.assign(Object.assign({}, updatedOptions), { abortSignal: options.abortSignal }));
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Creates a new queue under the specified account if it doesn't already exist.
     * If the queue already exists, it is not changed.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-queue4
     *
     * @param options -
     */
    async createIfNotExists(options = {}) {
        var _a, _b;
        const { span, updatedOptions } = createSpan("QueueClient-createIfNotExists", options);
        try {
            const response = await this.create(updatedOptions);
            // When a queue with the specified name already exists, the Queue service checks the metadata associated with the existing queue.
            // If the existing metadata is identical to the metadata specified on the Create Queue request, status code 204 (No Content) is returned.
            // If the existing metadata does not match, the operation fails and status code 409 (Conflict) is returned.
            if (response._response.status === 204) {
                return Object.assign({ succeeded: false }, response);
            }
            return Object.assign({ succeeded: true }, response);
        }
        catch (e) {
            if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "QueueAlreadyExists") {
                span.setStatus({
                    code: coreTracing.SpanStatusCode.ERROR,
                    message: "Expected exception when creating a queue only if it does not already exist."
                });
                return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });
            }
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Deletes the specified queue permanently if it exists.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-queue3
     *
     * @param options -
     */
    async deleteIfExists(options = {}) {
        var _a, _b;
        const { span, updatedOptions } = createSpan("QueueClient-deleteIfExists", options);
        try {
            const res = await this.delete(updatedOptions);
            return Object.assign({ succeeded: true }, res);
        }
        catch (e) {
            if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "QueueNotFound") {
                span.setStatus({
                    code: coreTracing.SpanStatusCode.ERROR,
                    message: "Expected exception when deleting a queue only if it exists."
                });
                return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response });
            }
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Deletes the specified queue permanently.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-queue3
     *
     * @param options - Options to Queue delete operation.
     * @returns Response data for the Queue delete operation.
     *
     * Example usage:
     *
     * ```js
     * const deleteQueueResponse = await queueClient.delete();
     * console.log(
     *   "Delete queue successfully, service assigned request Id:", deleteQueueResponse.requestId
     * );
     * ```
     */
    async delete(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-delete", options);
        try {
            return await this.queueContext.delete({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Returns true if the specified queue exists; false otherwise.
     *
     * NOTE: use this function with care since an existing queue might be deleted by other clients or
     * applications. Vice versa new queues might be added by other clients or applications after this
     * function completes.
     *
     * @param options - options to Exists operation.
     */
    async exists(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-exists", options);
        try {
            await this.getProperties({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
            return true;
        }
        catch (e) {
            if (e.statusCode === 404) {
                span.setStatus({
                    code: coreTracing.SpanStatusCode.ERROR,
                    message: "Expected exception when checking queue existence"
                });
                return false;
            }
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Gets all user-defined metadata and system properties for the specified
     * queue. Metadata is associated with the queue as name-values pairs.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-metadata
     *
     * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if
     * they originally contained uppercase characters. This differs from the metadata keys returned by
     * the `listQueues` method of {@link QueueServiceClient} using the `includeMetadata` option, which
     * will retain their original casing.
     *
     * @param options - Options to Queue get properties operation.
     * @returns Response data for the Queue get properties operation.
     */
    async getProperties(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-getProperties", options);
        try {
            return await this.queueContext.getProperties({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Sets one or more user-defined name-value pairs for the specified queue.
     *
     * If no option provided, or no metadata defined in the option parameter, the queue
     * metadata will be removed.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-metadata
     *
     * @param metadata - If no metadata provided, all existing metadata will be removed.
     * @param options - Options to Queue set metadata operation.
     * @returns Response data for the Queue set metadata operation.
     */
    async setMetadata(metadata, options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-setMetadata", options);
        try {
            return await this.queueContext.setMetadata({
                abortSignal: options.abortSignal,
                metadata,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Gets details about any stored access policies specified on the queue that may be used with Shared Access Signatures.
     *
     * WARNING: JavaScript Date will potential lost precision when parsing start and expiry string.
     * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z".
     *
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-acl
     *
     * @param options - Options to Queue get access policy operation.
     * @returns Response data for the Queue get access policy operation.
     */
    async getAccessPolicy(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-getAccessPolicy", options);
        try {
            const response = await this.queueContext.getAccessPolicy({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
            const res = {
                _response: response._response,
                date: response.date,
                requestId: response.requestId,
                clientRequestId: response.clientRequestId,
                signedIdentifiers: [],
                version: response.version,
                errorCode: response.errorCode
            };
            for (const identifier of response) {
                let accessPolicy = undefined;
                if (identifier.accessPolicy) {
                    accessPolicy = {
                        permissions: identifier.accessPolicy.permissions
                    };
                    if (identifier.accessPolicy.expiresOn) {
                        accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn);
                    }
                    if (identifier.accessPolicy.startsOn) {
                        accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn);
                    }
                }
                res.signedIdentifiers.push({
                    accessPolicy,
                    id: identifier.id
                });
            }
            return res;
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Sets stored access policies for the queue that may be used with Shared Access Signatures.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-acl
     *
     * @param queueAcl -
     * @param options - Options to Queue set access policy operation.
     * @returns Response data for the Queue set access policy operation.
     */
    async setAccessPolicy(queueAcl, options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-setAccessPolicy", options);
        try {
            const acl = [];
            for (const identifier of queueAcl || []) {
                acl.push({
                    accessPolicy: {
                        expiresOn: identifier.accessPolicy.expiresOn
                            ? truncatedISO8061Date(identifier.accessPolicy.expiresOn)
                            : undefined,
                        permissions: identifier.accessPolicy.permissions,
                        startsOn: identifier.accessPolicy.startsOn
                            ? truncatedISO8061Date(identifier.accessPolicy.startsOn)
                            : undefined
                    },
                    id: identifier.id
                });
            }
            return await this.queueContext.setAccessPolicy({
                abortSignal: options.abortSignal,
                queueAcl: acl,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Clear deletes all messages from a queue.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/clear-messages
     *
     * @param options - Options to clear messages operation.
     * @returns Response data for the clear messages operation.
     */
    async clearMessages(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-clearMessages", options);
        try {
            return await this.messagesContext.clear({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * sendMessage adds a new message to the back of a queue. The visibility timeout specifies how long
     * the message should be invisible to Dequeue and Peek operations.
     * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding.
     * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-message
     *
     * @param messageText - Text of the message to send
     * @param options - Options to send messages operation.
     * @returns Response data for the send messages operation.
     *
     * Example usage:
     *
     * ```js
     * const sendMessageResponse = await queueClient.sendMessage("Hello World!");
     * console.log(
     *   "Sent message successfully, service assigned message Id:", sendMessageResponse.messageId,
     *   "service assigned request Id:", sendMessageResponse.requestId
     * );
     * ```
     */
    async sendMessage(messageText, options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-sendMessage", options);
        try {
            const response = await this.messagesContext.enqueue({
                messageText: messageText
            }, updatedOptions);
            const item = response[0];
            return {
                _response: response._response,
                date: response.date,
                requestId: response.requestId,
                clientRequestId: response.clientRequestId,
                version: response.version,
                errorCode: response.errorCode,
                messageId: item.messageId,
                popReceipt: item.popReceipt,
                nextVisibleOn: item.nextVisibleOn,
                insertedOn: item.insertedOn,
                expiresOn: item.expiresOn
            };
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * receiveMessages retrieves one or more messages from the front of the queue.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-messages
     *
     * @param options - Options to receive messages operation.
     * @returns Response data for the receive messages operation.
     *
     * Example usage:
     *
     * ```js
     * const response = await queueClient.receiveMessages();
     * if (response.receivedMessageItems.length == 1) {
     *   const receivedMessageItem = response.receivedMessageItems[0];
     *   console.log("Processing & deleting message with content:", receivedMessageItem.messageText);
     *   const deleteMessageResponse = await queueClient.deleteMessage(
     *     receivedMessageItem.messageId,
     *     receivedMessageItem.popReceipt
     *   );
     *   console.log(
     *     "Delete message successfully, service assigned request Id:",
     *     deleteMessageResponse.requestId
     *   );
     * }
     * ```
     */
    async receiveMessages(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-receiveMessages", options);
        try {
            const response = await this.messagesContext.dequeue(updatedOptions);
            const res = {
                _response: response._response,
                date: response.date,
                requestId: response.requestId,
                clientRequestId: response.clientRequestId,
                receivedMessageItems: [],
                version: response.version,
                errorCode: response.errorCode
            };
            for (const item of response) {
                res.receivedMessageItems.push(item);
            }
            return res;
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * peekMessages retrieves one or more messages from the front of the queue but does not alter the visibility of the message.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/peek-messages
     *
     * @param options - Options to peek messages operation.
     * @returns Response data for the peek messages operation.
     *
     * Example usage:
     *
     * ```js
     * const peekMessagesResponse = await queueClient.peekMessages();
     * console.log("The peeked message is:", peekMessagesResponse.peekedMessageItems[0].messageText);
     * ```
     */
    async peekMessages(options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-peekMessages", options);
        try {
            const response = await this.messagesContext.peek(updatedOptions);
            const res = {
                _response: response._response,
                date: response.date,
                requestId: response.requestId,
                clientRequestId: response.clientRequestId,
                peekedMessageItems: [],
                version: response.version,
                errorCode: response.errorCode
            };
            for (const item of response) {
                res.peekedMessageItems.push(item);
            }
            return res;
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * deleteMessage permanently removes the specified message from its queue.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-message2
     *
     * @param messageId - Id of the message.
     * @param popReceipt - A valid pop receipt value returned from an earlier call to the receive messages or update message operation.
     * @param options - Options to delete message operation.
     * @returns Response data for the delete message operation.
     */
    async deleteMessage(messageId, popReceipt, options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-deleteMessage", options);
        try {
            return await this.getMessageIdContext(messageId).delete(popReceipt, {
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Update changes a message's visibility timeout and contents.
     * The message content is up to 64KB in size, and must be in a format that can be included in an XML request with UTF-8 encoding.
     * To include markup in the message, the contents of the message must either be XML-escaped or Base64-encode.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/update-message
     *
     * @param messageId - Id of the message
     * @param popReceipt - A valid pop receipt value returned from an earlier call to the receive messages or update message operation.
     * @param message - Message to update. If this parameter is undefined, then the content of the message won't be updated.
     * @param visibilityTimeout - Specifies the new visibility timeout value, in seconds,
     *                                   relative to server time. The new value must be larger than or equal to 0,
     *                                   and cannot be larger than 7 days. The visibility timeout of a message cannot
     *                                   be set to a value later than the expiry time.
     *                                   A message can be updated until it has been deleted or has expired.
     * @param options - Options to update message operation.
     * @returns Response data for the update message operation.
     */
    async updateMessage(messageId, popReceipt, message, visibilityTimeout, options = {}) {
        const { span, updatedOptions } = createSpan("QueueClient-updateMessage", options);
        let queueMessage = undefined;
        if (message !== undefined) {
            queueMessage = { messageText: message };
        }
        try {
            return await this.getMessageIdContext(messageId).update(popReceipt, visibilityTimeout || 0, {
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions,
                queueMessage
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    getQueueNameFromUrl() {
        let queueName;
        try {
            //  URL may look like the following
            // "https://myaccount.queue.core.windows.net/myqueue?sasString".
            // "https://myaccount.queue.core.windows.net/myqueue".
            // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10001/devstoreaccount1/myqueue`
            // http://localhost:10001/devstoreaccount1/queuename
            const parsedUrl = coreHttp.URLBuilder.parse(this.url);
            if (parsedUrl.getHost().split(".")[1] === "queue") {
                // "https://myaccount.queue.core.windows.net/queuename".
                // .getPath() -> /queuename
                queueName = parsedUrl.getPath().split("/")[1];
            }
            else if (isIpEndpointStyle(parsedUrl)) {
                // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/queuename
                // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/queuename
                // .getPath() -> /devstoreaccount1/queuename
                queueName = parsedUrl.getPath().split("/")[2];
            }
            else {
                // "https://customdomain.com/queuename".
                // .getPath() -> /queuename
                queueName = parsedUrl.getPath().split("/")[1];
            }
            if (!queueName) {
                throw new Error("Provided queueName is invalid.");
            }
            return queueName;
        }
        catch (error) {
            throw new Error("Unable to extract queueName with provided information.");
        }
    }
    /**
     * Only available for QueueClient constructed with a shared key credential.
     *
     * Generates a Service Shared Access Signature (SAS) URI based on the client properties
     * and parameters passed in. The SAS is signed by the shared key credential of the client.
     *
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas
     *
     * @param options - Optional parameters.
     * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token.
     */
    generateSasUrl(options) {
        if (!(this.credential instanceof StorageSharedKeyCredential)) {
            throw RangeError("Can only generate the SAS when the client is initialized with a shared key credential");
        }
        const sas = generateQueueSASQueryParameters(Object.assign({ queueName: this.name }, options), this.credential).toString();
        return appendToURLQuery(this.url, sas);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * A QueueServiceClient represents a URL to the Azure Storage Queue service allowing you
 * to manipulate queues.
 */
class QueueServiceClient extends StorageClient {
    constructor(url, credentialOrPipeline, 
    // Legacy, no way to fix the eslint error without breaking. Disable the rule for this line.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */
    options) {
        let pipeline;
        if (credentialOrPipeline instanceof Pipeline) {
            pipeline = credentialOrPipeline;
        }
        else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) ||
            credentialOrPipeline instanceof AnonymousCredential ||
            coreHttp.isTokenCredential(credentialOrPipeline)) {
            pipeline = newPipeline(credentialOrPipeline, options);
        }
        else {
            // The second paramter is undefined. Use anonymous credential.
            pipeline = newPipeline(new AnonymousCredential(), options);
        }
        super(url, pipeline);
        this.serviceContext = new Service(this.storageClientContext);
    }
    /**
     * Creates an instance of QueueServiceClient.
     *
     * @param connectionString - Account connection string or a SAS connection string of an Azure storage account.
     *                                  [ Note - Account connection string can only be used in NODE.JS runtime. ]
     *                                  Account connection string example -
     *                                  `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net`
     *                                  SAS connection string example -
     *                                  `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString`
     * @param options - Options to configure the HTTP pipeline.
     * @returns A new QueueServiceClient object from the given connection string.
     */
    static fromConnectionString(connectionString, 
    // Legacy, no way to fix the eslint error without breaking. Disable the rule for this line.
    /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */
    options) {
        options = options || {};
        const extractedCreds = extractConnectionStringParts(connectionString);
        if (extractedCreds.kind === "AccountConnString") {
            {
                const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey);
                options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri);
                const pipeline = newPipeline(sharedKeyCredential, options);
                return new QueueServiceClient(extractedCreds.url, pipeline);
            }
        }
        else if (extractedCreds.kind === "SASConnString") {
            const pipeline = newPipeline(new AnonymousCredential(), options);
            return new QueueServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline);
        }
        else {
            throw new Error("Connection string must be either an Account connection string or a SAS connection string");
        }
    }
    /**
     * Creates a {@link QueueClient} object.
     *
     * @param queueName -
     * @returns a new QueueClient
     *
     * Example usage:
     *
     * ```js
     * const queueClient = queueServiceClient.getQueueClient("<new queue name>");
     * const createQueueResponse = await queueClient.create();
     * ```
     */
    getQueueClient(queueName) {
        return new QueueClient(appendToURLPath(this.url, queueName), this.pipeline);
    }
    /**
     * Returns a list of the queues under the specified account.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-queues1
     *
     * @param marker - A string value that identifies the portion of
     *                        the list of queues to be returned with the next listing operation. The
     *                        operation returns the continuationToken value within the response body if the
     *                        listing operation did not return all queues remaining to be listed
     *                        with the current page. The continuationToken value can be used as the value for
     *                        the marker parameter in a subsequent call to request the next page of list
     *                        items. The marker value is opaque to the client.
     * @param options - Options to list queues operation.
     * @returns Response data for the list queues segment operation.
     */
    async listQueuesSegment(marker, options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-listQueuesSegment", options);
        if (options.prefix === "") {
            options.prefix = undefined;
        }
        try {
            return await this.serviceContext.listQueuesSegment({
                abortSignal: options.abortSignal,
                marker: marker,
                maxPageSize: options.maxPageSize,
                prefix: options.prefix,
                include: options.include === undefined ? undefined : [options.include],
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Returns an AsyncIterableIterator for {@link ServiceListQueuesSegmentResponse} objects
     *
     * @param marker - A string value that identifies the portion of
     *                        the list of queues to be returned with the next listing operation. The
     *                        operation returns the continuationToken value within the response body if the
     *                        listing operation did not return all queues remaining to be listed
     *                        with the current page. The continuationToken value can be used as the value for
     *                        the marker parameter in a subsequent call to request the next page of list
     *                        items. The marker value is opaque to the client.
     * @param options - Options to list queues operation.
     */
    listSegments(marker, options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listSegments_1() {
            if (options.prefix === "") {
                options.prefix = undefined;
            }
            let listQueuesResponse;
            do {
                listQueuesResponse = yield tslib.__await(this.listQueuesSegment(marker, options));
                marker = listQueuesResponse.continuationToken;
                yield yield tslib.__await(yield tslib.__await(listQueuesResponse));
            } while (marker);
        });
    }
    /**
     * Returns an AsyncIterableIterator for {@link QueueItem} objects
     *
     * @param options - Options to list queues operation.
     */
    listItems(options = {}) {
        return tslib.__asyncGenerator(this, arguments, function* listItems_1() {
            var e_1, _a;
            if (options.prefix === "") {
                options.prefix = undefined;
            }
            let marker;
            try {
                for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) {
                    const segment = _c.value;
                    if (segment.queueItems) {
                        yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.queueItems)));
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b));
                }
                finally { if (e_1) throw e_1.error; }
            }
        });
    }
    /**
     * Returns an async iterable iterator to list all the queues
     * under the specified account.
     *
     * .byPage() returns an async iterable iterator to list the queues in pages.
     *
     * Example using `for await` syntax:
     *
     * ```js
     * let i = 1;
     * for await (const item of queueServiceClient.listQueues()) {
     *   console.log(`Queue${i}: ${item.name}`);
     *   i++;
     * }
     * ```
     *
     * Example using `iter.next()`:
     *
     * ```js
     * let i = 1;
     * let iterator = queueServiceClient.listQueues();
     * let item = await iterator.next();
     * while (!item.done) {
     *   console.log(`Queue${i}: ${iterator.value.name}`);
     *   i++;
     *   item = await iterator.next();
     * }
     * ```
     *
     * Example using `byPage()`:
     *
     * ```js
     * // passing optional maxPageSize in the page settings
     * let i = 1;
     * for await (const item2 of queueServiceClient.listQueues().byPage({ maxPageSize: 20 })) {
     *   if (item2.queueItems) {
     *     for (const queueItem of item2.queueItems) {
     *       console.log(`Queue${i}: ${queueItem.name}`);
     *       i++;
     *     }
     *   }
     * }
     * ```
     *
     * Example using paging with a marker:
     *
     * ```js
     * let i = 1;
     * let iterator = queueServiceClient.listQueues().byPage({ maxPageSize: 2 });
     * let item = (await iterator.next()).value;
     *
     * // Prints 2 queue names
     * if (item.queueItems) {
     *   for (const queueItem of item.queueItems) {
     *     console.log(`Queue${i}: ${queueItem.name}`);
     *     i++;
     *   }
     * }
     * // Gets next marker
     * let marker = item.continuationToken;
     *
     * // Passing next marker as continuationToken
     * iterator = queueServiceClient.listQueues().byPage({ continuationToken: marker, maxPageSize: 10 });
     * item = (await iterator.next()).value;
     *
     * // Prints 10 queue names
     * if (item.queueItems) {
     *   for (const queueItem of item.queueItems) {
     *     console.log(`Queue${i}: ${queueItem.name}`);
     *     i++;
     *   }
     * }
     * ```
     *
     * @param options - Options to list queues operation.
     * @returns An asyncIterableIterator that supports paging.
     */
    listQueues(options = {}) {
        if (options.prefix === "") {
            options.prefix = undefined;
        }
        const updatedOptions = Object.assign(Object.assign({}, options), (options.includeMetadata ? { include: "metadata" } : {}));
        // AsyncIterableIterator to iterate over queues
        const iter = this.listItems(updatedOptions);
        return {
            /**
             * The next method, part of the iteration protocol
             */
            next() {
                return iter.next();
            },
            /**
             * The connection to the async iterator, part of the iteration protocol
             */
            [Symbol.asyncIterator]() {
                return this;
            },
            /**
             * Return an AsyncIterableIterator that works a page at a time
             */
            byPage: (settings = {}) => {
                return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions));
            }
        };
    }
    /**
     * Gets the properties of a storage account’s Queue service, including properties
     * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-service-properties
     *
     * @param options - Options to get properties operation.
     * @returns Response data including the queue service properties.
     */
    async getProperties(options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-getProperties", options);
        try {
            return await this.serviceContext.getProperties({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Sets properties for a storage account’s Queue service endpoint, including properties
     * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-queue-service-properties
     *
     * @param properties -
     * @param options - Options to set properties operation.
     * @returns Response data for the Set Properties operation.
     */
    async setProperties(properties, options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-setProperties", options);
        try {
            return await this.serviceContext.setProperties(properties, {
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Retrieves statistics related to replication for the Queue service. It is only
     * available on the secondary location endpoint when read-access geo-redundant
     * replication is enabled for the storage account.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-queue-service-stats
     *
     * @param options - Options to get statistics operation.
     * @returns Response data for get statistics the operation.
     */
    async getStatistics(options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-getStatistics", options);
        try {
            return await this.serviceContext.getStatistics({
                abortSignal: options.abortSignal,
                tracingOptions: updatedOptions.tracingOptions
            });
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Creates a new queue under the specified account.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-queue4
     *
     * @param queueName - name of the queue to create
     * @param options - Options to Queue create operation.
     * @returns Response data for the Queue create operation.
     */
    async createQueue(queueName, options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-createQueue", options);
        try {
            return await this.getQueueClient(queueName).create(updatedOptions);
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Deletes the specified queue permanently.
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-queue3
     *
     * @param queueName - name of the queue to delete.
     * @param options - Options to Queue delete operation.
     * @returns Response data for the Queue delete operation.
     */
    async deleteQueue(queueName, options = {}) {
        const { span, updatedOptions } = createSpan("QueueServiceClient-deleteQueue", options);
        try {
            return await this.getQueueClient(queueName).delete(updatedOptions);
        }
        catch (e) {
            span.setStatus({
                code: coreTracing.SpanStatusCode.ERROR,
                message: e.message
            });
            throw e;
        }
        finally {
            span.end();
        }
    }
    /**
     * Only available for QueueServiceClient constructed with a shared key credential.
     *
     * Generates an account Shared Access Signature (SAS) URI based on the client properties
     * and parameters passed in. The SAS is signed by the shared key credential of the client.
     *
     * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas
     *
     * @param expiresOn - Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not specified.
     * @param permissions - Specifies the list of permissions to be associated with the SAS.
     * @param resourceTypes - Specifies the resource types associated with the shared access signature.
     * @param options - Optional parameters.
     * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token.
     */
    generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) {
        if (!(this.credential instanceof StorageSharedKeyCredential)) {
            throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential");
        }
        if (expiresOn === undefined) {
            const now = new Date();
            expiresOn = new Date(now.getTime() + 3600 * 1000);
        }
        const sas = generateAccountSASQueryParameters(Object.assign({ permissions,
            expiresOn,
            resourceTypes, services: AccountSASServices.parse("q").toString() }, options), this.credential).toString();
        return appendToURLQuery(this.url, sas);
    }
}

Object.defineProperty(exports, 'BaseRequestPolicy', {
    enumerable: true,
    get: function () {
        return coreHttp.BaseRequestPolicy;
    }
});
Object.defineProperty(exports, 'HttpHeaders', {
    enumerable: true,
    get: function () {
        return coreHttp.HttpHeaders;
    }
});
Object.defineProperty(exports, 'RequestPolicyOptions', {
    enumerable: true,
    get: function () {
        return coreHttp.RequestPolicyOptions;
    }
});
Object.defineProperty(exports, 'RestError', {
    enumerable: true,
    get: function () {
        return coreHttp.RestError;
    }
});
Object.defineProperty(exports, 'WebResource', {
    enumerable: true,
    get: function () {
        return coreHttp.WebResource;
    }
});
Object.defineProperty(exports, 'deserializationPolicy', {
    enumerable: true,
    get: function () {
        return coreHttp.deserializationPolicy;
    }
});
exports.AccountSASPermissions = AccountSASPermissions;
exports.AccountSASResourceTypes = AccountSASResourceTypes;
exports.AccountSASServices = AccountSASServices;
exports.AnonymousCredential = AnonymousCredential;
exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy;
exports.Credential = Credential;
exports.CredentialPolicy = CredentialPolicy;
exports.Pipeline = Pipeline;
exports.QueueClient = QueueClient;
exports.QueueSASPermissions = QueueSASPermissions;
exports.QueueServiceClient = QueueServiceClient;
exports.SASQueryParameters = SASQueryParameters;
exports.StorageBrowserPolicy = StorageBrowserPolicy;
exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory;
exports.StorageOAuthScopes = StorageOAuthScopes;
exports.StorageRetryPolicy = StorageRetryPolicy;
exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory;
exports.StorageSharedKeyCredential = StorageSharedKeyCredential;
exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy;
exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters;
exports.generateQueueSASQueryParameters = generateQueueSASQueryParameters;
exports.logger = logger;
exports.newPipeline = newPipeline;
//# sourceMappingURL=index.js.map