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AClB,YAA4B,iBAAR,EAAmB,KAAK,UAAU,GAAO,GAE3D,IAAO,EAAM,aAAe,GAC5B,IAAY,EAAM,kBAAoB,GAC1C,EAAO,QAAQ,KAAK,EAAK,IAEpB,KAAK,IAAI,iBAAiB,GAAQ,SAAQ,GAErD,CAQA,eAAA,GACE,OAAQ,KAAK,MAAM,aAAe,KAAK,WAAa,KAAK,MAAM,YAAc,KAAK,MAAM,gBAC1F,CAOA,YAAA,GACE,OAAO,KAAK,uBACT,MAAK,IAAM,KAAK,gBAChB,MAAK,GAAY,KAAK,UAAU,KAChC,OAAM,GAAK,KAAK,KAAK,QAAS,IACnC,EAGF,OAAO,QAAU","file":"/npm/squiss@2.2.1/src/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/squiss@2.2.1/src/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","/*\n * Copyright (c) 2015-2017 TechnologyAdvice\n */\n\n'use strict'\n\nconst AWS = require('aws-sdk')\nconst EventEmitter = require('events').EventEmitter\nconst Message = require('./Message')\nconst url = require('url')\nconst TimeoutExtender = require('./TimeoutExtender')\n\n/**\n * The maximum number of messages that can be sent in an SQS sendMessageBatch request.\n * @type {number}\n */\nconst AWS_MAX_SEND_BATCH = 10\n\n/**\n * Option defaults.\n * @type {Object}\n */\nconst optDefaults = {\n  receiveBatchSize: 10,\n  receiveWaitTimeSecs: 20,\n  deleteBatchSize: 10,\n  deleteWaitMs: 2000,\n  maxInFlight: 100,\n  unwrapSns: false,\n  bodyFormat: 'plain',\n  correctQueueUrl: false,\n  pollRetryMs: 2000,\n  activePollIntervalMs: 0,\n  idlePollIntervalMs: 0,\n  delaySecs: 0,\n  maxMessageBytes: 262144,\n  messageRetentionSecs: 345600,\n  autoExtendTimeout: false\n}\n\n/**\n * Squiss is a high-volume-capable Amazon SQS polling class. See README for usage details.\n */\nclass Squiss extends EventEmitter {\n\n  /**\n   * Creates a new Squiss object.\n   * @param {Object} opts A map of options to configure this instance\n   * @param {Function} [opts.SQS] An instance of the official SQS Client, or an SQS constructor function to use\n   *    rather than the default one provided by AWS.SQS\n   * @param {Object} [opts.awsConfig] An object mapping to pass to the SQS constructor, configuring the\n   *    aws-sdk library. This is commonly used to set the AWS region, or the user credentials. See\n   *    http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html\n   * @param {string} [opts.queueUrl] The URL of the queue to be polled. If not specified, opts.queueName is\n   *    required.\n   * @param {string} [opts.queueName] The name of the queue to be polled. Used only if opts.queueUrl is not\n   *    specified.\n   * @param {string} [opts.accountNumber] If a queueName is specified, the accountNumber of the queue\n   *    owner can optionally be specified to access a queue in a different AWS account.\n   * @param {boolean} [opts.correctQueueUrl=false] Changes the protocol, host, and port of the queue URL to match the\n   *    configured SQS endpoint, applicable only if opts.queueName is specified. This can be useful for testing against\n   *    a stubbed SQS service, such as ElasticMQ.\n   * @param {number} [opts.deleteBatchSize=10] The number of messages to delete at one time. Squiss will trigger a\n   *    batch delete when this limit is reached, or when deleteWaitMs milliseconds have passed since the first queued\n   *    delete in the batch; whichever comes first. Set to 1 to make all deletes immediate. Maximum 10.\n   * @param {number} [opts.deleteWaitMs=2000] The number of milliseconds to wait after the first queued message\n   *    deletion before deleting the message(s) from SQS\n   * @param {number} [opts.maxInFlight=100] The number of messages to keep \"in-flight\", or processing simultaneously.\n   *    When this cap is reached, no more messages will be polled until currently in-flight messages are marked as\n   *    deleted or handled. Setting this to 0 will uncap your inFlight messages, pulling and delivering messages\n   *    as long as there are messages to pull.\n   * @param {number} [opts.receiveBatchSize=10] The number of messages to receive at one time. Maximum 10 or\n   *    maxInFlight, whichever is lower.\n   * @param {number} [opts.receiveWaitTimeSecs=20] The number of seconds for which to hold open the SQS call to\n   *    receive messages, when no message is currently available. It is recommended to set this high, as Squiss will\n   *    re-open the receiveMessage HTTP request as soon as the last one ends. Maximum 20.\n   * @param {boolean} [opts.unwrapSns=false] Set to `true` to denote that Squiss should treat each message as though\n   *    it comes from a queue subscribed to an SNS endpoint, and automatically extract the message from the SNS\n   *    metadata wrapper.\n   * @param {string} [opts.bodyFormat=\"plain\"] The format of the incoming message. Set to \"json\" to automatically call\n   *    `JSON.parse()` on each incoming message.\n   * @param {number} [opts.visibilityTimeoutSecs] The SQS VisibilityTimeout to apply to each message. This is the\n   *    number of seconds that each received message should be made inaccessible to other receive calls, so that a\n   *    message will not be received more than once before it is processed and deleted. If not specified, the default\n   *    for the SQS queue will be used when receiving messages, and the SQS default (30) will be used when creating a\n   *    queue.\n   * @param {number} [opts.pollRetryMs=2000] The number of milliseconds to wait before retrying when Squiss's call to\n   *    retrieve messages from SQS fails.\n   * @param {number} [opts.activePollIntervalMs=0] The number of milliseconds to wait between requesting batches of\n   *    messages when the queue is not empty, and the maxInFlight cap has not been hit.\n   * @param {number} [opts.idlePollIntervalMs=0] The number of milliseconds to wait before requesting a batch of\n   *    messages when the queue was empty on the prior request.\n   * @param {number} [opts.delaySecs=0] The number of milliseconds by which to delay the delivery of new messages into\n   *    the queue by default. This is only used when calling {@link #createQueue}.\n   * @param {number} [opts.maxMessageBytes=262144] The maximum size of a single message, in bytes, that the queue can\n   *    support. This is only used when calling {@link #createQueue}. Default is the maximum, 256KB.\n   * @param {number} [opts.messageRetentionSecs=345600] The amount of time for which to retain messages in the queue\n   *    until they expire, in seconds. This is only used when calling {@link #createQueue}. Default is equivalent to\n   *    4 days, maximum is 1209600 (14 days).\n   * @param {boolean} [opts.autoExtendTimeout=false] If true, the VisibilityTimeout for all in-flight messages will\n   *    be automatically extended when there are 5 seconds remaining before the VisibilityTimeout would normally\n   *    expire. It will be extended by the VisibilityTimeout. The VisibilityTimeout used will be the one\n   *    specified in opts.visibilityTimeoutSecs, or the queue's configured VisibilityTimeout if that option is not set.\n   * @param {number} [opts.noExtensionsAfterSecs=43200] The age, in seconds, at which a message will no longer have\n   *    its VisibilityTimeout automatically extended if opts.autoExtendTimeout is true.\n   * @param {number} [opts.advancedCallMs=5000] The number of milliseconds before a message expires to send the API\n   *    call to extend its VisibilityTimeout. Applicable only if opts.autoExtendTimeout is true.\n   * @param {Object} [opts.queuePolicy] If specified, will be set as the access policy of the queue when\n   *    {@link #createQueue} is called. See http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html for\n   *    more information.\n   */\n  constructor(opts) {\n    super()\n    opts = opts || {}\n    if (opts.SQS) {\n      if (typeof opts.SQS === 'function') this.sqs = new opts.SQS(opts.awsConfig)\n      else this.sqs = opts.SQS\n    } else {\n      this.sqs = new AWS.SQS(opts.awsConfig)\n    }\n    this._opts = {}\n    Object.assign(this._opts, optDefaults, opts)\n    this._opts.deleteBatchSize = Math.min(this._opts.deleteBatchSize, 10)\n    this._opts.receiveBatchSize = Math.min(this._opts.receiveBatchSize,\n      this._opts.maxInFlight > 0 ? this._opts.maxInFlight : 10, 10)\n    this._running = false\n    this._inFlight = 0\n    this._delQueue = []\n    this._delTimer = null\n    this._queueUrl = opts.queueUrl\n    this._queueVisibilityTimeout = null\n    if (!opts.queueUrl && !opts.queueName) {\n      throw new Error('Squiss requires either the \"queueUrl\", or the \"queueName\".')\n    }\n    this._timeoutExtender = null\n  }\n\n  /**\n   * Getter for the number of messages currently in flight.\n   * @returns {number}\n   */\n  get inFlight() {\n    return this._inFlight\n  }\n\n  /**\n   * Getter to determine whether Squiss is currently polling or not.\n   * @returns {boolean}\n   */\n  get running() {\n    return this._running\n  }\n\n  /**\n   * Changes the visibility timeout of a message.\n   * @param {Message|string} msg The Message object or ReceiptHandle for which to change the VisibilityTimeout.\n   * @param {number} timeoutInSeconds Visibility timeout in seconds.\n   * @returns {Promise} Resolves on complete. Rejects with the official AWS SDK's error object.\n   */\n  changeMessageVisibility(msg, timeoutInSeconds) {\n    let receiptHandle = msg\n    if (msg instanceof Message) {\n      receiptHandle = msg.raw.ReceiptHandle\n    }\n    return this.getQueueUrl().then((queueUrl) =>\n      this.sqs.changeMessageVisibility({\n        QueueUrl: queueUrl,\n        ReceiptHandle: receiptHandle,\n        VisibilityTimeout: timeoutInSeconds\n      }).promise()\n    )\n  }\n\n  /**\n   * Creates the configured queue in Amazon SQS and retrieves its queue URL. Note that this method can only be called\n   * if Squiss was instantiated with the queueName property.\n   * @returns {Promise.<string>} Resolves with the URL of the created queue, rejects with the official AWS SDK's\n   *    error object.\n   */\n  createQueue() {\n    if (!this._opts.queueName) {\n      return Promise.reject(new Error('Squiss was not instantiated with a queueName'))\n    }\n    const params = {\n      QueueName: this._opts.queueName,\n      Attributes: {\n        ReceiveMessageWaitTimeSeconds: this._opts.receiveWaitTimeSecs.toString(),\n        DelaySeconds: this._opts.delaySecs.toString(),\n        MaximumMessageSize: this._opts.maxMessageBytes.toString(),\n        MessageRetentionPeriod: this._opts.messageRetentionSecs.toString()\n      }\n    }\n    if (this._opts.visibilityTimeoutSecs) {\n      params.Attributes.VisibilityTimeout = this._opts.visibilityTimeoutSecs.toString()\n    }\n    if (this._opts.queuePolicy) {\n      params.Attributes.Policy = this._opts.queuePolicy\n    }\n    return this.sqs.createQueue(params).promise().then(res => {\n      this._queueUrl = res.QueueUrl\n      return res.QueueUrl\n    })\n  }\n\n  /**\n   * Queues the given message for deletion. The message will actually be deleted from SQS per the settings\n   * supplied to the constructor.\n   * @param {Message} msg The message object to be deleted\n   */\n  deleteMessage(msg) {\n    if (!msg.raw) throw new Error('Squiss.deleteMessage requires a Message object')\n    this._delQueue.push({ Id: msg.raw.MessageId, ReceiptHandle: msg.raw.ReceiptHandle })\n    this.emit('delQueued', msg)\n    this.handledMessage(msg)\n    if (this._delQueue.length >= this._opts.deleteBatchSize) {\n      if (this._delTimer) {\n        clearTimeout(this._delTimer)\n        this._delTimer = null\n      }\n      const delBatch = this._delQueue.splice(0, this._opts.deleteBatchSize)\n      this._deleteMessages(delBatch)\n    } else if (!this._delTimer) {\n      this._delTimer = setTimeout(() => {\n        this._delTimer = null\n        const delBatch = this._delQueue.splice(0, this._delQueue.length)\n        this._deleteMessages(delBatch)\n      }, this._opts.deleteWaitMs)\n    }\n  }\n\n  /**\n   * Deletes the configured queue.\n   * @returns {Promise} Resolves on complete. Rejects with the official AWS SDK's error object.\n   */\n  deleteQueue() {\n    return this.getQueueUrl().then((queueUrl) => {\n      return this.sqs.deleteQueue({ QueueUrl: queueUrl }).promise()\n    })\n  }\n\n  /**\n   * Gets the queueUrl for the configured queue and sets this instance up to use it. Any calls to\n   * {@link #start} will wait until this function completes to begin polling.\n   * @returns {Promise.<string>} Resolves with the queue URL\n   * @private\n   */\n  getQueueUrl() {\n    if (this._queueUrl) return Promise.resolve(this._queueUrl)\n    const params = { QueueName: this._opts.queueName }\n    if (this._opts.accountNumber) {\n      params.QueueOwnerAWSAccountId = this._opts.accountNumber.toString()\n    }\n    return this.sqs.getQueueUrl(params).promise().then(data => {\n      this._queueUrl = data.QueueUrl\n      if (this._opts.correctQueueUrl) {\n        let newUrl = url.parse(this.sqs.config.endpoint)\n        const parsedQueueUrl = url.parse(this._queueUrl)\n        newUrl.pathname = parsedQueueUrl.pathname\n        this._queueUrl = url.format(newUrl)\n      }\n      return this._queueUrl\n    })\n  }\n\n  /**\n   * Retrieves the VisibilityTimeout set on the target queue. When a message is received, it has this many\n   * seconds to be deleted before it will become available to be received again.\n   * @returns {Promise.<number>} The VisibilityTimeout setting of the target queue, in seconds\n   */\n  getQueueVisibilityTimeout() {\n    if (this._queueVisibilityTimeout) return Promise.resolve(this._queueVisibilityTimeout)\n    return this.getQueueUrl().then(QueueUrl => {\n      return this.sqs.getQueueAttributes({\n        AttributeNames: [ 'VisibilityTimeout' ],\n        QueueUrl\n      }).promise()\n    }).then(res => {\n      if (!res.Attributes || !res.Attributes.VisibilityTimeout) {\n        throw new Error('AWS.SQS.GetQueueAttributes call did not return expected shape. Response: ' +\n          JSON.stringify(res))\n      }\n      this._queueVisibilityTimeout = parseInt(res.Attributes.VisibilityTimeout, 10)\n      return this._queueVisibilityTimeout\n    })\n  }\n\n  /**\n   * Informs Squiss that a message has been handled. This allows Squiss to decrement the number of in-flight\n   * messages without deleting one, which may be necessary in the event of an error.\n   * @param {Message} msg The message to be handled\n   */\n  handledMessage(msg) {\n    this._inFlight--\n    if (this._paused && this._slotsAvailable()) {\n      this._paused = false\n      this._startPoller()\n    }\n    this.emit('handled', msg)\n    if (!this._inFlight) {\n      this.emit('drained')\n    }\n  }\n\n  /**\n   * Releases a message back into the queue by changing its VisibilityTimeout to 0 and calling\n   * {@link #handledMessage}. Note that if this is used when the poller is running, the message will be\n   * immediately picked up and processed again (by this or any other application instance polling the same\n   * queue).\n   * @param {Message} msg The Message object for which to change the VisibilityTimeout.\n   * @returns {Promise} Resolves when the VisibilityTimeout has been changed. Rejects with the official AWS SDK's\n   * error object.\n   */\n  releaseMessage(msg) {\n    this.handledMessage(msg)\n    return this.changeMessageVisibility(msg, 0).then(res => {\n      this.emit('released', msg)\n      return res\n    })\n  }\n\n  /**\n   * Sends an individual message to the configured queue.\n   * @param {string|Object} message The message to be sent. Objects will be JSON.stringified.\n   * @param {number} [delay] The number of seconds by which to delay the delivery of the message, max 900. If not\n   *    specified, the queue default will be used.\n   * @param {Object} [attributes] An optional attributes mapping to associate with the message. For more information,\n   *    see http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessage-property.\n   * @returns {Promise.<{MessageId: string, MD5OfMessageAttributes: string, MD5OfMessageBody: string}>} Resolves with\n   *    the official AWS SDK sendMessage response, rejects with the official error object.\n   */\n  sendMessage(message, delay, attributes) {\n    return this.getQueueUrl().then((queueUrl) => {\n      const params = {\n        QueueUrl: queueUrl,\n        MessageBody: typeof message === 'object' ? JSON.stringify(message) : message\n      }\n      if (delay) params.DelaySeconds = delay\n      if (attributes) params.MessageAttributes = attributes\n      return this.sqs.sendMessage(params).promise()\n    })\n  }\n\n  /**\n   * Sends an array of any number of messages to the configured SQS queue, breaking them down into appropriate batch\n   * requests executed in parallel (or as much as the default HTTP agent allows). The response is closely aligned to\n   * the official AWS SDK's sendMessageBatch response, except the results from all batch requests are merged. Expect\n   * a result similar to:\n   *\n   * {\n   *   Successful: [\n   *     {Id: string, MessageId: string, MD5OfMessageAttributes: string, MD5OfMessageBody: string}\n   *   ],\n   *   Failed: [\n   *     {Id: string, SenderFault: boolean, Code: string, Message: string}\n   *   ]\n   * }\n   *\n   * See http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessageBatch-property for full details.\n   * The \"Id\" supplied in the response will be the index of the message in the original messages array, in string form.\n   * @param {string|Object||Array<string|Object>} messages An array of messages to be sent. Objects will be\n   *    JSON.stringified.\n   * @param {number} [delay] The number of seconds by which to delay the delivery of the messages, max 900. If not\n   *    specified, the queue default will be used.\n   * @param {Object} [attributes] An optional attributes mapping to associate with all messages. For more information,\n   *    see http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessageBatch-property.\n   * @returns {Promise.<{Successful: Array<{Id: string, MessageId: string, MD5OfMessageAttributes: string,\n   *    MD5OfMessageBody: string}>, Failed: Array<{Id: string, SenderFault: boolean, Code: string,\n   *    Message: string}>}>} Resolves with successful and failed messages, rejects with API error on critical failure.\n   */\n  sendMessages(messages, delay, attributes) {\n    const batches = []\n    const msgs = Array.isArray(messages) ? messages : [messages]\n    for (let i = 0; i < msgs.length; i++) {\n      if (i % AWS_MAX_SEND_BATCH === 0) batches.push([])\n      batches[batches.length - 1].push(msgs[i])\n    }\n    return Promise.all(batches.map((batch, idx) => {\n      return this._sendMessageBatch(batch, delay, attributes, idx * AWS_MAX_SEND_BATCH)\n    })).then((results) => {\n      const merged = {Successful: [], Failed: []}\n      results.forEach((res) => {\n        res.Successful.forEach(elem => merged.Successful.push(elem))\n        res.Failed.forEach(elem => merged.Failed.push(elem))\n      })\n      return merged\n    })\n  }\n\n  /**\n   * Starts the poller, if it's not already running.\n   * @returns {Promise} Resolves when the poller has been started; resolves instantly if the poller is already running\n   */\n  start() {\n    if (this._running) return Promise.resolve()\n    this._running = true\n    return this._startPoller()\n  }\n\n  /**\n   * Stops the poller.\n   * @param {boolean} [soft=false] If a soft stop is performed, any active SQS request for new messages will be left\n   *    open until it terminates naturally. Note that if this is the case, the message event may still be fired after\n   *    this function has been called.\n   */\n  stop(soft) {\n    if (!soft && this._activeReq) {\n      this._activeReq.abort()\n    }\n    this._running = false\n    this._paused = false\n  }\n\n  /**\n   * Deletes a batch of messages (maximum 10) from Amazon SQS.  If there is an error making the call to SQS, the\n   * `error` event will be emitted with an Error object. If SQS reports any issue deleting any of the messages,\n   * the `delError` event will be emitted with the failure object passed back by the AWS SDK.\n   * @param {Array<{Id: string, ReceiptHandle: string}>} batch The batch of messages to be deleted, in the format\n   *    required for sqs.deleteMessageBatch's Entries parameter.\n   * @private\n   */\n  _deleteMessages(batch) {\n    this.getQueueUrl().then((queueUrl) => {\n      return this.sqs.deleteMessageBatch({\n        QueueUrl: queueUrl,\n        Entries: batch\n      }).promise()\n    }).then((data) => {\n      if (data.Failed && data.Failed.length) {\n        data.Failed.forEach(fail => this.emit('delError', fail))\n      }\n      if (data.Successful && data.Successful.length) {\n        data.Successful.forEach(success => this.emit('deleted', success.Id))\n      }\n    }).catch((err) => {\n      this.emit('error', err)\n    })\n  }\n\n  /**\n   * Given an array of message bodies from SQS, this method will construct Message objects for each and emit them\n   * in separate `message` events.\n   * @param {Array<Object>} messages An array of SQS message objects, as returned from the aws sdk\n   * @private\n   */\n  _emitMessages(messages) {\n    messages.forEach((msg) => {\n      const message = new Message({\n        squiss: this,\n        unwrapSns: this._opts.unwrapSns,\n        bodyFormat: this._opts.bodyFormat,\n        msg\n      })\n      this._inFlight++\n      this.emit('message', message)\n    })\n  }\n\n  /**\n   * Gets a new batch of messages from Amazon SQS. Note that this function does no checking of the current inFlight\n   * count, or the current running status. A `message` event will be emitted for each new message, with the provided\n   * object being an instance of Squiss' Message class.\n   * @private\n   */\n  _getBatch(queueUrl) {\n    const next = this._getBatch.bind(this, queueUrl)\n    const params = {\n      QueueUrl: queueUrl,\n      MaxNumberOfMessages: this._opts.receiveBatchSize,\n      WaitTimeSeconds: this._opts.receiveWaitTimeSecs\n    }\n    if (this._opts.visibilityTimeoutSecs !== undefined) {\n      params.VisibilityTimeout = this._opts.visibilityTimeoutSecs\n    }\n    this._activeReq = this.sqs.receiveMessage(params)\n    this._activeReq.promise().then((data) => {\n      let gotMessages = true\n      this._activeReq = null\n      if (data && data.Messages) {\n        this.emit('gotMessages', data.Messages.length)\n        this._emitMessages(data.Messages)\n      } else {\n        this.emit('queueEmpty')\n        gotMessages = false\n      }\n      if (this._slotsAvailable()) {\n        if (gotMessages && this._opts.activePollIntervalMs) {\n          setTimeout(next, this._opts.activePollIntervalMs)\n        } else if (!gotMessages && this._opts.idlePollIntervalMs) {\n          setTimeout(next, this._opts.idlePollIntervalMs)\n        } else {\n          next()\n        }\n      } else {\n        this._paused = true\n        this.emit('maxInFlight')\n      }\n    }).catch((err) => {\n      this._activeReq = null\n      if (err.code && err.code === 'RequestAbortedError') {\n        this.emit('aborted')\n      } else {\n        setTimeout(next, this._opts.pollRetryMs)\n        this.emit('error', err)\n      }\n    })\n  }\n\n  /**\n   * Initializes the TimeoutExtender and associates it with this Squiss instance, if and only if the options passed\n   * to the constructor dictate that a TimeoutExtender is required.\n   * @returns {Promise} Resolves when the TimeoutExtender has been initialized\n   * @private\n   */\n  _initTimeoutExtender() {\n    if (!this._opts.autoExtendTimeout || this._timeoutExtender) return Promise.resolve()\n    return Promise.resolve().then(() => {\n      if (this._opts.visibilityTimeoutSecs) return this._opts.visibilityTimeoutSecs\n      return this.getQueueVisibilityTimeout()\n    }).then(visibilityTimeoutSecs => {\n      const opts = { visibilityTimeoutSecs }\n      if (this._opts.noExtensionsAfterSecs) opts.noExtensionsAfterSecs = this._opts.noExtensionsAfterSecs\n      if (this._opts.advancedCallMs) opts.advancedCallMs = this._opts.advancedCallMs\n      this._timeoutExtender = new TimeoutExtender(this, opts)\n    })\n  }\n\n  /**\n   * Sends a batch of a maximum of 10 messages to Amazon SQS. The Id generated for each will be the stringified\n   * index of each message in the array, plus the startIndex\n   * @param {Array<string|Object>} messages An array of messages to be sent. Objects will be JSON.stringified.\n   * @param {number} [delay] The number of seconds by which to delay the delivery of the messages, max 900. If not\n   *    specified, the queue default will be used.\n   * @param {Object} [attributes] An optional attributes mapping to associate with all messages. For more information,\n   *    see http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SQS.html#sendMessageBatch-property.\n   * @param {number} [startIndex=0] The index at which to start numbering the messages.\n   * @returns {Promise.<{Successful: Array<{Id: string, MessageId: string, MD5OfMessageAttributes: string,\n   *    MD5OfMessageBody: string}>, Failed: Array<{Id: string, SenderFault: boolean, Code: string,\n   *    Message: string}>}>} Resolves with successful and failed messages, rejects with API error on critical failure.\n   * @private\n   */\n  _sendMessageBatch(messages, delay, attributes, startIndex) {\n    const start = startIndex || 0\n    return this.getQueueUrl().then((queueUrl) => {\n      const params = {\n        QueueUrl: queueUrl,\n        Entries: []\n      }\n      messages.forEach((msg, idx) => {\n        const entry = {\n          Id: (start + idx).toString(),\n          MessageBody: typeof msg === 'object' ? JSON.stringify(msg) : msg\n        }\n        if (delay) entry.DelaySeconds = delay\n        if (attributes) entry.MessageAttributes = attributes\n        params.Entries.push(entry)\n      })\n      return this.sqs.sendMessageBatch(params).promise()\n    })\n  }\n\n  /**\n   * Determines if there are enough available slots to receive another batch of messages from Amazon SQS without going\n   * over the maxInFlight limit set in the constructor options.\n   * @returns {boolean}\n   * @private\n   */\n  _slotsAvailable() {\n    return !this._opts.maxInFlight || this._inFlight <= this._opts.maxInFlight - this._opts.receiveBatchSize\n  }\n\n  /**\n   * Starts the polling process, regardless of the status of the this._running or this._paused flags.\n   * @returns {Promise} Resolves when the poller has started\n   * @private\n   */\n  _startPoller() {\n    return this._initTimeoutExtender()\n      .then(() => this.getQueueUrl())\n      .then(queueUrl => this._getBatch(queueUrl))\n      .catch(e => this.emit('error', e))\n  }\n}\n\nmodule.exports = Squiss\n"]}