diff --git a/README.md b/README.md index 9362e89..25c1e7d 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ We also support `make` for legacy builds. # Important Announcements -- September 2023 - Amazon Connect CCP uses cookies for authentication. As part of Google's [Privacy Sandbox](https://privacysandbox.com/open-web/#the-privacy-sandbox-timeline) initiative, Google Chrome has announced plans to block third-party cookies (that is, cookies passed between two top level domains). Version 1.7.6 comes with request storage access API implementation which allows CCP to continue using third party cookies. [Learn more](https://docs.aws.amazon.com/connect/latest/adminguide/admin-3pcookies.html#implement-streams-upgrade). +- September 2023 - Amazon Connect CCP uses cookies for authentication. As part of Google's [Privacy Sandbox](https://privacysandbox.com/open-web/#the-privacy-sandbox-timeline) initiative, Google Chrome has announced plans to block third-party cookies (that is, cookies passed between two top level domains). Version 1.7.7 comes with request storage access API implementation which allows CCP to continue using third party cookies. [Learn more](https://docs.aws.amazon.com/connect/latest/adminguide/admin-3pcookies.html#implement-streams-upgrade). - September 2021 - 1.7.0 comes with changes needed to use Amazon Connect Voice ID, which launched on 9/27/2021. For customers who want to use Voice ID, please upgrade Streams to version 1.7.0 or later in the next 1 month, otherwise the Voice ID APIs will stop working by the end of October 2021. For more details on the Voice ID APIs, please look at [the Voice ID APIs section](Documentation.md#voice-id-apis). diff --git a/package-lock.json b/package-lock.json index 2db4363..1ed9205 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "amazon-connect-streams", - "version": "1.7.6", + "version": "1.7.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "amazon-connect-streams", - "version": "1.7.6", + "version": "1.7.7", "license": "Apache-2.0", "devDependencies": { "@babel/preset-env": "^7.21.4", diff --git a/package.json b/package.json index 9bec3e2..0733c1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "amazon-connect-streams", - "version": "1.7.6", + "version": "1.7.7", "description": "Amazon Connect Streams Library", "engines": { "node": ">=12.0.0" diff --git a/release/connect-streams-min.js b/release/connect-streams-min.js index 74cb7b4..8dfabb4 100644 --- a/release/connect-streams-min.js +++ b/release/connect-streams-min.js @@ -1 +1 @@ -(() => { var e = { 340: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect, e.lily = connect, connect.agentApp = {}; var t = "ccp"; connect.agentApp.initCCP = connect.core.initCCP, connect.agentApp.isInitialized = function (e) { }, connect.agentApp.initAppCommunication = function (e, t) { var n = document.getElementById(e), o = new connect.IFrameConduit(t, window, n), r = [connect.AgentEvents.UPDATE, connect.ContactEvents.VIEW, connect.EventType.ACKNOWLEDGE, connect.EventType.TERMINATED, connect.TaskEvents.CREATED]; n.addEventListener("load", (function (e) { r.forEach((function (e) { connect.core.getUpstream().onUpstream(e, (function (t) { o.sendUpstream(e, t) })) })) })) }; var n = function (e) { var t = e.indexOf("ccp-v2"); return e.slice(0, t - 1) }; connect.agentApp.initApp = function (e, o, r, i) { i = i || {}; var s = r.endsWith("/") ? r : r + "/", c = i.onLoad ? i.onLoad : null, a = { endpoint: s, style: i.style, onLoad: c }; connect.agentApp.AppRegistry.register(e, a, document.getElementById(o)), connect.agentApp.AppRegistry.start(e, (function (o) { var r = o.endpoint, s = o.containerDOM; return { init: function () { return e === t ? function (e, t, o) { var r = { ccpUrl: e, ccpLoadTimeout: 1e4, loginPopup: !0, loginUrl: n(e) + "/login", softphone: { allowFramedSoftphone: !0, disableRingtone: !1 } }, i = connect.merge(r, o.ccpParams); connect.core.initCCP(t, i) }(r, s, i) : connect.agentApp.initAppCommunication(e, r) }, destroy: function () { return e === t ? (o = n(r) + "/logout", connect.fetch(o, { credentials: "include" }).then((function () { return connect.core.getEventBus().trigger(connect.EventType.TERMINATE), !0 })).catch((function (e) { return connect.getLog().error("An error occured on logout." + e).withException(e), window.location.href = o, !1 }))) : null; var o } } })) }, connect.agentApp.stopApp = function (e) { return connect.agentApp.AppRegistry.stop(e) } }() }, 228: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect; var t, n = "ccp"; e.connect.agentApp.AppRegistry = (t = {}, { register: function (e, n, o) { t[e] = { containerDOM: o, endpoint: n.endpoint, style: n.style, instance: void 0, onLoad: n.onLoad } }, start: function (e, o) { if (t[e]) { var r = t[e].containerDOM, i = t[e].endpoint, s = t[e].style, c = t[e].onLoad; if (e !== n) { var a = function (e, t, n, o) { var r = document.createElement("iframe"); return r.src = t, r.style = n || "width: 100%; height:100%;", r.id = e, r["aria-label"] = e, r.onload = o, r.setAttribute("sandbox", "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"), r }(e, i, s, c); r.appendChild(a) } return t[e].instance = o(t[e]), t[e].instance.init() } }, stop: function (e) { if (t[e]) { var n, o = t[e], r = o.containerDOM.querySelector("iframe"); return o.containerDOM.removeChild(r), o.instance && (n = o.instance.destroy(), delete o.instance), n } } }) }() }, 35: () => { function e(e, n) { var o = "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"]; if (!o) { if (Array.isArray(e) || (o = function (e, n) { if (e) { if ("string" == typeof e) return t(e, n); var o = Object.prototype.toString.call(e).slice(8, -1); return "Object" === o && e.constructor && (o = e.constructor.name), "Map" === o || "Set" === o ? Array.from(e) : "Arguments" === o || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o) ? t(e, n) : void 0 } }(e)) || n && e && "number" == typeof e.length) { o && (e = o); var r = 0, i = function () { }; return { s: i, n: function () { return r >= e.length ? { done: !0 } : { done: !1, value: e[r++] } }, e: function (e) { throw e }, f: i } } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.") } var s, c = !0, a = !1; return { s: function () { o = o.call(e) }, n: function () { var e = o.next(); return c = e.done, e }, e: function (e) { a = !0, s = e }, f: function () { try { c || null == o.return || o.return() } finally { if (a) throw s } } } } function t(e, t) { (null == t || t > e.length) && (t = e.length); for (var n = 0, o = new Array(t); n < t; n++)o[n] = e[n]; return o } !function () { var t = this; connect = t.connect || {}, t.connect = connect, t.lily = connect, connect.AgentStateType = connect.makeEnum(["init", "routable", "not_routable", "offline"]), connect.AgentStatusType = connect.AgentStateType, connect.AgentAvailStates = connect.makeEnum(["Init", "Busy", "AfterCallWork", "CallingCustomer", "Dialing", "Joining", "PendingAvailable", "PendingBusy"]), connect.AgentErrorStates = connect.makeEnum(["Error", "AgentHungUp", "BadAddressAgent", "BadAddressCustomer", "Default", "FailedConnectAgent", "FailedConnectCustomer", "InvalidLocale", "LineEngagedAgent", "LineEngagedCustomer", "MissedCallAgent", "MissedCallCustomer", "MultipleCcpWindows", "RealtimeCommunicationError"]), connect.EndpointType = connect.makeEnum(["phone_number", "agent", "queue"]), connect.AddressType = connect.EndpointType, connect.ConnectionType = connect.makeEnum(["agent", "inbound", "outbound", "monitoring"]), connect.ConnectionStateType = connect.makeEnum(["init", "connecting", "connected", "hold", "disconnected"]), connect.ConnectionStatusType = connect.ConnectionStateType, connect.CONNECTION_ACTIVE_STATES = connect.set([connect.ConnectionStateType.CONNECTING, connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.HOLD]), connect.ContactStateType = connect.makeEnum(["init", "incoming", "pending", "connecting", "connected", "missed", "error", "ended"]), connect.ContactStatusType = connect.ContactStateType, connect.CONTACT_ACTIVE_STATES = connect.makeEnum(["incoming", "pending", "connecting", "connected"]), connect.ContactType = connect.makeEnum(["voice", "queue_callback", "chat", "task"]), connect.ContactInitiationMethod = connect.makeEnum(["inbound", "outbound", "transfer", "queue_transfer", "callback", "api", "disconnect"]), connect.ChannelType = connect.makeEnum(["VOICE", "CHAT", "TASK"]), connect.MediaType = connect.makeEnum(["softphone", "chat", "task"]), connect.SoftphoneCallType = connect.makeEnum(["audio_video", "video_only", "audio_only", "none"]), connect.SoftphoneErrorTypes = connect.makeEnum(["unsupported_browser", "microphone_not_shared", "signalling_handshake_failure", "signalling_connection_failure", "ice_collection_timeout", "user_busy_error", "webrtc_error", "realtime_communication_error", "other"]), connect.VoiceIdErrorTypes = connect.makeEnum(["no_speaker_id_found", "speaker_id_not_enrolled", "get_speaker_id_failed", "get_speaker_status_failed", "opt_out_speaker_failed", "opt_out_speaker_in_lcms_failed", "delete_speaker_failed", "start_session_failed", "evaluate_speaker_failed", "session_not_exists", "describe_session_failed", "enroll_speaker_failed", "update_speaker_id_failed", "update_speaker_id_in_lcms_failed", "not_supported_on_conference_calls", "enroll_speaker_timeout", "evaluate_speaker_timeout", "get_domain_id_failed", "no_domain_id_found"]), connect.CTIExceptions = connect.makeEnum(["AccessDeniedException", "InvalidStateException", "BadEndpointException", "InvalidAgentARNException", "InvalidConfigurationException", "InvalidContactTypeException", "PaginationException", "RefreshTokenExpiredException", "SendDataFailedException", "UnauthorizedException", "QuotaExceededException"]), connect.VoiceIdStreamingStatus = connect.makeEnum(["ONGOING", "ENDED", "PENDING_CONFIGURATION"]), connect.VoiceIdAuthenticationDecision = connect.makeEnum(["ACCEPT", "REJECT", "NOT_ENOUGH_SPEECH", "SPEAKER_NOT_ENROLLED", "SPEAKER_OPTED_OUT", "SPEAKER_ID_NOT_PROVIDED", "SPEAKER_EXPIRED"]), connect.VoiceIdFraudDetectionDecision = connect.makeEnum(["NOT_ENOUGH_SPEECH", "HIGH_RISK", "LOW_RISK"]), connect.ContactFlowAuthenticationDecision = connect.makeEnum(["Authenticated", "NotAuthenticated", "Inconclusive", "NotEnrolled", "OptedOut", "NotEnabled", "Error"]), connect.ContactFlowFraudDetectionDecision = connect.makeEnum(["HighRisk", "LowRisk", "Inconclusive", "NotEnabled", "Error"]), connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum(["NOT_ENOUGH_SPEECH", "IN_PROGRESS", "COMPLETED", "FAILED"]), connect.VoiceIdSpeakerStatus = connect.makeEnum(["OPTED_OUT", "ENROLLED", "PENDING"]), connect.VoiceIdConstants = { EVALUATE_SESSION_DELAY: 1e4, EVALUATION_MAX_POLL_TIMES: 24, EVALUATION_POLLING_INTERVAL: 5e3, ENROLLMENT_MAX_POLL_TIMES: 120, ENROLLMENT_POLLING_INTERVAL: 5e3, START_SESSION_DELAY: 8e3 }, connect.AgentPermissions = { OUTBOUND_CALL: "outboundCall", VOICE_ID: "voiceId" }; var n = function () { if (!connect.agent.initialized) throw new connect.StateError("The agent is not yet initialized!") }; n.prototype._getData = function () { return connect.core.getAgentDataProvider().getAgentData() }, n.prototype._createContactAPI = function (e) { return new connect.Contact(e.contactId) }, n.prototype.onContactPending = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.CONTACT_PENDING, e) }, n.prototype.onRefresh = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.REFRESH, e) }, n.prototype.onRoutable = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.ROUTABLE, e) }, n.prototype.onNotRoutable = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.NOT_ROUTABLE, e) }, n.prototype.onOffline = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.OFFLINE, e) }, n.prototype.onError = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.ERROR, e) }, n.prototype.onSoftphoneError = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.SOFTPHONE_ERROR, e) }, n.prototype.onWebSocketConnectionLost = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, e) }, n.prototype.onWebSocketConnectionGained = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, e) }, n.prototype.onAfterCallWork = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.ACW, e) }, n.prototype.onStateChange = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.STATE_CHANGE, e) }, n.prototype.onMuteToggle = function (e) { connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE, e) }, n.prototype.onLocalMediaStreamCreated = function (e) { connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, e) }, n.prototype.onSpeakerDeviceChanged = function (e) { connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, e) }, n.prototype.onMicrophoneDeviceChanged = function (e) { connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, e) }, n.prototype.onRingerDeviceChanged = function (e) { connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, e) }, n.prototype.mute = function () { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE, data: { mute: !0 } }) }, n.prototype.unmute = function () { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE, data: { mute: !1 } }) }, n.prototype.setSpeakerDevice = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, data: { deviceId: e } }) }, n.prototype.setMicrophoneDevice = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, data: { deviceId: e } }) }, n.prototype.setRingerDevice = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SET_RINGER_DEVICE, data: { deviceId: e } }) }, n.prototype.getState = function () { return this._getData().snapshot.state }, n.prototype.getNextState = function () { return this._getData().snapshot.nextState }, n.prototype.getAvailabilityState = function () { return this._getData().snapshot.agentAvailabilityState }, n.prototype.getStatus = n.prototype.getState, n.prototype.getStateDuration = function () { return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew() }, n.prototype.getStatusDuration = n.prototype.getStateDuration, n.prototype.getPermissions = function () { return this.getConfiguration().permissions }, n.prototype.getContacts = function (e) { var t = this; return this._getData().snapshot.contacts.map((function (e) { return t._createContactAPI(e) })).filter((function (t) { return !e || t.getType() === e })) }, n.prototype.getConfiguration = function () { return this._getData().configuration }, n.prototype.getAgentStates = function () { return this.getConfiguration().agentStates }, n.prototype.getRoutingProfile = function () { return this.getConfiguration().routingProfile }, n.prototype.getChannelConcurrency = function (e) { var t = this.getRoutingProfile().channelConcurrencyMap; return t || (t = Object.keys(connect.ChannelType).reduce((function (e, t) { return "TASK" !== t && (e[connect.ChannelType[t]] = 1), e }), {})), e ? t[e] || 0 : t }, n.prototype.getName = function () { return this.getConfiguration().name }, n.prototype.getExtension = function () { return this.getConfiguration().extension }, n.prototype.getDialableCountries = function () { return this.getConfiguration().dialableCountries }, n.prototype.isSoftphoneEnabled = function () { return this.getConfiguration().softphoneEnabled }, n.prototype.setConfiguration = function (e, t) { var n = connect.core.getClient(); e && e.agentPreferences && !connect.isValidLocale(e.agentPreferences.locale) ? t && t.failure && t.failure(connect.AgentErrorStates.INVALID_LOCALE) : n.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { configuration: connect.assertNotNull(e, "configuration") }, { success: function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION), t.success && t.success(e) }, failure: t && t.failure }) }, n.prototype.setState = function (e, t, n) { connect.core.getClient().call(connect.ClientMethods.PUT_AGENT_STATE, { state: connect.assertNotNull(e, "state"), enqueueNextState: n && !!n.enqueueNextState }, t) }, n.prototype.onEnqueuedNextState = function (e) { connect.core.getEventBus().subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, e) }, n.prototype.setStatus = n.prototype.setState, n.prototype.connect = function (e, t) { var n = connect.core.getClient(), o = new connect.Endpoint(e); delete o.endpointId, n.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, { endpoint: connect.assertNotNull(o, "endpoint"), queueARN: t && (t.queueARN || t.queueId) || this.getRoutingProfile().defaultOutboundQueue.queueARN }, t && { success: t.success, failure: t.failure }) }, n.prototype.getAllQueueARNs = function () { return this.getConfiguration().routingProfile.queues.map((function (e) { return e.queueARN })) }, n.prototype.getEndpoints = function (e, t, n) { var o = this, r = connect.core.getClient(); connect.assertNotNull(t, "callbacks"), connect.assertNotNull(t.success, "callbacks.success"); var i = n || {}; i.endpoints = i.endpoints || [], i.maxResults = i.maxResults || connect.DEFAULT_BATCH_SIZE, connect.isArray(e) || (e = [e]), r.call(connect.ClientMethods.GET_ENDPOINTS, { queueARNs: e, nextToken: i.nextToken || null, maxResults: i.maxResults }, { success: function (n) { if (n.nextToken) o.getEndpoints(e, t, { nextToken: n.nextToken, maxResults: i.maxResults, endpoints: i.endpoints.concat(n.endpoints) }); else { i.endpoints = i.endpoints.concat(n.endpoints); var r = i.endpoints.map((function (e) { return new connect.Endpoint(e) })); t.success({ endpoints: r, addresses: r }) } }, failure: t.failure }) }, n.prototype.getAddresses = n.prototype.getEndpoints, n.prototype._getResourceId = function () { queueArns = this.getAllQueueARNs(); var t, n = e(queueArns); try { for (n.s(); !(t = n.n()).done;) { var o = t.value.match(/\/agent\/([^/]+)/); if (o) return o[1] } } catch (e) { n.e(e) } finally { n.f() } return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns) }, n.prototype.toSnapshot = function () { return new connect.AgentSnapshot(this._getData()) }; var o = function (e) { connect.Agent.call(this), this.agentData = e }; (o.prototype = Object.create(n.prototype)).constructor = o, o.prototype._getData = function () { return this.agentData }, o.prototype._createContactAPI = function (e) { return new connect.ContactSnapshot(e) }; var r = function (e) { this.contactId = e }; r.prototype._getData = function () { return connect.core.getAgentDataProvider().getContactData(this.getContactId()) }, r.prototype._createConnectionAPI = function (e) { return this.getType() === connect.ContactType.CHAT ? new connect.ChatConnection(this.contactId, e.connectionId) : this.getType() === connect.ContactType.TASK ? new connect.TaskConnection(this.contactId, e.connectionId) : new connect.VoiceConnection(this.contactId, e.connectionId) }, r.prototype.getEventName = function (e) { return connect.core.getContactEventName(e, this.getContactId()) }, r.prototype.onRefresh = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.REFRESH), e) }, r.prototype.onIncoming = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.INCOMING), e) }, r.prototype.onConnecting = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTING), e) }, r.prototype.onPending = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.PENDING), e) }, r.prototype.onAccepted = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), e) }, r.prototype.onMissed = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.MISSED), e) }, r.prototype.onEnded = function (e) { var t = connect.core.getEventBus(); t.subscribe(this.getEventName(connect.ContactEvents.ENDED), e), t.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), e) }, r.prototype.onDestroy = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.DESTROYED), e) }, r.prototype.onACW = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ACW), e) }, r.prototype.onConnected = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.CONNECTED), e) }, r.prototype.onError = function (e) { connect.core.getEventBus().subscribe(this.getEventName(connect.ContactEvents.ERROR), e) }, r.prototype.getContactId = function () { return this.contactId }, r.prototype.getOriginalContactId = function () { return this._getData().initialContactId }, r.prototype.getInitialContactId = r.prototype.getOriginalContactId, r.prototype.getType = function () { return this._getData().type }, r.prototype.getContactDuration = function () { return this._getData().contactDuration }, r.prototype.getState = function () { return this._getData().state }, r.prototype.getStatus = r.prototype.getState, r.prototype.getStateDuration = function () { return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew() }, r.prototype.getStatusDuration = r.prototype.getStateDuration, r.prototype.getQueue = function () { return this._getData().queue }, r.prototype.getQueueTimestamp = function () { return this._getData().queueTimestamp }, r.prototype.getConnections = function () { var e = this; return this._getData().connections.map((function (t) { return e.getType() === connect.ContactType.CHAT ? new connect.ChatConnection(e.contactId, t.connectionId) : e.getType() === connect.ContactType.TASK ? new connect.TaskConnection(e.contactId, t.connectionId) : new connect.VoiceConnection(e.contactId, t.connectionId) })) }, r.prototype.getInitialConnection = function () { return connect.find(this.getConnections(), (function (e) { return e.isInitialConnection() })) || null }, r.prototype.getActiveInitialConnection = function () { var e = this.getInitialConnection(); return null != e && e.isActive() ? e : null }, r.prototype.getThirdPartyConnections = function () { return this.getConnections().filter((function (e) { return !e.isInitialConnection() && e.getType() !== connect.ConnectionType.AGENT })) }, r.prototype.getSingleActiveThirdPartyConnection = function () { return this.getThirdPartyConnections().filter((function (e) { return e.isActive() }))[0] || null }, r.prototype.getAgentConnection = function () { return connect.find(this.getConnections(), (function (e) { var t = e.getType(); return t === connect.ConnectionType.AGENT || t === connect.ConnectionType.MONITORING })) }, r.prototype.getName = function () { return this._getData().name }, r.prototype.getContactMetadata = function () { return this._getData().contactMetadata }, r.prototype.getDescription = function () { return this._getData().description }, r.prototype.getReferences = function () { return this._getData().references }, r.prototype.getAttributes = function () { return this._getData().attributes }, r.prototype.getContactFeatures = function () { return this._getData().contactFeatures }, r.prototype.isSoftphoneCall = function () { return null != connect.find(this.getConnections(), (function (e) { return null != e.getSoftphoneMediaInfo() })) }, r.prototype._isInbound = function () { return this._getData().initiationMethod !== connect.ContactInitiationMethod.OUTBOUND }, r.prototype.isInbound = function () { var e = this.getInitialConnection(); return e.getMediaType() === connect.MediaType.TASK ? this._isInbound() : !!e && e.getType() === connect.ConnectionType.INBOUND }, r.prototype.isConnected = function () { return this.getStatus().type === connect.ContactStateType.CONNECTED }, r.prototype.accept = function (e) { var t = connect.core.getClient(), n = this, o = this.getContactId(); t.call(connect.ClientMethods.ACCEPT_CONTACT, { contactId: o }, { success: function (t) { var r = connect.core.getUpstream(); r.sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.ACCEPTED, data: new connect.Contact(o) }), r.sendUpstream(connect.EventType.BROADCAST, { event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, n.getContactId()), data: new connect.Contact(o) }); var i = new connect.Contact(o); connect.isFirefoxBrowser() && i.isSoftphoneCall() && connect.core.triggerReadyToStartSessionEvent(), e && e.success && e.success(t) }, failure: e ? e.failure : null }) }, r.prototype.destroy = function () { connect.getLog().warn("contact.destroy() has been deprecated.") }, r.prototype.reject = function (e) { connect.core.getClient().call(connect.ClientMethods.REJECT_CONTACT, { contactId: this.getContactId() }, e) }, r.prototype.complete = function (e) { connect.core.getClient().call(connect.ClientMethods.COMPLETE_CONTACT, { contactId: this.getContactId() }, e) }, r.prototype.clear = function (e) { connect.core.getClient().call(connect.ClientMethods.CLEAR_CONTACT, { contactId: this.getContactId() }, e) }, r.prototype.notifyIssue = function (e, t, n) { connect.core.getClient().call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { contactId: this.getContactId(), issueCode: e, description: t }, n) }, r.prototype.addConnection = function (e, t) { var n = connect.core.getClient(), o = new connect.Endpoint(e); delete o.endpointId, n.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { contactId: this.getContactId(), endpoint: o }, t) }, r.prototype.toggleActiveConnections = function (e) { var t = connect.core.getClient(), n = null, o = connect.find(this.getConnections(), (function (e) { return e.getStatus().type === connect.ConnectionStateType.HOLD })); if (null != o) n = o.getConnectionId(); else { var r = this.getConnections().filter((function (e) { return e.isActive() })); r.length > 0 && (n = r[0].getConnectionId()) } t.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { contactId: this.getContactId(), connectionId: n }, e) }, r.prototype.sendSoftphoneMetrics = function (e, n) { connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { contactId: this.getContactId(), ccpVersion: t.ccpVersion, softphoneStreamStatistics: e }, n), connect.publishSoftphoneStats({ contactId: this.getContactId(), ccpVersion: t.ccpVersion, stats: e }) }, r.prototype.sendSoftphoneReport = function (e, n) { connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { contactId: this.getContactId(), ccpVersion: t.ccpVersion, report: e }, n), connect.publishSoftphoneReport({ contactId: this.getContactId(), ccpVersion: t.ccpVersion, report: e }) }, r.prototype.conferenceConnections = function (e) { connect.core.getClient().call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { contactId: this.getContactId() }, e) }, r.prototype.toSnapshot = function () { return new connect.ContactSnapshot(this._getData()) }; var i = function (e) { connect.Contact.call(this, e.contactId), this.contactData = e }; (i.prototype = Object.create(r.prototype)).constructor = i, i.prototype._getData = function () { return this.contactData }, i.prototype._createConnectionAPI = function (e) { return new connect.ConnectionSnapshot(e) }; var s = function (e, t) { this.contactId = e, this.connectionId = t, this._initMediaController() }; s.prototype._getData = function () { return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(), this.getConnectionId()) }, s.prototype.getContactId = function () { return this.contactId }, s.prototype.getConnectionId = function () { return this.connectionId }, s.prototype.getEndpoint = function () { return new connect.Endpoint(this._getData().endpoint) }, s.prototype.getAddress = s.prototype.getEndpoint, s.prototype.getState = function () { return this._getData().state }, s.prototype.getStatus = s.prototype.getState, s.prototype.getStateDuration = function () { return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew() }, s.prototype.getStatusDuration = s.prototype.getStateDuration, s.prototype.getType = function () { return this._getData().type }, s.prototype.isInitialConnection = function () { return this._getData().initial }, s.prototype.isActive = function () { return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type) }, s.prototype.isConnected = function () { return this.getStatus().type === connect.ConnectionStateType.CONNECTED }, s.prototype.isConnecting = function () { return this.getStatus().type === connect.ConnectionStateType.CONNECTING }, s.prototype.isOnHold = function () { return this.getStatus().type === connect.ConnectionStateType.HOLD }, s.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo }, s.prototype.getMonitorInfo = function () { return this._getData().monitoringInfo }, s.prototype.destroy = function (e) { connect.core.getClient().call(connect.ClientMethods.DESTROY_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, e) }, s.prototype.sendDigits = function (e, t) { connect.core.getClient().call(connect.ClientMethods.SEND_DIGITS, { contactId: this.getContactId(), connectionId: this.getConnectionId(), digits: e }, t) }, s.prototype.hold = function (e) { connect.core.getClient().call(connect.ClientMethods.HOLD_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, e) }, s.prototype.resume = function (e) { connect.core.getClient().call(connect.ClientMethods.RESUME_CONNECTION, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, e) }, s.prototype.toSnapshot = function () { return new connect.ConnectionSnapshot(this._getData()) }, s.prototype._initMediaController = function () { this.getMediaInfo() && connect.core.mediaFactory.get(this).catch((function () { })) }, s.prototype._isAgentConnectionType = function () { var e = this.getType(); return e === connect.ConnectionType.AGENT || e === connect.ConnectionType.MONITORING }, s.prototype._isAgentConnectionType = function () { var e = this.getType(); return e === connect.ConnectionType.AGENT || e === connect.ConnectionType.MONITORING }; var c = function (e) { this.contactId = e }; c.prototype.getSpeakerId = function () { var e = this; e.checkConferenceCall(); var t = connect.core.getClient(); return new Promise((function (n, o) { t.call(connect.AgentAppClientMethods.GET_CONTACT, { contactId: e.contactId, instanceId: connect.core.getAgentDataProvider().getInstanceId(), awsAccountId: connect.core.getAgentDataProvider().getAWSAccountId() }, { success: function (e) { if (e.contactData.customerId) { var t = { speakerId: e.contactData.customerId }; connect.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(), n(t) } else { var r = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); o(r) } }, failure: function (e) { connect.getLog().error("Get SpeakerId failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", e); o(t) } }) })) }, c.prototype.getSpeakerStatus = function () { var e = this; e.checkConferenceCall(); var t = connect.core.getClient(); return new Promise((function (n, o) { e.getSpeakerId().then((function (r) { e.getDomainId().then((function (e) { t.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, { SpeakerId: connect.assertNotNull(r.speakerId, "speakerId"), DomainId: e }, { success: function (e) { connect.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(), n(e) }, failure: function (e) { var t = JSON.parse(e); switch (t.status) { case 400: case 404: var r = t; r.type = r.type ? r.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED, connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(), n(r); break; default: connect.getLog().error("getSpeakerStatus failed").withObject({ err: e }).sendInternalLogToServer(); var i = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", e); o(i) } } }) })).catch((function (e) { o(e) })) })).catch((function (e) { o(e) })) })) }, c.prototype._optOutSpeakerInLcms = function (e) { var t = this, n = connect.core.getClient(); return new Promise((function (o, r) { n.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { ContactId: t.contactId, InstanceId: connect.core.getAgentDataProvider().getInstanceId(), AWSAccountId: connect.core.getAgentDataProvider().getAWSAccountId(), CustomerId: connect.assertNotNull(e, "speakerId"), VoiceIdResult: { SpeakerOptedOut: !0 } }, { success: function (e) { connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(), o(e) }, failure: function (e) { connect.getLog().error("optOutSpeakerInLcms failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", e); r(t) } }) })) }, c.prototype.optOutSpeaker = function () { var e = this; e.checkConferenceCall(); var t = connect.core.getClient(); return new Promise((function (n, o) { e.getSpeakerId().then((function (r) { e.getDomainId().then((function (i) { var s = r.speakerId; t.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, { SpeakerId: connect.assertNotNull(s, "speakerId"), DomainId: i }, { success: function (t) { e._optOutSpeakerInLcms(s).catch((function () { })), connect.getLog().info("optOutSpeaker succeeded").withObject(t).sendInternalLogToServer(), n(t) }, failure: function (e) { connect.getLog().error("optOutSpeaker failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", e); o(t) } }) })).catch((function (e) { o(e) })) })).catch((function (e) { o(e) })) })) }, c.prototype.deleteSpeaker = function () { var e = this; e.checkConferenceCall(); var t = connect.core.getClient(); return new Promise((function (n, o) { e.getSpeakerId().then((function (r) { e.getDomainId().then((function (e) { t.call(connect.AgentAppClientMethods.DELETE_SPEAKER, { SpeakerId: connect.assertNotNull(r.speakerId, "speakerId"), DomainId: e }, { success: function (e) { connect.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(), n(e) }, failure: function (e) { connect.getLog().error("deleteSpeaker failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", e); o(t) } }) })).catch((function (e) { o(e) })) })).catch((function (e) { o(e) })) })) }, c.prototype.startSession = function () { var e = this; e.checkConferenceCall(); var t = connect.core.getClient(); return new Promise((function (n, o) { e.getDomainId().then((function (r) { t.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, { contactId: e.contactId, instanceId: connect.core.getAgentDataProvider().getInstanceId(), customerAccountId: connect.core.getAgentDataProvider().getAWSAccountId(), clientToken: AWS.util.uuid.v4(), domainId: r }, { success: function (e) { if (e.sessionId) n(e); else { connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({ data: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); o(t) } }, failure: function (e) { connect.getLog().error("startVoiceIdSession failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", e); o(t) } }) })).catch((function (e) { o(e) })) })) }, c.prototype.evaluateSpeaker = function (e) { var t = this; t.checkConferenceCall(); var n = connect.core.getClient(), o = connect.core.getAgentDataProvider().getContactData(this.contactId), r = 0; return new Promise((function (i, s) { function c() { t.getDomainId().then((function (e) { n.call(connect.AgentAppClientMethods.EVALUATE_SESSION, { SessionNameOrId: o.initialContactId || this.contactId, DomainId: e }, { success: function (e) { if (++r < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) if (e.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) setTimeout(c, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); else { if (e.AuthenticationResult || (e.AuthenticationResult = {}, e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED), e.FraudDetectionResult || (e.FraudDetectionResult = {}, e.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED), !t.isAuthEnabled(e.AuthenticationResult.Decision) && !t.isFraudEnabled(e.FraudDetectionResult.Decision)) return connect.getLog().info("evaluateSpeaker succeeded").withObject(e).sendInternalLogToServer(), void i(e); if (e.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED && (t.isAuthResultNotEnoughSpeech(e.AuthenticationResult.Decision) && (e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE), t.isFraudResultNotEnoughSpeech(e.FraudDetectionResult.Decision) && (e.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE)), t.isAuthResultInconclusive(e.AuthenticationResult.Decision) && t.isFraudResultInconclusive(e.FraudDetectionResult.Decision)) return connect.getLog().info("evaluateSpeaker succeeded").withObject(e).sendInternalLogToServer(), void i(e); if (!t.isAuthResultNotEnoughSpeech(e.AuthenticationResult.Decision) && t.isAuthEnabled(e.AuthenticationResult.Decision)) switch (e.AuthenticationResult.Decision) { case connect.VoiceIdAuthenticationDecision.ACCEPT: e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; break; case connect.VoiceIdAuthenticationDecision.REJECT: e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; break; case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; break; case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; break; default: e.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR }if (!t.isFraudResultNotEnoughSpeech(e.FraudDetectionResult.Decision) && t.isFraudEnabled(e.FraudDetectionResult.Decision)) switch (e.FraudDetectionResult.Decision) { case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: e.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; break; case connect.VoiceIdFraudDetectionDecision.LOW_RISK: e.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; break; default: e.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR }if (!t.isAuthResultNotEnoughSpeech(e.AuthenticationResult.Decision) && !t.isFraudResultNotEnoughSpeech(e.FraudDetectionResult.Decision)) return connect.getLog().info("evaluateSpeaker succeeded").withObject(e).sendInternalLogToServer(), void i(e); setTimeout(c, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL) } else { connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); var n = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); s(n) } }, failure: function (e) { var t; switch (JSON.parse(e).status) { case 400: case 404: t = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", e), connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ err: e }).sendInternalLogToServer(); break; default: t = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", e), connect.getLog().error("evaluateSpeaker failed").withObject({ err: e }).sendInternalLogToServer() }s(t) } }) })).catch((function (e) { s(e) })) } e ? t.startSession().then((function (e) { t.syncSpeakerId().then((function (e) { setTimeout(c, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY) })).catch((function (e) { connect.getLog().error("syncSpeakerId failed when session startNew=true").withObject({ err: e }).sendInternalLogToServer(), s(e) })) })).catch((function (e) { connect.getLog().error("startSession failed when session startNew=true").withObject({ err: e }).sendInternalLogToServer(), s(e) })) : t.syncSpeakerId().then((function () { c() })).catch((function (e) { connect.getLog().error("syncSpeakerId failed when session startNew=false").withObject({ err: e }).sendInternalLogToServer(), s(e) })) })) }, c.prototype.describeSession = function () { var e = this, t = connect.core.getClient(), n = connect.core.getAgentDataProvider().getContactData(this.contactId); return new Promise((function (o, r) { e.getDomainId().then((function (e) { t.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, { SessionNameOrId: n.initialContactId || this.contactId, DomainId: e }, { success: function (e) { o(e) }, failure: function (e) { connect.getLog().error("describeSession failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", e); r(t) } }) })).catch((function (e) { r(e) })) })) }, c.prototype.checkEnrollmentStatus = function () { var e = this, t = 0; return new Promise((function (n, o) { !function r() { if (++t < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) e.describeSession().then((function (t) { switch (t.Session.EnrollmentRequestDetails.Status) { case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: n(t); break; case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: setTimeout(r, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); break; case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: t.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED ? setTimeout(r, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL) : setTimeout((function () { e.startSession().then((function (e) { r() })).catch((function (e, t) { o(e) })) }), connect.VoiceIdConstants.START_SESSION_DELAY); break; default: var i = t.Session.EnrollmentRequestDetails.Message ? t.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; connect.getLog().error(i).sendInternalLogToServer(); var s = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, i, t.Session.EnrollmentRequestDetails.Status); o(s) } })); else { connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); var i = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); o(i) } }() })) }, c.prototype.enrollSpeaker = function () { var e = this; return e.checkConferenceCall(), new Promise((function (t, n) { e.syncSpeakerId().then((function () { e.getSpeakerStatus().then((function (o) { o.Speaker && o.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT ? e.deleteSpeaker().then((function () { e.enrollSpeakerHelper(t, n) })).catch((function (e) { n(e) })) : e.enrollSpeakerHelper(t, n) })).catch((function (e) { n(e) })) })).catch((function (e) { n(e) })) })) }, c.prototype.enrollSpeakerHelper = function (e, t) { var n = this, o = connect.core.getClient(), r = connect.core.getAgentDataProvider().getContactData(this.contactId); n.getDomainId().then((function (i) { o.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, { SessionNameOrId: r.initialContactId || this.contactId, DomainId: i }, { success: function (o) { o.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED ? (connect.getLog().info("enrollSpeaker succeeded").withObject(o).sendInternalLogToServer(), e(o)) : n.checkEnrollmentStatus().then((function (t) { connect.getLog().info("enrollSpeaker succeeded").withObject(t).sendInternalLogToServer(), e(t) })).catch((function (e) { t(e) })) }, failure: function (e) { connect.getLog().error("enrollSpeaker failed").withObject({ err: e }).sendInternalLogToServer(); var n = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", e); t(n) } }) })).catch((function (e) { t(e) })) }, c.prototype._updateSpeakerIdInLcms = function (e) { var t = this, n = connect.core.getClient(); return new Promise((function (o, r) { n.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { ContactId: t.contactId, InstanceId: connect.core.getAgentDataProvider().getInstanceId(), AWSAccountId: connect.core.getAgentDataProvider().getAWSAccountId(), CustomerId: connect.assertNotNull(e, "speakerId"), VoiceIdResult: { generatedSpeakerId: e } }, { success: function (e) { connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(e).sendInternalLogToServer(), o(e) }, failure: function (e) { connect.getLog().error("updateSpeakerIdInLcms failed").withObject({ err: e }).sendInternalLogToServer(); var t = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", e); r(t) } }) })) }, c.prototype.updateSpeakerIdInVoiceId = function (e) { var t = this; t.checkConferenceCall(); var n = connect.core.getClient(), o = connect.core.getAgentDataProvider().getContactData(this.contactId); return new Promise((function (r, i) { t.getDomainId().then((function (s) { n.call(connect.AgentAppClientMethods.UPDATE_SESSION, { SessionNameOrId: o.initialContactId || this.contactId, SpeakerId: connect.assertNotNull(e, "speakerId"), DomainId: s }, { success: function (n) { connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(n).sendInternalLogToServer(), t._updateSpeakerIdInLcms(e).then((function () { r(n) })).catch((function (e) { i(e) })) }, failure: function (e) { var t; switch (JSON.parse(e).status) { case 400: case 404: t = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", e), connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ err: e }).sendInternalLogToServer(); break; default: t = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", e), connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ err: e }).sendInternalLogToServer() }i(t) } }) })).catch((function (e) { i(e) })) })) }, c.prototype.syncSpeakerId = function () { var e = this; return new Promise((function (t, n) { e.getSpeakerId().then((function (o) { e.updateSpeakerIdInVoiceId(o.speakerId).then((function (e) { t(e) })).catch((function (e) { n(e) })) })).catch((function (e) { n(e) })) })) }, c.prototype.getDomainId = function () { return new Promise((function (e, t) { (new connect.Agent).getPermissions().includes(connect.AgentPermissions.VOICE_ID) ? connect.core.voiceIdDomainId ? e(connect.core.voiceIdDomainId) : connect.core.getClient().call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, { InstanceId: connect.core.getAgentDataProvider().getInstanceId(), IntegrationType: "VOICE_ID" }, { success: function (n) { try { var o; if (n.IntegrationAssociationSummaryList.length >= 1 && (o = n.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i, "")), !o) { connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); var r = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); return void t(r) } connect.getLog().info("getDomainId succeeded").withObject(n).sendInternalLogToServer(), connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, data: { domainId: o } }), e(o) } catch (e) { connect.getLog().error("getDomainId failed").withObject({ err: e }).sendInternalLogToServer(), r = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", e), t(r) } }, failure: function (e) { connect.getLog().error("getDomainId failed").withObject({ err: e }).sendInternalLogToServer(); var n = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", e); t(n) } }) : t(new Error("Agent doesn't have the permission for Voice ID")) })) }, c.prototype.checkConferenceCall = function () { if (connect.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function (e) { return connect.contains(connect.CONNECTION_ACTIVE_STATES, e.state.type) })).length > 2) throw new connect.NotImplementedError("VoiceId is not supported for conference calls") }, c.prototype.isAuthEnabled = function (e) { return e !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED }, c.prototype.isAuthResultNotEnoughSpeech = function (e) { return e === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH }, c.prototype.isAuthResultInconclusive = function (e) { return e === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE }, c.prototype.isFraudEnabled = function (e) { return e !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED }, c.prototype.isFraudResultNotEnoughSpeech = function (e) { return e === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH }, c.prototype.isFraudResultInconclusive = function (e) { return e === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE }; var a = function (e, t) { this._speakerAuthenticator = new c(e), s.call(this, e, t) }; (a.prototype = Object.create(s.prototype)).constructor = a, a.prototype.getSoftphoneMediaInfo = function () { return this._getData().softphoneMediaInfo }, a.prototype.getMediaInfo = function () { return this._getData().softphoneMediaInfo }, a.prototype.getMediaType = function () { return connect.MediaType.SOFTPHONE }, a.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this) }, a.prototype.getVoiceIdSpeakerId = function () { return this._speakerAuthenticator.getSpeakerId() }, a.prototype.getVoiceIdSpeakerStatus = function () { return this._speakerAuthenticator.getSpeakerStatus() }, a.prototype.optOutVoiceIdSpeaker = function () { return this._speakerAuthenticator.optOutSpeaker() }, a.prototype.deleteVoiceIdSpeaker = function () { return this._speakerAuthenticator.deleteSpeaker() }, a.prototype.evaluateSpeakerWithVoiceId = function (e) { return this._speakerAuthenticator.evaluateSpeaker(e) }, a.prototype.enrollSpeakerInVoiceId = function () { return this._speakerAuthenticator.enrollSpeaker() }, a.prototype.updateVoiceIdSpeakerId = function (e) { return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e) }, a.prototype.getQuickConnectName = function () { return this._getData().quickConnectName }, a.prototype.isMute = function () { return this._getData().mute }, a.prototype.muteParticipant = function (e) { connect.core.getClient().call(connect.ClientMethods.MUTE_PARTICIPANT, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, e) }, a.prototype.unmuteParticipant = function (e) { connect.core.getClient().call(connect.ClientMethods.UNMUTE_PARTICIPANT, { contactId: this.getContactId(), connectionId: this.getConnectionId() }, e) }; var u = function (e, t) { s.call(this, e, t) }; (u.prototype = Object.create(s.prototype)).constructor = u, u.prototype.getMediaInfo = function () { var e = this._getData().chatMediaInfo; if (e) { var t = connect.core.getAgentDataProvider().getContactData(this.contactId), n = { contactId: this.contactId, initialContactId: t.initialContactId || this.contactId, participantId: this.connectionId, getConnectionToken: connect.hitch(this, this.getConnectionToken) }; if (e.connectionData) try { n.participantToken = JSON.parse(e.connectionData).ConnectionAuthenticationToken } catch (t) { connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid").withObject(e).withException(t).sendInternalLogToServer(), n.participantToken = null } return n.participantToken = n.participantToken || null, n.originalInfo = this._getData().chatMediaInfo, n } return null }, u.prototype.getConnectionToken = function () { client = connect.core.getClient(); var e = connect.core.getAgentDataProvider().getContactData(this.contactId), t = { transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, participantId: this.connectionId, contactId: e.initialContactId || this.contactId }; return new Promise((function (e, n) { client.call(connect.ClientMethods.CREATE_TRANSPORT, t, { success: function (t) { connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(), e(t) }, failure: function (e, t) { connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({ err: e, data: t }), n(Error("getConnectionToken failed")) } }) })) }, u.prototype.getMediaType = function () { return connect.MediaType.CHAT }, u.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this) }, u.prototype._initMediaController = function () { this._isAgentConnectionType() && connect.core.mediaFactory.get(this).catch((function () { })) }; var l = function (e, t) { s.call(this, e, t) }; (l.prototype = Object.create(s.prototype)).constructor = l, l.prototype.getMediaType = function () { return connect.MediaType.TASK }, l.prototype.getMediaInfo = function () { var e = connect.core.getAgentDataProvider().getContactData(this.contactId); return { contactId: this.contactId, initialContactId: e.initialContactId || this.contactId } }, l.prototype.getMediaController = function () { return connect.core.mediaFactory.get(this) }; var p = function (e) { connect.Connection.call(this, e.contactId, e.connectionId), this.connectionData = e }; (p.prototype = Object.create(s.prototype)).constructor = p, p.prototype._getData = function () { return this.connectionData }, p.prototype._initMediaController = function () { }; var h = function (e) { var t = e || {}; this.endpointARN = t.endpointId || t.endpointARN || null, this.endpointId = this.endpointARN, this.type = t.type || null, this.name = t.name || null, this.phoneNumber = t.phoneNumber || null, this.agentLogin = t.agentLogin || null, this.queue = t.queue || null }; h.prototype.stripPhoneNumber = function () { return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : "" }, h.byPhoneNumber = function (e, t) { return new h({ type: connect.EndpointType.PHONE_NUMBER, phoneNumber: e, name: t || null }) }; var d = function (e, t, n) { this.errorType = e, this.errorMessage = t, this.endPointUrl = n }; d.prototype.getErrorType = function () { return this.errorType }, d.prototype.getErrorMessage = function () { return this.errorMessage }, d.prototype.getEndPointUrl = function () { return this.endPointUrl }, connect.agent = function (e) { var t = connect.core.getEventBus().subscribe(connect.AgentEvents.INIT, e); return connect.agent.initialized && e(new connect.Agent), t }, connect.agent.initialized = !1, connect.contact = function (e) { return connect.core.getEventBus().subscribe(connect.ContactEvents.INIT, e) }, connect.onWebsocketInitFailure = function (e) { var t = connect.core.getEventBus().subscribe(connect.WebSocketEvents.INIT_FAILURE, e); return connect.webSocketInitFailed && e(), t }, connect.ifMaster = function (e, t, n, o) { if (connect.assertNotNull(e, "A topic must be provided."), connect.assertNotNull(t, "A true callback must be provided."), !connect.core.masterClient) return connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", e).sendInternalLogToServer(), void (n && n()); connect.core.getMasterClient().call(connect.MasterMethods.CHECK_MASTER, { topic: e, shouldNotBecomeMasterIfNone: o }, { success: function (e) { e.isMaster ? t() : n && n() } }) }, connect.becomeMaster = function (e, t, n) { connect.assertNotNull(e, "A topic must be provided."), connect.core.masterClient ? connect.core.getMasterClient().call(connect.MasterMethods.BECOME_MASTER, { topic: e }, { success: function () { t && t() } }) : (connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", e), n && n()) }, connect.Agent = n, connect.AgentSnapshot = o, connect.Contact = r, connect.ContactSnapshot = i, connect.Connection = a, connect.BaseConnection = s, connect.VoiceConnection = a, connect.ChatConnection = u, connect.TaskConnection = l, connect.ConnectionSnapshot = p, connect.Endpoint = h, connect.Address = h, connect.SoftphoneError = d, connect.VoiceId = c }() }, 538: (e, t, n) => { var o; function r(e) { return r = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, r(e) } !function e(t, n, o) { function r(s, c) { if (!n[s]) { if (!t[s]) { if (i) return i(s, !0); var a = new Error("Cannot find module '" + s + "'"); throw a.code = "MODULE_NOT_FOUND", a } var u = n[s] = { exports: {} }; t[s][0].call(u.exports, (function (e) { return r(t[s][1][e] || e) }), u, u.exports, e, t, n, o) } return n[s].exports } for (var i = void 0, s = 0; s < o.length; s++)r(o[s]); return r }({ 1: [function (e, t, n) { t.exports = { version: "2.0", metadata: { apiVersion: "2014-06-30", endpointPrefix: "cognito-identity", jsonVersion: "1.1", protocol: "json", serviceFullName: "Amazon Cognito Identity", serviceId: "Cognito Identity", signatureVersion: "v4", targetPrefix: "AWSCognitoIdentityService", uid: "cognito-identity-2014-06-30" }, operations: { CreateIdentityPool: { input: { type: "structure", required: ["IdentityPoolName", "AllowUnauthenticatedIdentities"], members: { IdentityPoolName: {}, AllowUnauthenticatedIdentities: { type: "boolean" }, SupportedLoginProviders: { shape: "S4" }, DeveloperProviderName: {}, OpenIdConnectProviderARNs: { shape: "S8" }, CognitoIdentityProviders: { shape: "Sa" }, SamlProviderARNs: { shape: "Sf" }, IdentityPoolTags: { shape: "Sg" } } }, output: { shape: "Sj" } }, DeleteIdentities: { input: { type: "structure", required: ["IdentityIdsToDelete"], members: { IdentityIdsToDelete: { type: "list", member: {} } } }, output: { type: "structure", members: { UnprocessedIdentityIds: { type: "list", member: { type: "structure", members: { IdentityId: {}, ErrorCode: {} } } } } } }, DeleteIdentityPool: { input: { type: "structure", required: ["IdentityPoolId"], members: { IdentityPoolId: {} } } }, DescribeIdentity: { input: { type: "structure", required: ["IdentityId"], members: { IdentityId: {} } }, output: { shape: "Su" } }, DescribeIdentityPool: { input: { type: "structure", required: ["IdentityPoolId"], members: { IdentityPoolId: {} } }, output: { shape: "Sj" } }, GetCredentialsForIdentity: { input: { type: "structure", required: ["IdentityId"], members: { IdentityId: {}, Logins: { shape: "Sz" }, CustomRoleArn: {} } }, output: { type: "structure", members: { IdentityId: {}, Credentials: { type: "structure", members: { AccessKeyId: {}, SecretKey: {}, SessionToken: {}, Expiration: { type: "timestamp" } } } } } }, GetId: { input: { type: "structure", required: ["IdentityPoolId"], members: { AccountId: {}, IdentityPoolId: {}, Logins: { shape: "Sz" } } }, output: { type: "structure", members: { IdentityId: {} } } }, GetIdentityPoolRoles: { input: { type: "structure", required: ["IdentityPoolId"], members: { IdentityPoolId: {} } }, output: { type: "structure", members: { IdentityPoolId: {}, Roles: { shape: "S1b" }, RoleMappings: { shape: "S1d" } } } }, GetOpenIdToken: { input: { type: "structure", required: ["IdentityId"], members: { IdentityId: {}, Logins: { shape: "Sz" } } }, output: { type: "structure", members: { IdentityId: {}, Token: {} } } }, GetOpenIdTokenForDeveloperIdentity: { input: { type: "structure", required: ["IdentityPoolId", "Logins"], members: { IdentityPoolId: {}, IdentityId: {}, Logins: { shape: "Sz" }, TokenDuration: { type: "long" } } }, output: { type: "structure", members: { IdentityId: {}, Token: {} } } }, ListIdentities: { input: { type: "structure", required: ["IdentityPoolId", "MaxResults"], members: { IdentityPoolId: {}, MaxResults: { type: "integer" }, NextToken: {}, HideDisabled: { type: "boolean" } } }, output: { type: "structure", members: { IdentityPoolId: {}, Identities: { type: "list", member: { shape: "Su" } }, NextToken: {} } } }, ListIdentityPools: { input: { type: "structure", required: ["MaxResults"], members: { MaxResults: { type: "integer" }, NextToken: {} } }, output: { type: "structure", members: { IdentityPools: { type: "list", member: { type: "structure", members: { IdentityPoolId: {}, IdentityPoolName: {} } } }, NextToken: {} } } }, ListTagsForResource: { input: { type: "structure", required: ["ResourceArn"], members: { ResourceArn: {} } }, output: { type: "structure", members: { Tags: { shape: "Sg" } } } }, LookupDeveloperIdentity: { input: { type: "structure", required: ["IdentityPoolId"], members: { IdentityPoolId: {}, IdentityId: {}, DeveloperUserIdentifier: {}, MaxResults: { type: "integer" }, NextToken: {} } }, output: { type: "structure", members: { IdentityId: {}, DeveloperUserIdentifierList: { type: "list", member: {} }, NextToken: {} } } }, MergeDeveloperIdentities: { input: { type: "structure", required: ["SourceUserIdentifier", "DestinationUserIdentifier", "DeveloperProviderName", "IdentityPoolId"], members: { SourceUserIdentifier: {}, DestinationUserIdentifier: {}, DeveloperProviderName: {}, IdentityPoolId: {} } }, output: { type: "structure", members: { IdentityId: {} } } }, SetIdentityPoolRoles: { input: { type: "structure", required: ["IdentityPoolId", "Roles"], members: { IdentityPoolId: {}, Roles: { shape: "S1b" }, RoleMappings: { shape: "S1d" } } } }, TagResource: { input: { type: "structure", required: ["ResourceArn"], members: { ResourceArn: {}, Tags: { shape: "Sg" } } }, output: { type: "structure", members: {} } }, UnlinkDeveloperIdentity: { input: { type: "structure", required: ["IdentityId", "IdentityPoolId", "DeveloperProviderName", "DeveloperUserIdentifier"], members: { IdentityId: {}, IdentityPoolId: {}, DeveloperProviderName: {}, DeveloperUserIdentifier: {} } } }, UnlinkIdentity: { input: { type: "structure", required: ["IdentityId", "Logins", "LoginsToRemove"], members: { IdentityId: {}, Logins: { shape: "Sz" }, LoginsToRemove: { shape: "Sv" } } } }, UntagResource: { input: { type: "structure", required: ["ResourceArn"], members: { ResourceArn: {}, TagKeys: { type: "list", member: {} } } }, output: { type: "structure", members: {} } }, UpdateIdentityPool: { input: { shape: "Sj" }, output: { shape: "Sj" } } }, shapes: { S4: { type: "map", key: {}, value: {} }, S8: { type: "list", member: {} }, Sa: { type: "list", member: { type: "structure", members: { ProviderName: {}, ClientId: {}, ServerSideTokenCheck: { type: "boolean" } } } }, Sf: { type: "list", member: {} }, Sg: { type: "map", key: {}, value: {} }, Sj: { type: "structure", required: ["IdentityPoolId", "IdentityPoolName", "AllowUnauthenticatedIdentities"], members: { IdentityPoolId: {}, IdentityPoolName: {}, AllowUnauthenticatedIdentities: { type: "boolean" }, SupportedLoginProviders: { shape: "S4" }, DeveloperProviderName: {}, OpenIdConnectProviderARNs: { shape: "S8" }, CognitoIdentityProviders: { shape: "Sa" }, SamlProviderARNs: { shape: "Sf" }, IdentityPoolTags: { shape: "Sg" } } }, Su: { type: "structure", members: { IdentityId: {}, Logins: { shape: "Sv" }, CreationDate: { type: "timestamp" }, LastModifiedDate: { type: "timestamp" } } }, Sv: { type: "list", member: {} }, Sz: { type: "map", key: {}, value: {} }, S1b: { type: "map", key: {}, value: {} }, S1d: { type: "map", key: {}, value: { type: "structure", required: ["Type"], members: { Type: {}, AmbiguousRoleResolution: {}, RulesConfiguration: { type: "structure", required: ["Rules"], members: { Rules: { type: "list", member: { type: "structure", required: ["Claim", "MatchType", "Value", "RoleARN"], members: { Claim: {}, MatchType: {}, Value: {}, RoleARN: {} } } } } } } } } } } }, {}], 2: [function (e, t, n) { t.exports = { pagination: {} } }, {}], 3: [function (e, t, n) { t.exports = { version: "2.0", metadata: { apiVersion: "2017-02-15", endpointPrefix: "connect", jsonVersion: "1.0", protocol: "json", serviceAbbreviation: "Connect", serviceFullName: "AmazonConnectCTIService", signatureVersion: "", targetPrefix: "AmazonConnectCTIService", uid: "connect-2017-02-15" }, operations: { AcceptContact: { input: { type: "structure", required: ["authentication", "contactId"], members: { authentication: { shape: "S2" }, contactId: {} } }, output: { type: "structure", members: {} } }, ClearContact: { input: { type: "structure", required: ["contactId"], members: { contactId: {} } }, output: { type: "structure", members: {} } }, CompleteContact: { input: { type: "structure", required: ["contactId"], members: { contactId: {} } }, output: { type: "structure", members: {} } }, ConferenceConnections: { input: { type: "structure", required: ["authentication", "contactId"], members: { authentication: { shape: "S2" }, contactId: {} } }, output: { type: "structure", members: {} } }, CreateAdditionalConnection: { input: { type: "structure", required: ["authentication", "contactId", "endpoint"], members: { authentication: { shape: "S2" }, contactId: {}, endpoint: { shape: "Se" } } }, output: { type: "structure", members: {} } }, CreateOutboundContact: { input: { type: "structure", required: ["authentication", "endpoint"], members: { authentication: { shape: "S2" }, endpoint: { shape: "Se" }, queueARN: {} } }, output: { type: "structure", members: {} } }, CreateTaskContact: { input: { type: "structure", required: ["endpoint", "name"], members: { endpoint: { shape: "Se" }, previousContactId: {}, name: {}, description: {}, references: { shape: "Sr" }, idempotencyToken: {}, scheduledTime: { type: "long" } } }, output: { type: "structure", members: { contactId: {} } } }, CreateTransport: { input: { type: "structure", required: ["transportType", "authentication"], members: { transportType: {}, participantId: {}, contactId: {}, softphoneClientId: {}, authentication: { shape: "S2" } } }, output: { type: "structure", members: { webSocketTransport: { type: "structure", required: ["url", "transportLifeTimeInSeconds"], members: { url: {}, transportLifeTimeInSeconds: { type: "long" }, expiry: {} } }, chatTokenTransport: { type: "structure", required: ["participantToken", "expiry"], members: { participantToken: {}, expiry: {} } }, softphoneTransport: { type: "structure", required: ["softphoneMediaConnections"], members: { softphoneMediaConnections: { type: "list", member: { type: "structure", required: ["username", "credential", "urls"], members: { username: {}, credential: {}, urls: { type: "list", member: {} } } } } } } } } }, DestroyConnection: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, GetAgentConfiguration: { input: { type: "structure", required: ["authentication"], members: { authentication: { shape: "S2" } } }, output: { type: "structure", required: ["configuration"], members: { configuration: { shape: "S1h" } } } }, GetAgentPermissions: { input: { type: "structure", required: ["authentication"], members: { authentication: { shape: "S2" }, nextToken: {}, maxResults: { type: "integer" } } }, output: { type: "structure", required: ["permissions"], members: { permissions: { type: "list", member: {} }, nextToken: {} } } }, GetAgentSnapshot: { input: { type: "structure", required: ["authentication"], members: { authentication: { shape: "S2" }, nextToken: {}, timeout: { type: "long" } } }, output: { type: "structure", required: ["snapshot", "nextToken"], members: { snapshot: { type: "structure", required: ["state", "contacts", "snapshotTimestamp"], members: { state: { shape: "S20" }, nextState: { shape: "S20" }, agentAvailabilityState: { type: "structure", members: { state: {}, timeStamp: { type: "timestamp" } } }, contacts: { type: "list", member: { type: "structure", required: ["contactId", "type", "state", "connections", "attributes"], members: { contactId: {}, initialContactId: {}, type: {}, state: { type: "structure", required: ["type", "timestamp"], members: { type: {}, timestamp: { type: "timestamp" } } }, queue: { shape: "Sk" }, queueTimestamp: { type: "timestamp" }, connections: { type: "list", member: { type: "structure", required: ["connectionId", "state", "type", "initial"], members: { connectionId: {}, endpoint: { shape: "Se" }, state: { type: "structure", required: ["type", "timestamp"], members: { type: {}, timestamp: { type: "timestamp" } } }, type: {}, initial: { type: "boolean" }, softphoneMediaInfo: { type: "structure", members: { callType: {}, autoAccept: { type: "boolean" }, mediaLegContextToken: {}, callContextToken: {}, callConfigJson: {} } }, chatMediaInfo: { type: "structure", members: { chatAutoAccept: { type: "boolean" }, connectionData: {}, customerName: {} } }, monitoringInfo: { type: "structure", members: { agent: { type: "structure", members: { agentName: {} } }, joinTimeStamp: { type: "timestamp" } } }, mute: { type: "boolean" }, quickConnectName: {} } } }, attributes: { type: "map", key: {}, value: { type: "structure", required: ["name"], members: { name: {}, value: {} } } }, contactDuration: {}, name: {}, description: {}, references: { shape: "Sr" }, initiationMethod: {}, contactFeatures: { type: "structure", members: { attachmentsEnabled: { type: "boolean" } } } } } }, snapshotTimestamp: { type: "timestamp" } } }, nextToken: {} } } }, GetAgentStates: { input: { type: "structure", required: ["authentication"], members: { authentication: { shape: "S2" }, nextToken: {}, maxResults: { type: "integer" } } }, output: { type: "structure", required: ["states"], members: { states: { type: "list", member: { shape: "S20" } }, nextToken: {} } } }, GetDialableCountryCodes: { input: { type: "structure", required: ["authentication"], members: { authentication: { shape: "S2" }, nextToken: {}, maxResults: { type: "integer" } } }, output: { type: "structure", required: ["countryCodes"], members: { countryCodes: { type: "list", member: {} }, nextToken: {} } } }, GetEndpoints: { input: { type: "structure", required: ["authentication", "queueARNs"], members: { authentication: { shape: "S2" }, queueARNs: { type: "list", member: {} }, nextToken: {}, maxResults: { type: "integer" } } }, output: { type: "structure", members: { endpoints: { type: "list", member: { shape: "Se" } }, nextToken: {} } } }, GetNewAuthToken: { input: { type: "structure", required: ["authentication", "refreshToken"], members: { authentication: { shape: "S2" }, refreshToken: {} } }, output: { type: "structure", members: { newAuthToken: {}, expirationDateTime: { type: "timestamp" } } } }, GetRoutingProfileQueues: { input: { type: "structure", required: ["authentication", "routingProfileARN"], members: { authentication: { shape: "S2" }, routingProfileARN: {}, nextToken: {}, maxResults: { type: "integer" } } }, output: { type: "structure", required: ["queues"], members: { queues: { type: "list", member: { shape: "Sk" } }, nextToken: {} } } }, HoldConnection: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, MuteParticipant: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, NotifyContactIssue: { input: { type: "structure", required: ["authentication", "contactId"], members: { authentication: { shape: "S2" }, contactId: {}, issueCode: {}, description: {}, clientLogs: {} } }, output: { type: "structure", members: {} } }, PutAgentState: { input: { type: "structure", required: ["authentication", "state"], members: { authentication: { shape: "S2" }, state: { shape: "S20" }, enqueueNextState: { type: "boolean" } } }, output: { type: "structure", members: {} } }, RejectContact: { input: { type: "structure", required: ["contactId"], members: { contactId: {} } }, output: { type: "structure", members: {} } }, ResumeConnection: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, SendClientLogs: { input: { type: "structure", required: ["authentication", "logEvents"], members: { authentication: { shape: "S2" }, logEvents: { type: "list", member: { type: "structure", members: { timestamp: { type: "timestamp" }, component: {}, message: {} } } } } }, output: { type: "structure", members: {} } }, SendDigits: { input: { type: "structure", required: ["authentication", "contactId", "connectionId", "digits"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {}, digits: {} } }, output: { type: "structure", members: {} } }, SendSoftphoneCallMetrics: { input: { type: "structure", required: ["authentication", "contactId", "softphoneStreamStatistics"], members: { authentication: { shape: "S2" }, contactId: {}, ccpVersion: {}, softphoneStreamStatistics: { shape: "S3r" } } }, output: { type: "structure", members: {} } }, SendSoftphoneCallReport: { input: { type: "structure", required: ["authentication", "contactId", "report"], members: { authentication: { shape: "S2" }, contactId: {}, ccpVersion: {}, report: { type: "structure", members: { callStartTime: { type: "timestamp" }, callEndTime: { type: "timestamp" }, softphoneStreamStatistics: { shape: "S3r" }, gumTimeMillis: { type: "long" }, initializationTimeMillis: { type: "long" }, iceCollectionTimeMillis: { type: "long" }, signallingConnectTimeMillis: { type: "long" }, handshakeTimeMillis: { type: "long" }, preTalkTimeMillis: { type: "long" }, talkTimeMillis: { type: "long" }, cleanupTimeMillis: { type: "long" }, iceCollectionFailure: { type: "boolean" }, signallingConnectionFailure: { type: "boolean" }, handshakeFailure: { type: "boolean" }, gumOtherFailure: { type: "boolean" }, gumTimeoutFailure: { type: "boolean" }, createOfferFailure: { type: "boolean" }, setLocalDescriptionFailure: { type: "boolean" }, userBusyFailure: { type: "boolean" }, invalidRemoteSDPFailure: { type: "boolean" }, noRemoteIceCandidateFailure: { type: "boolean" }, setRemoteDescriptionFailure: { type: "boolean" } } } } }, output: { type: "structure", members: {} } }, ToggleActiveConnections: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, UnmuteParticipant: { input: { type: "structure", required: ["authentication", "contactId", "connectionId"], members: { authentication: { shape: "S2" }, contactId: {}, connectionId: {} } }, output: { type: "structure", members: {} } }, UpdateAgentConfiguration: { input: { type: "structure", required: ["authentication", "configuration"], members: { authentication: { shape: "S2" }, configuration: { shape: "S1h" } } }, output: { type: "structure", members: {} } } }, shapes: { S2: { type: "structure", members: { agentARN: {}, authToken: {} } }, Se: { type: "structure", required: ["type"], members: { endpointARN: {}, type: {}, name: {}, phoneNumber: {}, agentLogin: {}, queue: { shape: "Sk" } } }, Sk: { type: "structure", members: { queueARN: {}, name: {} } }, Sr: { type: "map", key: {}, value: { type: "structure", required: ["value", "type"], members: { value: {}, type: {} } } }, S1h: { type: "structure", required: ["name", "softphoneEnabled", "softphoneAutoAccept", "extension", "routingProfile"], members: { name: {}, username: {}, softphoneEnabled: { type: "boolean" }, softphoneAutoAccept: { type: "boolean" }, extension: {}, routingProfile: { type: "structure", members: { name: {}, routingProfileARN: {}, defaultOutboundQueue: { shape: "Sk" }, channelConcurrencyMap: { type: "map", key: {}, value: { type: "long" } } } }, agentPreferences: { type: "map", key: {}, value: {} } } }, S20: { type: "structure", required: ["type", "name"], members: { agentStateARN: {}, type: {}, name: {}, startTimestamp: { type: "timestamp" } } }, S3r: { type: "list", member: { type: "structure", members: { timestamp: { type: "timestamp" }, softphoneStreamType: {}, packetCount: { type: "long" }, packetsLost: { type: "long" }, audioLevel: { type: "double" }, jitterBufferMillis: { type: "long" }, roundTripTimeMillis: { type: "long" } } } } } } }, {}], 4: [function (e, t, n) { t.exports = { acm: { name: "ACM", cors: !0 }, apigateway: { name: "APIGateway", cors: !0 }, applicationautoscaling: { prefix: "application-autoscaling", name: "ApplicationAutoScaling", cors: !0 }, appstream: { name: "AppStream" }, autoscaling: { name: "AutoScaling", cors: !0 }, batch: { name: "Batch" }, budgets: { name: "Budgets" }, clouddirectory: { name: "CloudDirectory", versions: ["2016-05-10*"] }, cloudformation: { name: "CloudFormation", cors: !0 }, cloudfront: { name: "CloudFront", versions: ["2013-05-12*", "2013-11-11*", "2014-05-31*", "2014-10-21*", "2014-11-06*", "2015-04-17*", "2015-07-27*", "2015-09-17*", "2016-01-13*", "2016-01-28*", "2016-08-01*", "2016-08-20*", "2016-09-07*", "2016-09-29*", "2016-11-25*", "2017-03-25*", "2017-10-30*", "2018-06-18*", "2018-11-05*"], cors: !0 }, cloudhsm: { name: "CloudHSM", cors: !0 }, cloudsearch: { name: "CloudSearch" }, cloudsearchdomain: { name: "CloudSearchDomain" }, cloudtrail: { name: "CloudTrail", cors: !0 }, cloudwatch: { prefix: "monitoring", name: "CloudWatch", cors: !0 }, cloudwatchevents: { prefix: "events", name: "CloudWatchEvents", versions: ["2014-02-03*"], cors: !0 }, cloudwatchlogs: { prefix: "logs", name: "CloudWatchLogs", cors: !0 }, codebuild: { name: "CodeBuild", cors: !0 }, codecommit: { name: "CodeCommit", cors: !0 }, codedeploy: { name: "CodeDeploy", cors: !0 }, codepipeline: { name: "CodePipeline", cors: !0 }, cognitoidentity: { prefix: "cognito-identity", name: "CognitoIdentity", cors: !0 }, cognitoidentityserviceprovider: { prefix: "cognito-idp", name: "CognitoIdentityServiceProvider", cors: !0 }, cognitosync: { prefix: "cognito-sync", name: "CognitoSync", cors: !0 }, configservice: { prefix: "config", name: "ConfigService", cors: !0 }, connect: { name: "Connect", cors: !0 }, cur: { name: "CUR", cors: !0 }, datapipeline: { name: "DataPipeline" }, devicefarm: { name: "DeviceFarm", cors: !0 }, directconnect: { name: "DirectConnect", cors: !0 }, directoryservice: { prefix: "ds", name: "DirectoryService" }, discovery: { name: "Discovery" }, dms: { name: "DMS" }, dynamodb: { name: "DynamoDB", cors: !0 }, dynamodbstreams: { prefix: "streams.dynamodb", name: "DynamoDBStreams", cors: !0 }, ec2: { name: "EC2", versions: ["2013-06-15*", "2013-10-15*", "2014-02-01*", "2014-05-01*", "2014-06-15*", "2014-09-01*", "2014-10-01*", "2015-03-01*", "2015-04-15*", "2015-10-01*", "2016-04-01*", "2016-09-15*"], cors: !0 }, ecr: { name: "ECR", cors: !0 }, ecs: { name: "ECS", cors: !0 }, efs: { prefix: "elasticfilesystem", name: "EFS", cors: !0 }, elasticache: { name: "ElastiCache", versions: ["2012-11-15*", "2014-03-24*", "2014-07-15*", "2014-09-30*"], cors: !0 }, elasticbeanstalk: { name: "ElasticBeanstalk", cors: !0 }, elb: { prefix: "elasticloadbalancing", name: "ELB", cors: !0 }, elbv2: { prefix: "elasticloadbalancingv2", name: "ELBv2", cors: !0 }, emr: { prefix: "elasticmapreduce", name: "EMR", cors: !0 }, es: { name: "ES" }, elastictranscoder: { name: "ElasticTranscoder", cors: !0 }, firehose: { name: "Firehose", cors: !0 }, gamelift: { name: "GameLift", cors: !0 }, glacier: { name: "Glacier" }, health: { name: "Health" }, iam: { name: "IAM", cors: !0 }, importexport: { name: "ImportExport" }, inspector: { name: "Inspector", versions: ["2015-08-18*"], cors: !0 }, iot: { name: "Iot", cors: !0 }, iotdata: { prefix: "iot-data", name: "IotData", cors: !0 }, kinesis: { name: "Kinesis", cors: !0 }, kinesisanalytics: { name: "KinesisAnalytics" }, kms: { name: "KMS", cors: !0 }, lambda: { name: "Lambda", cors: !0 }, lexruntime: { prefix: "runtime.lex", name: "LexRuntime", cors: !0 }, lightsail: { name: "Lightsail" }, machinelearning: { name: "MachineLearning", cors: !0 }, marketplacecommerceanalytics: { name: "MarketplaceCommerceAnalytics", cors: !0 }, marketplacemetering: { prefix: "meteringmarketplace", name: "MarketplaceMetering" }, mturk: { prefix: "mturk-requester", name: "MTurk", cors: !0 }, mobileanalytics: { name: "MobileAnalytics", cors: !0 }, opsworks: { name: "OpsWorks", cors: !0 }, opsworkscm: { name: "OpsWorksCM" }, organizations: { name: "Organizations" }, pinpoint: { name: "Pinpoint" }, polly: { name: "Polly", cors: !0 }, rds: { name: "RDS", versions: ["2014-09-01*"], cors: !0 }, redshift: { name: "Redshift", cors: !0 }, rekognition: { name: "Rekognition", cors: !0 }, resourcegroupstaggingapi: { name: "ResourceGroupsTaggingAPI" }, route53: { name: "Route53", cors: !0 }, route53domains: { name: "Route53Domains", cors: !0 }, s3: { name: "S3", dualstackAvailable: !0, cors: !0 }, s3control: { name: "S3Control", dualstackAvailable: !0 }, servicecatalog: { name: "ServiceCatalog", cors: !0 }, ses: { prefix: "email", name: "SES", cors: !0 }, shield: { name: "Shield" }, simpledb: { prefix: "sdb", name: "SimpleDB" }, sms: { name: "SMS" }, snowball: { name: "Snowball" }, sns: { name: "SNS", cors: !0 }, sqs: { name: "SQS", cors: !0 }, ssm: { name: "SSM", cors: !0 }, storagegateway: { name: "StorageGateway", cors: !0 }, stepfunctions: { prefix: "states", name: "StepFunctions" }, sts: { name: "STS", cors: !0 }, support: { name: "Support" }, swf: { name: "SWF" }, xray: { name: "XRay", cors: !0 }, waf: { name: "WAF", cors: !0 }, wafregional: { prefix: "waf-regional", name: "WAFRegional" }, workdocs: { name: "WorkDocs", cors: !0 }, workspaces: { name: "WorkSpaces" }, codestar: { name: "CodeStar" }, lexmodelbuildingservice: { prefix: "lex-models", name: "LexModelBuildingService", cors: !0 }, marketplaceentitlementservice: { prefix: "entitlement.marketplace", name: "MarketplaceEntitlementService" }, athena: { name: "Athena" }, greengrass: { name: "Greengrass" }, dax: { name: "DAX" }, migrationhub: { prefix: "AWSMigrationHub", name: "MigrationHub" }, cloudhsmv2: { name: "CloudHSMV2" }, glue: { name: "Glue" }, mobile: { name: "Mobile" }, pricing: { name: "Pricing", cors: !0 }, costexplorer: { prefix: "ce", name: "CostExplorer", cors: !0 }, mediaconvert: { name: "MediaConvert" }, medialive: { name: "MediaLive" }, mediapackage: { name: "MediaPackage" }, mediastore: { name: "MediaStore" }, mediastoredata: { prefix: "mediastore-data", name: "MediaStoreData", cors: !0 }, appsync: { name: "AppSync" }, guardduty: { name: "GuardDuty" }, mq: { name: "MQ" }, comprehend: { name: "Comprehend", cors: !0 }, iotjobsdataplane: { prefix: "iot-jobs-data", name: "IoTJobsDataPlane" }, kinesisvideoarchivedmedia: { prefix: "kinesis-video-archived-media", name: "KinesisVideoArchivedMedia", cors: !0 }, kinesisvideomedia: { prefix: "kinesis-video-media", name: "KinesisVideoMedia", cors: !0 }, kinesisvideo: { name: "KinesisVideo", cors: !0 }, sagemakerruntime: { prefix: "runtime.sagemaker", name: "SageMakerRuntime" }, sagemaker: { name: "SageMaker" }, translate: { name: "Translate", cors: !0 }, resourcegroups: { prefix: "resource-groups", name: "ResourceGroups", cors: !0 }, alexaforbusiness: { name: "AlexaForBusiness" }, cloud9: { name: "Cloud9" }, serverlessapplicationrepository: { prefix: "serverlessrepo", name: "ServerlessApplicationRepository" }, servicediscovery: { name: "ServiceDiscovery" }, workmail: { name: "WorkMail" }, autoscalingplans: { prefix: "autoscaling-plans", name: "AutoScalingPlans" }, transcribeservice: { prefix: "transcribe", name: "TranscribeService" }, acmpca: { prefix: "acm-pca", name: "ACMPCA" }, fms: { name: "FMS" }, secretsmanager: { name: "SecretsManager", cors: !0 }, iotanalytics: { name: "IoTAnalytics", cors: !0 }, iot1clickdevicesservice: { prefix: "iot1click-devices", name: "IoT1ClickDevicesService" }, iot1clickprojects: { prefix: "iot1click-projects", name: "IoT1ClickProjects" }, pi: { name: "PI" }, neptune: { name: "Neptune" }, mediatailor: { name: "MediaTailor" }, eks: { name: "EKS" }, macie: { name: "Macie" }, dlm: { name: "DLM" }, signer: { name: "Signer" }, chime: { name: "Chime" }, pinpointemail: { prefix: "pinpoint-email", name: "PinpointEmail" }, ram: { name: "RAM" }, route53resolver: { name: "Route53Resolver" }, pinpointsmsvoice: { prefix: "sms-voice", name: "PinpointSMSVoice" }, quicksight: { name: "QuickSight" }, rdsdataservice: { prefix: "rds-data", name: "RDSDataService" }, amplify: { name: "Amplify" }, datasync: { name: "DataSync" }, robomaker: { name: "RoboMaker" }, transfer: { name: "Transfer" }, globalaccelerator: { name: "GlobalAccelerator" }, comprehendmedical: { name: "ComprehendMedical", cors: !0 }, kinesisanalyticsv2: { name: "KinesisAnalyticsV2" }, mediaconnect: { name: "MediaConnect" }, fsx: { name: "FSx" }, securityhub: { name: "SecurityHub" }, appmesh: { name: "AppMesh", versions: ["2018-10-01*"] }, licensemanager: { prefix: "license-manager", name: "LicenseManager" }, kafka: { name: "Kafka" }, apigatewaymanagementapi: { name: "ApiGatewayManagementApi" }, apigatewayv2: { name: "ApiGatewayV2" }, docdb: { name: "DocDB" }, backup: { name: "Backup" }, worklink: { name: "WorkLink" }, textract: { name: "Textract" }, managedblockchain: { name: "ManagedBlockchain" }, mediapackagevod: { prefix: "mediapackage-vod", name: "MediaPackageVod" }, groundstation: { name: "GroundStation" }, iotthingsgraph: { name: "IoTThingsGraph" }, iotevents: { name: "IoTEvents" }, ioteventsdata: { prefix: "iotevents-data", name: "IoTEventsData" }, personalize: { name: "Personalize", cors: !0 }, personalizeevents: { prefix: "personalize-events", name: "PersonalizeEvents", cors: !0 }, personalizeruntime: { prefix: "personalize-runtime", name: "PersonalizeRuntime", cors: !0 }, applicationinsights: { prefix: "application-insights", name: "ApplicationInsights" }, servicequotas: { prefix: "service-quotas", name: "ServiceQuotas" }, ec2instanceconnect: { prefix: "ec2-instance-connect", name: "EC2InstanceConnect" }, eventbridge: { name: "EventBridge" }, lakeformation: { name: "LakeFormation" }, forecastservice: { prefix: "forecast", name: "ForecastService", cors: !0 }, forecastqueryservice: { prefix: "forecastquery", name: "ForecastQueryService", cors: !0 }, qldb: { name: "QLDB" }, qldbsession: { prefix: "qldb-session", name: "QLDBSession" }, workmailmessageflow: { name: "WorkMailMessageFlow" } } }, {}], 5: [function (e, t, n) { t.exports = { version: "2.0", metadata: { apiVersion: "2011-06-15", endpointPrefix: "sts", globalEndpoint: "sts.amazonaws.com", protocol: "query", serviceAbbreviation: "AWS STS", serviceFullName: "AWS Security Token Service", serviceId: "STS", signatureVersion: "v4", uid: "sts-2011-06-15", xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/" }, operations: { AssumeRole: { input: { type: "structure", required: ["RoleArn", "RoleSessionName"], members: { RoleArn: {}, RoleSessionName: {}, PolicyArns: { shape: "S4" }, Policy: {}, DurationSeconds: { type: "integer" }, ExternalId: {}, SerialNumber: {}, TokenCode: {} } }, output: { resultWrapper: "AssumeRoleResult", type: "structure", members: { Credentials: { shape: "Sc" }, AssumedRoleUser: { shape: "Sh" }, PackedPolicySize: { type: "integer" } } } }, AssumeRoleWithSAML: { input: { type: "structure", required: ["RoleArn", "PrincipalArn", "SAMLAssertion"], members: { RoleArn: {}, PrincipalArn: {}, SAMLAssertion: {}, PolicyArns: { shape: "S4" }, Policy: {}, DurationSeconds: { type: "integer" } } }, output: { resultWrapper: "AssumeRoleWithSAMLResult", type: "structure", members: { Credentials: { shape: "Sc" }, AssumedRoleUser: { shape: "Sh" }, PackedPolicySize: { type: "integer" }, Subject: {}, SubjectType: {}, Issuer: {}, Audience: {}, NameQualifier: {} } } }, AssumeRoleWithWebIdentity: { input: { type: "structure", required: ["RoleArn", "RoleSessionName", "WebIdentityToken"], members: { RoleArn: {}, RoleSessionName: {}, WebIdentityToken: {}, ProviderId: {}, PolicyArns: { shape: "S4" }, Policy: {}, DurationSeconds: { type: "integer" } } }, output: { resultWrapper: "AssumeRoleWithWebIdentityResult", type: "structure", members: { Credentials: { shape: "Sc" }, SubjectFromWebIdentityToken: {}, AssumedRoleUser: { shape: "Sh" }, PackedPolicySize: { type: "integer" }, Provider: {}, Audience: {} } } }, DecodeAuthorizationMessage: { input: { type: "structure", required: ["EncodedMessage"], members: { EncodedMessage: {} } }, output: { resultWrapper: "DecodeAuthorizationMessageResult", type: "structure", members: { DecodedMessage: {} } } }, GetAccessKeyInfo: { input: { type: "structure", required: ["AccessKeyId"], members: { AccessKeyId: {} } }, output: { resultWrapper: "GetAccessKeyInfoResult", type: "structure", members: { Account: {} } } }, GetCallerIdentity: { input: { type: "structure", members: {} }, output: { resultWrapper: "GetCallerIdentityResult", type: "structure", members: { UserId: {}, Account: {}, Arn: {} } } }, GetFederationToken: { input: { type: "structure", required: ["Name"], members: { Name: {}, Policy: {}, PolicyArns: { shape: "S4" }, DurationSeconds: { type: "integer" } } }, output: { resultWrapper: "GetFederationTokenResult", type: "structure", members: { Credentials: { shape: "Sc" }, FederatedUser: { type: "structure", required: ["FederatedUserId", "Arn"], members: { FederatedUserId: {}, Arn: {} } }, PackedPolicySize: { type: "integer" } } } }, GetSessionToken: { input: { type: "structure", members: { DurationSeconds: { type: "integer" }, SerialNumber: {}, TokenCode: {} } }, output: { resultWrapper: "GetSessionTokenResult", type: "structure", members: { Credentials: { shape: "Sc" } } } } }, shapes: { S4: { type: "list", member: { type: "structure", members: { arn: {} } } }, Sc: { type: "structure", required: ["AccessKeyId", "SecretAccessKey", "SessionToken", "Expiration"], members: { AccessKeyId: {}, SecretAccessKey: {}, SessionToken: {}, Expiration: { type: "timestamp" } } }, Sh: { type: "structure", required: ["AssumedRoleId", "Arn"], members: { AssumedRoleId: {}, Arn: {} } } } } }, {}], 6: [function (e, t, n) { arguments[4][2][0].apply(n, arguments) }, { dup: 2 }], 7: [function (e, t, n) { e("../lib/node_loader"); var o = e("../lib/core"), r = o.Service, i = o.apiLoader; i.services.cognitoidentity = {}, o.CognitoIdentity = r.defineService("cognitoidentity", ["2014-06-30"]), e("../lib/services/cognitoidentity"), Object.defineProperty(i.services.cognitoidentity, "2014-06-30", { get: function () { var t = e("../apis/cognito-identity-2014-06-30.min.json"); return t.paginators = e("../apis/cognito-identity-2014-06-30.paginators.json").pagination, t }, enumerable: !0, configurable: !0 }), t.exports = o.CognitoIdentity }, { "../apis/cognito-identity-2014-06-30.min.json": 1, "../apis/cognito-identity-2014-06-30.paginators.json": 2, "../lib/core": 18, "../lib/node_loader": 16, "../lib/services/cognitoidentity": 60 }], 8: [function (e, t, n) { e("../lib/node_loader"); var o = e("../lib/core"), r = o.Service, i = o.apiLoader; i.services.sts = {}, o.STS = r.defineService("sts", ["2011-06-15"]), e("../lib/services/sts"), Object.defineProperty(i.services.sts, "2011-06-15", { get: function () { var t = e("../apis/sts-2011-06-15.min.json"); return t.paginators = e("../apis/sts-2011-06-15.paginators.json").pagination, t }, enumerable: !0, configurable: !0 }), t.exports = o.STS }, { "../apis/sts-2011-06-15.min.json": 5, "../apis/sts-2011-06-15.paginators.json": 6, "../lib/core": 18, "../lib/node_loader": 16, "../lib/services/sts": 61 }], 9: [function (e, t, n) { function o(e, t) { if (!o.services.hasOwnProperty(e)) throw new Error("InvalidService: Failed to load api for " + e); return o.services[e][t] } o.services = {}, t.exports = o }, {}], 10: [function (e, t, n) { var o = e("./browserHmac"), r = e("./browserMd5"), i = e("./browserSha1"), s = e("./browserSha256"); t.exports = { createHash: function (e) { if ("md5" === (e = e.toLowerCase())) return new r; if ("sha256" === e) return new s; if ("sha1" === e) return new i; throw new Error("Hash algorithm " + e + " is not supported in the browser SDK") }, createHmac: function (e, t) { if ("md5" === (e = e.toLowerCase())) return new o(r, t); if ("sha256" === e) return new o(s, t); if ("sha1" === e) return new o(i, t); throw new Error("HMAC algorithm " + e + " is not supported in the browser SDK") }, createSign: function () { throw new Error("createSign is not implemented in the browser") } } }, { "./browserHmac": 12, "./browserMd5": 13, "./browserSha1": 14, "./browserSha256": 15 }], 11: [function (e, t, n) { var o = e("buffer/").Buffer; "undefined" != typeof ArrayBuffer && void 0 === ArrayBuffer.isView && (ArrayBuffer.isView = function (e) { return r.indexOf(Object.prototype.toString.call(e)) > -1 }); var r = ["[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]", "[object DataView]"]; t.exports = { isEmptyData: function (e) { return "string" == typeof e ? 0 === e.length : 0 === e.byteLength }, convertToBuffer: function (e) { return "string" == typeof e && (e = new o(e, "utf8")), ArrayBuffer.isView(e) ? new Uint8Array(e.buffer, e.byteOffset, e.byteLength / Uint8Array.BYTES_PER_ELEMENT) : new Uint8Array(e) } } }, { "buffer/": 81 }], 12: [function (e, t, n) { var o = e("./browserHashUtils"); function r(e, t) { this.hash = new e, this.outer = new e; var n = function (e, t) { var n = o.convertToBuffer(t); if (n.byteLength > e.BLOCK_SIZE) { var r = new e; r.update(n), n = r.digest() } var i = new Uint8Array(e.BLOCK_SIZE); return i.set(n), i }(e, t), r = new Uint8Array(e.BLOCK_SIZE); r.set(n); for (var i = 0; i < e.BLOCK_SIZE; i++)n[i] ^= 54, r[i] ^= 92; for (this.hash.update(n), this.outer.update(r), i = 0; i < n.byteLength; i++)n[i] = 0 } t.exports = r, r.prototype.update = function (e) { if (o.isEmptyData(e) || this.error) return this; try { this.hash.update(o.convertToBuffer(e)) } catch (e) { this.error = e } return this }, r.prototype.digest = function (e) { return this.outer.finished || this.outer.update(this.hash.digest()), this.outer.digest(e) } }, { "./browserHashUtils": 11 }], 13: [function (e, t, n) { var o = e("./browserHashUtils"), r = e("buffer/").Buffer, i = 64; function s() { this.state = [1732584193, 4023233417, 2562383102, 271733878], this.buffer = new DataView(new ArrayBuffer(i)), this.bufferLength = 0, this.bytesHashed = 0, this.finished = !1 } function c(e, t, n, o, r, i) { return ((t = (t + e & 4294967295) + (o + i & 4294967295) & 4294967295) << r | t >>> 32 - r) + n & 4294967295 } function a(e, t, n, o, r, i, s) { return c(t & n | ~t & o, e, t, r, i, s) } function u(e, t, n, o, r, i, s) { return c(t & o | n & ~o, e, t, r, i, s) } function l(e, t, n, o, r, i, s) { return c(t ^ n ^ o, e, t, r, i, s) } function p(e, t, n, o, r, i, s) { return c(n ^ (t | ~o), e, t, r, i, s) } t.exports = s, s.BLOCK_SIZE = i, s.prototype.update = function (e) { if (o.isEmptyData(e)) return this; if (this.finished) throw new Error("Attempted to update an already finished hash."); var t = o.convertToBuffer(e), n = 0, r = t.byteLength; for (this.bytesHashed += r; r > 0;)this.buffer.setUint8(this.bufferLength++, t[n++]), r--, this.bufferLength === i && (this.hashBuffer(), this.bufferLength = 0); return this }, s.prototype.digest = function (e) { if (!this.finished) { var t = this, n = t.buffer, o = t.bufferLength, s = 8 * t.bytesHashed; if (n.setUint8(this.bufferLength++, 128), o % i >= 56) { for (var c = this.bufferLength; c < i; c++)n.setUint8(c, 0); this.hashBuffer(), this.bufferLength = 0 } for (c = this.bufferLength; c < 56; c++)n.setUint8(c, 0); n.setUint32(56, s >>> 0, !0), n.setUint32(60, Math.floor(s / 4294967296), !0), this.hashBuffer(), this.finished = !0 } var a = new DataView(new ArrayBuffer(16)); for (c = 0; c < 4; c++)a.setUint32(4 * c, this.state[c], !0); var u = new r(a.buffer, a.byteOffset, a.byteLength); return e ? u.toString(e) : u }, s.prototype.hashBuffer = function () { var e = this.buffer, t = this.state, n = t[0], o = t[1], r = t[2], i = t[3]; n = a(n, o, r, i, e.getUint32(0, !0), 7, 3614090360), i = a(i, n, o, r, e.getUint32(4, !0), 12, 3905402710), r = a(r, i, n, o, e.getUint32(8, !0), 17, 606105819), o = a(o, r, i, n, e.getUint32(12, !0), 22, 3250441966), n = a(n, o, r, i, e.getUint32(16, !0), 7, 4118548399), i = a(i, n, o, r, e.getUint32(20, !0), 12, 1200080426), r = a(r, i, n, o, e.getUint32(24, !0), 17, 2821735955), o = a(o, r, i, n, e.getUint32(28, !0), 22, 4249261313), n = a(n, o, r, i, e.getUint32(32, !0), 7, 1770035416), i = a(i, n, o, r, e.getUint32(36, !0), 12, 2336552879), r = a(r, i, n, o, e.getUint32(40, !0), 17, 4294925233), o = a(o, r, i, n, e.getUint32(44, !0), 22, 2304563134), n = a(n, o, r, i, e.getUint32(48, !0), 7, 1804603682), i = a(i, n, o, r, e.getUint32(52, !0), 12, 4254626195), r = a(r, i, n, o, e.getUint32(56, !0), 17, 2792965006), n = u(n, o = a(o, r, i, n, e.getUint32(60, !0), 22, 1236535329), r, i, e.getUint32(4, !0), 5, 4129170786), i = u(i, n, o, r, e.getUint32(24, !0), 9, 3225465664), r = u(r, i, n, o, e.getUint32(44, !0), 14, 643717713), o = u(o, r, i, n, e.getUint32(0, !0), 20, 3921069994), n = u(n, o, r, i, e.getUint32(20, !0), 5, 3593408605), i = u(i, n, o, r, e.getUint32(40, !0), 9, 38016083), r = u(r, i, n, o, e.getUint32(60, !0), 14, 3634488961), o = u(o, r, i, n, e.getUint32(16, !0), 20, 3889429448), n = u(n, o, r, i, e.getUint32(36, !0), 5, 568446438), i = u(i, n, o, r, e.getUint32(56, !0), 9, 3275163606), r = u(r, i, n, o, e.getUint32(12, !0), 14, 4107603335), o = u(o, r, i, n, e.getUint32(32, !0), 20, 1163531501), n = u(n, o, r, i, e.getUint32(52, !0), 5, 2850285829), i = u(i, n, o, r, e.getUint32(8, !0), 9, 4243563512), r = u(r, i, n, o, e.getUint32(28, !0), 14, 1735328473), n = l(n, o = u(o, r, i, n, e.getUint32(48, !0), 20, 2368359562), r, i, e.getUint32(20, !0), 4, 4294588738), i = l(i, n, o, r, e.getUint32(32, !0), 11, 2272392833), r = l(r, i, n, o, e.getUint32(44, !0), 16, 1839030562), o = l(o, r, i, n, e.getUint32(56, !0), 23, 4259657740), n = l(n, o, r, i, e.getUint32(4, !0), 4, 2763975236), i = l(i, n, o, r, e.getUint32(16, !0), 11, 1272893353), r = l(r, i, n, o, e.getUint32(28, !0), 16, 4139469664), o = l(o, r, i, n, e.getUint32(40, !0), 23, 3200236656), n = l(n, o, r, i, e.getUint32(52, !0), 4, 681279174), i = l(i, n, o, r, e.getUint32(0, !0), 11, 3936430074), r = l(r, i, n, o, e.getUint32(12, !0), 16, 3572445317), o = l(o, r, i, n, e.getUint32(24, !0), 23, 76029189), n = l(n, o, r, i, e.getUint32(36, !0), 4, 3654602809), i = l(i, n, o, r, e.getUint32(48, !0), 11, 3873151461), r = l(r, i, n, o, e.getUint32(60, !0), 16, 530742520), n = p(n, o = l(o, r, i, n, e.getUint32(8, !0), 23, 3299628645), r, i, e.getUint32(0, !0), 6, 4096336452), i = p(i, n, o, r, e.getUint32(28, !0), 10, 1126891415), r = p(r, i, n, o, e.getUint32(56, !0), 15, 2878612391), o = p(o, r, i, n, e.getUint32(20, !0), 21, 4237533241), n = p(n, o, r, i, e.getUint32(48, !0), 6, 1700485571), i = p(i, n, o, r, e.getUint32(12, !0), 10, 2399980690), r = p(r, i, n, o, e.getUint32(40, !0), 15, 4293915773), o = p(o, r, i, n, e.getUint32(4, !0), 21, 2240044497), n = p(n, o, r, i, e.getUint32(32, !0), 6, 1873313359), i = p(i, n, o, r, e.getUint32(60, !0), 10, 4264355552), r = p(r, i, n, o, e.getUint32(24, !0), 15, 2734768916), o = p(o, r, i, n, e.getUint32(52, !0), 21, 1309151649), n = p(n, o, r, i, e.getUint32(16, !0), 6, 4149444226), i = p(i, n, o, r, e.getUint32(44, !0), 10, 3174756917), r = p(r, i, n, o, e.getUint32(8, !0), 15, 718787259), o = p(o, r, i, n, e.getUint32(36, !0), 21, 3951481745), t[0] = n + t[0] & 4294967295, t[1] = o + t[1] & 4294967295, t[2] = r + t[2] & 4294967295, t[3] = i + t[3] & 4294967295 } }, { "./browserHashUtils": 11, "buffer/": 81 }], 14: [function (e, t, n) { var o = e("buffer/").Buffer, r = e("./browserHashUtils"); function i() { this.h0 = 1732584193, this.h1 = 4023233417, this.h2 = 2562383102, this.h3 = 271733878, this.h4 = 3285377520, this.block = new Uint32Array(80), this.offset = 0, this.shift = 24, this.totalLength = 0 } new Uint32Array([1518500249, 1859775393, -1894007588, -899497514]), Math.pow(2, 53), t.exports = i, i.BLOCK_SIZE = 64, i.prototype.update = function (e) { if (this.finished) throw new Error("Attempted to update an already finished hash."); if (r.isEmptyData(e)) return this; var t = (e = r.convertToBuffer(e)).length; this.totalLength += 8 * t; for (var n = 0; n < t; n++)this.write(e[n]); return this }, i.prototype.write = function (e) { this.block[this.offset] |= (255 & e) << this.shift, this.shift ? this.shift -= 8 : (this.offset++, this.shift = 24), 16 === this.offset && this.processBlock() }, i.prototype.digest = function (e) { this.write(128), (this.offset > 14 || 14 === this.offset && this.shift < 24) && this.processBlock(), this.offset = 14, this.shift = 24, this.write(0), this.write(0), this.write(this.totalLength > 0xffffffffff ? this.totalLength / 1099511627776 : 0), this.write(this.totalLength > 4294967295 ? this.totalLength / 4294967296 : 0); for (var t = 24; t >= 0; t -= 8)this.write(this.totalLength >> t); var n = new o(20), r = new DataView(n.buffer); return r.setUint32(0, this.h0, !1), r.setUint32(4, this.h1, !1), r.setUint32(8, this.h2, !1), r.setUint32(12, this.h3, !1), r.setUint32(16, this.h4, !1), e ? n.toString(e) : n }, i.prototype.processBlock = function () { for (var e = 16; e < 80; e++) { var t = this.block[e - 3] ^ this.block[e - 8] ^ this.block[e - 14] ^ this.block[e - 16]; this.block[e] = t << 1 | t >>> 31 } var n, o, r = this.h0, i = this.h1, s = this.h2, c = this.h3, a = this.h4; for (e = 0; e < 80; e++) { e < 20 ? (n = c ^ i & (s ^ c), o = 1518500249) : e < 40 ? (n = i ^ s ^ c, o = 1859775393) : e < 60 ? (n = i & s | c & (i | s), o = 2400959708) : (n = i ^ s ^ c, o = 3395469782); var u = (r << 5 | r >>> 27) + n + a + o + (0 | this.block[e]); a = c, c = s, s = i << 30 | i >>> 2, i = r, r = u } for (this.h0 = this.h0 + r | 0, this.h1 = this.h1 + i | 0, this.h2 = this.h2 + s | 0, this.h3 = this.h3 + c | 0, this.h4 = this.h4 + a | 0, this.offset = 0, e = 0; e < 16; e++)this.block[e] = 0 } }, { "./browserHashUtils": 11, "buffer/": 81 }], 15: [function (e, t, n) { var o = e("buffer/").Buffer, r = e("./browserHashUtils"), i = 64, s = new Uint32Array([1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]), c = Math.pow(2, 53) - 1; function a() { this.state = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.temp = new Int32Array(64), this.buffer = new Uint8Array(64), this.bufferLength = 0, this.bytesHashed = 0, this.finished = !1 } t.exports = a, a.BLOCK_SIZE = i, a.prototype.update = function (e) { if (this.finished) throw new Error("Attempted to update an already finished hash."); if (r.isEmptyData(e)) return this; var t = 0, n = (e = r.convertToBuffer(e)).byteLength; if (this.bytesHashed += n, 8 * this.bytesHashed > c) throw new Error("Cannot hash more than 2^53 - 1 bits"); for (; n > 0;)this.buffer[this.bufferLength++] = e[t++], n--, this.bufferLength === i && (this.hashBuffer(), this.bufferLength = 0); return this }, a.prototype.digest = function (e) { if (!this.finished) { var t = 8 * this.bytesHashed, n = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength), r = this.bufferLength; if (n.setUint8(this.bufferLength++, 128), r % i >= 56) { for (var s = this.bufferLength; s < i; s++)n.setUint8(s, 0); this.hashBuffer(), this.bufferLength = 0 } for (s = this.bufferLength; s < 56; s++)n.setUint8(s, 0); n.setUint32(56, Math.floor(t / 4294967296), !0), n.setUint32(60, t), this.hashBuffer(), this.finished = !0 } var c = new o(32); for (s = 0; s < 8; s++)c[4 * s] = this.state[s] >>> 24 & 255, c[4 * s + 1] = this.state[s] >>> 16 & 255, c[4 * s + 2] = this.state[s] >>> 8 & 255, c[4 * s + 3] = this.state[s] >>> 0 & 255; return e ? c.toString(e) : c }, a.prototype.hashBuffer = function () { for (var e = this.buffer, t = this.state, n = t[0], o = t[1], r = t[2], c = t[3], a = t[4], u = t[5], l = t[6], p = t[7], h = 0; h < i; h++) { if (h < 16) this.temp[h] = (255 & e[4 * h]) << 24 | (255 & e[4 * h + 1]) << 16 | (255 & e[4 * h + 2]) << 8 | 255 & e[4 * h + 3]; else { var d = this.temp[h - 2], f = (d >>> 17 | d << 15) ^ (d >>> 19 | d << 13) ^ d >>> 10, g = ((d = this.temp[h - 15]) >>> 7 | d << 25) ^ (d >>> 18 | d << 14) ^ d >>> 3; this.temp[h] = (f + this.temp[h - 7] | 0) + (g + this.temp[h - 16] | 0) } var m = (((a >>> 6 | a << 26) ^ (a >>> 11 | a << 21) ^ (a >>> 25 | a << 7)) + (a & u ^ ~a & l) | 0) + (p + (s[h] + this.temp[h] | 0) | 0) | 0, v = ((n >>> 2 | n << 30) ^ (n >>> 13 | n << 19) ^ (n >>> 22 | n << 10)) + (n & o ^ n & r ^ o & r) | 0; p = l, l = u, u = a, a = c + m | 0, c = r, r = o, o = n, n = m + v | 0 } t[0] += n, t[1] += o, t[2] += r, t[3] += c, t[4] += a, t[5] += u, t[6] += l, t[7] += p } }, { "./browserHashUtils": 11, "buffer/": 81 }], 16: [function (e, t, n) { (function (n) { (function () { var n = e("./util"); n.crypto.lib = e("./browserCryptoLib"), n.Buffer = e("buffer/").Buffer, n.url = e("url/"), n.querystring = e("querystring/"), n.realClock = e("./realclock/browserClock"), n.environment = "js", n.createEventStream = e("./event-stream/buffered-create-event-stream").createEventStream, n.isBrowser = function () { return !0 }, n.isNode = function () { return !1 }; var o = e("./core"); if (t.exports = o, e("./credentials"), e("./credentials/credential_provider_chain"), e("./credentials/temporary_credentials"), e("./credentials/chainable_temporary_credentials"), e("./credentials/web_identity_credentials"), e("./credentials/cognito_identity_credentials"), e("./credentials/saml_credentials"), o.XML.Parser = e("./xml/browser_parser"), e("./http/xhr"), void 0 === r) var r = { browser: !0 } }).call(this) }).call(this, e("_process")) }, { "./browserCryptoLib": 10, "./core": 18, "./credentials": 19, "./credentials/chainable_temporary_credentials": 20, "./credentials/cognito_identity_credentials": 21, "./credentials/credential_provider_chain": 22, "./credentials/saml_credentials": 23, "./credentials/temporary_credentials": 24, "./credentials/web_identity_credentials": 25, "./event-stream/buffered-create-event-stream": 27, "./http/xhr": 35, "./realclock/browserClock": 52, "./util": 71, "./xml/browser_parser": 72, _process: 86, "buffer/": 81, "querystring/": 92, "url/": 94 }], 17: [function (e, t, n) { var o, r = e("./core"); e("./credentials"), e("./credentials/credential_provider_chain"), r.Config = r.util.inherit({ constructor: function (e) { void 0 === e && (e = {}), e = this.extractCredentials(e), r.util.each.call(this, this.keys, (function (t, n) { this.set(t, e[t], n) })) }, getCredentials: function (e) { var t, n = this; function o(t) { e(t, t ? null : n.credentials) } function i(e, t) { return new r.util.error(t || new Error, { code: "CredentialsError", message: e, name: "CredentialsError" }) } n.credentials ? "function" == typeof n.credentials.get ? n.credentials.get((function (e) { e && (e = i("Could not load credentials from " + n.credentials.constructor.name, e)), o(e) })) : (t = null, n.credentials.accessKeyId && n.credentials.secretAccessKey || (t = i("Missing credentials")), o(t)) : n.credentialProvider ? n.credentialProvider.resolve((function (e, t) { e && (e = i("Could not load credentials from any providers", e)), n.credentials = t, o(e) })) : o(i("No credentials to load")) }, update: function (e, t) { t = t || !1, e = this.extractCredentials(e), r.util.each.call(this, e, (function (e, n) { (t || Object.prototype.hasOwnProperty.call(this.keys, e) || r.Service.hasService(e)) && this.set(e, n) })) }, loadFromPath: function (e) { this.clear(); var t = JSON.parse(r.util.readFileSync(e)), n = new r.FileSystemCredentials(e), o = new r.CredentialProviderChain; return o.providers.unshift(n), o.resolve((function (e, n) { if (e) throw e; t.credentials = n })), this.constructor(t), this }, clear: function () { r.util.each.call(this, this.keys, (function (e) { delete this[e] })), this.set("credentials", void 0), this.set("credentialProvider", void 0) }, set: function (e, t, n) { void 0 === t ? (void 0 === n && (n = this.keys[e]), this[e] = "function" == typeof n ? n.call(this) : n) : "httpOptions" === e && this[e] ? this[e] = r.util.merge(this[e], t) : this[e] = t }, keys: { credentials: null, credentialProvider: null, region: null, logger: null, apiVersions: {}, apiVersion: null, endpoint: void 0, httpOptions: { timeout: 12e4 }, maxRetries: void 0, maxRedirects: 10, paramValidation: !0, sslEnabled: !0, s3ForcePathStyle: !1, s3BucketEndpoint: !1, s3DisableBodySigning: !0, computeChecksums: !0, convertResponseTypes: !0, correctClockSkew: !1, customUserAgent: null, dynamoDbCrc32: !0, systemClockOffset: 0, signatureVersion: null, signatureCache: !0, retryDelayOptions: {}, useAccelerateEndpoint: !1, clientSideMonitoring: !1, endpointDiscoveryEnabled: !1, endpointCacheSize: 1e3, hostPrefixEnabled: !0, stsRegionalEndpoints: null }, extractCredentials: function (e) { return e.accessKeyId && e.secretAccessKey && ((e = r.util.copy(e)).credentials = new r.Credentials(e)), e }, setPromisesDependency: function (e) { o = e, null === e && "function" == typeof Promise && (o = Promise); var t = [r.Request, r.Credentials, r.CredentialProviderChain]; r.S3 && (t.push(r.S3), r.S3.ManagedUpload && t.push(r.S3.ManagedUpload)), r.util.addPromises(t, o) }, getPromisesDependency: function () { return o } }), r.config = new r.Config }, { "./core": 18, "./credentials": 19, "./credentials/credential_provider_chain": 22 }], 18: [function (e, t, n) { var o = { util: e("./util") }; ({}).toString(), t.exports = o, o.util.update(o, { VERSION: "2.553.0", Signers: {}, Protocol: { Json: e("./protocol/json"), Query: e("./protocol/query"), Rest: e("./protocol/rest"), RestJson: e("./protocol/rest_json"), RestXml: e("./protocol/rest_xml") }, XML: { Builder: e("./xml/builder"), Parser: null }, JSON: { Builder: e("./json/builder"), Parser: e("./json/parser") }, Model: { Api: e("./model/api"), Operation: e("./model/operation"), Shape: e("./model/shape"), Paginator: e("./model/paginator"), ResourceWaiter: e("./model/resource_waiter") }, apiLoader: e("./api_loader"), EndpointCache: e("../vendor/endpoint-cache").EndpointCache }), e("./sequential_executor"), e("./service"), e("./config"), e("./http"), e("./event_listeners"), e("./request"), e("./response"), e("./resource_waiter"), e("./signers/request_signer"), e("./param_validator"), o.events = new o.SequentialExecutor, o.util.memoizedProperty(o, "endpointCache", (function () { return new o.EndpointCache(o.config.endpointCacheSize) }), !0) }, { "../vendor/endpoint-cache": 103, "./api_loader": 9, "./config": 17, "./event_listeners": 33, "./http": 34, "./json/builder": 36, "./json/parser": 37, "./model/api": 38, "./model/operation": 40, "./model/paginator": 41, "./model/resource_waiter": 42, "./model/shape": 43, "./param_validator": 44, "./protocol/json": 46, "./protocol/query": 47, "./protocol/rest": 48, "./protocol/rest_json": 49, "./protocol/rest_xml": 50, "./request": 55, "./resource_waiter": 56, "./response": 57, "./sequential_executor": 58, "./service": 59, "./signers/request_signer": 63, "./util": 71, "./xml/builder": 73 }], 19: [function (e, t, n) { var o = e("./core"); o.Credentials = o.util.inherit({ constructor: function () { if (o.util.hideProperties(this, ["secretAccessKey"]), this.expired = !1, this.expireTime = null, this.refreshCallbacks = [], 1 === arguments.length && "object" === r(arguments[0])) { var e = arguments[0].credentials || arguments[0]; this.accessKeyId = e.accessKeyId, this.secretAccessKey = e.secretAccessKey, this.sessionToken = e.sessionToken } else this.accessKeyId = arguments[0], this.secretAccessKey = arguments[1], this.sessionToken = arguments[2] }, expiryWindow: 15, needsRefresh: function () { var e = o.util.date.getDate().getTime(), t = new Date(e + 1e3 * this.expiryWindow); return !!(this.expireTime && t > this.expireTime) || this.expired || !this.accessKeyId || !this.secretAccessKey }, get: function (e) { var t = this; this.needsRefresh() ? this.refresh((function (n) { n || (t.expired = !1), e && e(n) })) : e && e() }, refresh: function (e) { this.expired = !1, e() }, coalesceRefresh: function (e, t) { var n = this; 1 === n.refreshCallbacks.push(e) && n.load((function (e) { o.util.arrayEach(n.refreshCallbacks, (function (n) { t ? n(e) : o.util.defer((function () { n(e) })) })), n.refreshCallbacks.length = 0 })) }, load: function (e) { e() } }), o.Credentials.addPromisesToClass = function (e) { this.prototype.getPromise = o.util.promisifyMethod("get", e), this.prototype.refreshPromise = o.util.promisifyMethod("refresh", e) }, o.Credentials.deletePromisesFromClass = function () { delete this.prototype.getPromise, delete this.prototype.refreshPromise }, o.util.addPromises(o.Credentials) }, { "./core": 18 }], 20: [function (e, t, n) { var o = e("../core"), r = e("../../clients/sts"); o.ChainableTemporaryCredentials = o.util.inherit(o.Credentials, { constructor: function (e) { o.Credentials.call(this), e = e || {}, this.errorCode = "ChainableTemporaryCredentialsProviderFailure", this.expired = !0, this.tokenCodeFn = null; var t = o.util.copy(e.params) || {}; if (t.RoleArn && (t.RoleSessionName = t.RoleSessionName || "temporary-credentials"), t.SerialNumber) { if (!e.tokenCodeFn || "function" != typeof e.tokenCodeFn) throw new o.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"), { code: this.errorCode }); this.tokenCodeFn = e.tokenCodeFn } var n = o.util.merge({ params: t, credentials: e.masterCredentials || o.config.credentials }, e.stsConfig || {}); this.service = new r(n) }, refresh: function (e) { this.coalesceRefresh(e || o.util.fn.callback) }, load: function (e) { var t = this, n = t.service.config.params.RoleArn ? "assumeRole" : "getSessionToken"; this.getTokenCode((function (o, r) { var i = {}; o ? e(o) : (r && (i.TokenCode = r), t.service[n](i, (function (n, o) { n || t.service.credentialsFrom(o, t), e(n) }))) })) }, getTokenCode: function (e) { var t = this; this.tokenCodeFn ? this.tokenCodeFn(this.service.config.params.SerialNumber, (function (n, r) { if (n) { var i = n; return n instanceof Error && (i = n.message), void e(o.util.error(new Error("Error fetching MFA token: " + i), { code: t.errorCode })) } e(null, r) })) : e(null) } }) }, { "../../clients/sts": 8, "../core": 18 }], 21: [function (e, t, n) { var o = e("../core"), i = e("../../clients/cognitoidentity"), s = e("../../clients/sts"); o.CognitoIdentityCredentials = o.util.inherit(o.Credentials, { localStorageKey: { id: "aws.cognito.identity-id.", providers: "aws.cognito.identity-providers." }, constructor: function (e, t) { o.Credentials.call(this), this.expired = !0, this.params = e, this.data = null, this._identityId = null, this._clientConfig = o.util.copy(t || {}), this.loadCachedId(); var n = this; Object.defineProperty(this, "identityId", { get: function () { return n.loadCachedId(), n._identityId || n.params.IdentityId }, set: function (e) { n._identityId = e } }) }, refresh: function (e) { this.coalesceRefresh(e || o.util.fn.callback) }, load: function (e) { var t = this; t.createClients(), t.data = null, t._identityId = null, t.getId((function (n) { n ? (t.clearIdOnNotAuthorized(n), e(n)) : t.params.RoleArn ? t.getCredentialsFromSTS(e) : t.getCredentialsForIdentity(e) })) }, clearCachedId: function () { this._identityId = null, delete this.params.IdentityId; var e = this.params.IdentityPoolId, t = this.params.LoginId || ""; delete this.storage[this.localStorageKey.id + e + t], delete this.storage[this.localStorageKey.providers + e + t] }, clearIdOnNotAuthorized: function (e) { "NotAuthorizedException" == e.code && this.clearCachedId() }, getId: function (e) { var t = this; if ("string" == typeof t.params.IdentityId) return e(null, t.params.IdentityId); t.cognito.getId((function (n, o) { !n && o.IdentityId ? (t.params.IdentityId = o.IdentityId, e(null, o.IdentityId)) : e(n) })) }, loadCredentials: function (e, t) { e && t && (t.expired = !1, t.accessKeyId = e.Credentials.AccessKeyId, t.secretAccessKey = e.Credentials.SecretKey, t.sessionToken = e.Credentials.SessionToken, t.expireTime = e.Credentials.Expiration) }, getCredentialsForIdentity: function (e) { var t = this; t.cognito.getCredentialsForIdentity((function (n, o) { n ? t.clearIdOnNotAuthorized(n) : (t.cacheId(o), t.data = o, t.loadCredentials(t.data, t)), e(n) })) }, getCredentialsFromSTS: function (e) { var t = this; t.cognito.getOpenIdToken((function (n, o) { n ? (t.clearIdOnNotAuthorized(n), e(n)) : (t.cacheId(o), t.params.WebIdentityToken = o.Token, t.webIdentityCredentials.refresh((function (n) { n || (t.data = t.webIdentityCredentials.data, t.sts.credentialsFrom(t.data, t)), e(n) }))) })) }, loadCachedId: function () { var e = this; if (o.util.isBrowser() && !e.params.IdentityId) { var t = e.getStorage("id"); if (t && e.params.Logins) { var n = Object.keys(e.params.Logins); 0 !== (e.getStorage("providers") || "").split(",").filter((function (e) { return -1 !== n.indexOf(e) })).length && (e.params.IdentityId = t) } else t && (e.params.IdentityId = t) } }, createClients: function () { var e = this._clientConfig; if (this.webIdentityCredentials = this.webIdentityCredentials || new o.WebIdentityCredentials(this.params, e), !this.cognito) { var t = o.util.merge({}, e); t.params = this.params, this.cognito = new i(t) } this.sts = this.sts || new s(e) }, cacheId: function (e) { this._identityId = e.IdentityId, this.params.IdentityId = this._identityId, o.util.isBrowser() && (this.setStorage("id", e.IdentityId), this.params.Logins && this.setStorage("providers", Object.keys(this.params.Logins).join(","))) }, getStorage: function (e) { return this.storage[this.localStorageKey[e] + this.params.IdentityPoolId + (this.params.LoginId || "")] }, setStorage: function (e, t) { try { this.storage[this.localStorageKey[e] + this.params.IdentityPoolId + (this.params.LoginId || "")] = t } catch (e) { } }, storage: function () { try { var e = o.util.isBrowser() && null !== window.localStorage && "object" === r(window.localStorage) ? window.localStorage : {}; return e["aws.test-storage"] = "foobar", delete e["aws.test-storage"], e } catch (e) { return {} } }() }) }, { "../../clients/cognitoidentity": 7, "../../clients/sts": 8, "../core": 18 }], 22: [function (e, t, n) { var o = e("../core"); o.CredentialProviderChain = o.util.inherit(o.Credentials, { constructor: function (e) { this.providers = e || o.CredentialProviderChain.defaultProviders.slice(0), this.resolveCallbacks = [] }, resolve: function (e) { var t = this; if (0 === t.providers.length) return e(new Error("No providers")), t; if (1 === t.resolveCallbacks.push(e)) { var n = 0, r = t.providers.slice(0); !function e(i, s) { if (!i && s || n === r.length) return o.util.arrayEach(t.resolveCallbacks, (function (e) { e(i, s) })), void (t.resolveCallbacks.length = 0); var c = r[n++]; (s = "function" == typeof c ? c.call() : c).get ? s.get((function (t) { e(t, t ? null : s) })) : e(null, s) }() } return t } }), o.CredentialProviderChain.defaultProviders = [], o.CredentialProviderChain.addPromisesToClass = function (e) { this.prototype.resolvePromise = o.util.promisifyMethod("resolve", e) }, o.CredentialProviderChain.deletePromisesFromClass = function () { delete this.prototype.resolvePromise }, o.util.addPromises(o.CredentialProviderChain) }, { "../core": 18 }], 23: [function (e, t, n) { var o = e("../core"), r = e("../../clients/sts"); o.SAMLCredentials = o.util.inherit(o.Credentials, { constructor: function (e) { o.Credentials.call(this), this.expired = !0, this.params = e }, refresh: function (e) { this.coalesceRefresh(e || o.util.fn.callback) }, load: function (e) { var t = this; t.createClients(), t.service.assumeRoleWithSAML((function (n, o) { n || t.service.credentialsFrom(o, t), e(n) })) }, createClients: function () { this.service = this.service || new r({ params: this.params }) } }) }, { "../../clients/sts": 8, "../core": 18 }], 24: [function (e, t, n) { var o = e("../core"), r = e("../../clients/sts"); o.TemporaryCredentials = o.util.inherit(o.Credentials, { constructor: function (e, t) { o.Credentials.call(this), this.loadMasterCredentials(t), this.expired = !0, this.params = e || {}, this.params.RoleArn && (this.params.RoleSessionName = this.params.RoleSessionName || "temporary-credentials") }, refresh: function (e) { this.coalesceRefresh(e || o.util.fn.callback) }, load: function (e) { var t = this; t.createClients(), t.masterCredentials.get((function () { t.service.config.credentials = t.masterCredentials, (t.params.RoleArn ? t.service.assumeRole : t.service.getSessionToken).call(t.service, (function (n, o) { n || t.service.credentialsFrom(o, t), e(n) })) })) }, loadMasterCredentials: function (e) { for (this.masterCredentials = e || o.config.credentials; this.masterCredentials.masterCredentials;)this.masterCredentials = this.masterCredentials.masterCredentials; "function" != typeof this.masterCredentials.get && (this.masterCredentials = new o.Credentials(this.masterCredentials)) }, createClients: function () { this.service = this.service || new r({ params: this.params }) } }) }, { "../../clients/sts": 8, "../core": 18 }], 25: [function (e, t, n) { var o = e("../core"), r = e("../../clients/sts"); o.WebIdentityCredentials = o.util.inherit(o.Credentials, { constructor: function (e, t) { o.Credentials.call(this), this.expired = !0, this.params = e, this.params.RoleSessionName = this.params.RoleSessionName || "web-identity", this.data = null, this._clientConfig = o.util.copy(t || {}) }, refresh: function (e) { this.coalesceRefresh(e || o.util.fn.callback) }, load: function (e) { var t = this; t.createClients(), t.service.assumeRoleWithWebIdentity((function (n, o) { t.data = null, n || (t.data = o, t.service.credentialsFrom(o, t)), e(n) })) }, createClients: function () { if (!this.service) { var e = o.util.merge({}, this._clientConfig); e.params = this.params, this.service = new r(e) } } }) }, { "../../clients/sts": 8, "../core": 18 }], 26: [function (e, t, n) { (function (n) { (function () { var o = e("./core"), r = e("./util"), i = ["AWS_ENABLE_ENDPOINT_DISCOVERY", "AWS_ENDPOINT_DISCOVERY_ENABLED"]; function s(e) { var t = e.service, n = t.api || {}, o = (n.operations, {}); return t.config.region && (o.region = t.config.region), n.serviceId && (o.serviceId = n.serviceId), t.config.credentials.accessKeyId && (o.accessKeyId = t.config.credentials.accessKeyId), o } function c(e, t, n) { n && null != t && "structure" === n.type && n.required && n.required.length > 0 && r.arrayEach(n.required, (function (o) { var r = n.members[o]; if (!0 === r.endpointDiscoveryId) { var i = r.isLocationName ? r.name : o; e[i] = String(t[o]) } else c(e, t[o], r) })) } function a(e, t) { var n = {}; return c(n, e.params, t), n } function u(e) { var t = e.service, n = t.api, i = n.operations ? n.operations[e.operation] : void 0, c = a(e, i ? i.input : void 0), u = s(e); Object.keys(c).length > 0 && (u = r.update(u, c), i && (u.operation = i.name)); var l = o.endpointCache.get(u); if (!l || 1 !== l.length || "" !== l[0].Address) if (l && l.length > 0) e.httpRequest.updateEndpoint(l[0].Address); else { var p = t.makeRequest(n.endpointOperation, { Operation: i.name, Identifiers: c }); h(p), p.removeListener("validate", o.EventListeners.Core.VALIDATE_PARAMETERS), p.removeListener("retry", o.EventListeners.Core.RETRY_CHECK), o.endpointCache.put(u, [{ Address: "", CachePeriodInMinutes: 1 }]), p.send((function (e, t) { t && t.Endpoints ? o.endpointCache.put(u, t.Endpoints) : e && o.endpointCache.put(u, [{ Address: "", CachePeriodInMinutes: 1 }]) })) } } var l = {}; function p(e, t) { var n = e.service, i = n.api, c = i.operations ? i.operations[e.operation] : void 0, u = c ? c.input : void 0, p = a(e, u), d = s(e); Object.keys(p).length > 0 && (d = r.update(d, p), c && (d.operation = c.name)); var f = o.EndpointCache.getKeyString(d), g = o.endpointCache.get(f); if (g && 1 === g.length && "" === g[0].Address) return l[f] || (l[f] = []), void l[f].push({ request: e, callback: t }); if (g && g.length > 0) e.httpRequest.updateEndpoint(g[0].Address), t(); else { var m = n.makeRequest(i.endpointOperation, { Operation: c.name, Identifiers: p }); m.removeListener("validate", o.EventListeners.Core.VALIDATE_PARAMETERS), h(m), o.endpointCache.put(f, [{ Address: "", CachePeriodInMinutes: 60 }]), m.send((function (n, i) { if (n) { var s = { code: "EndpointDiscoveryException", message: "Request cannot be fulfilled without specifying an endpoint", retryable: !1 }; if (e.response.error = r.error(n, s), o.endpointCache.remove(d), l[f]) { var c = l[f]; r.arrayEach(c, (function (e) { e.request.response.error = r.error(n, s), e.callback() })), delete l[f] } } else i && (o.endpointCache.put(f, i.Endpoints), e.httpRequest.updateEndpoint(i.Endpoints[0].Address), l[f]) && (c = l[f], r.arrayEach(c, (function (e) { e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address), e.callback() })), delete l[f]); t() })) } } function h(e) { var t = e.service.api.apiVersion; t && !e.httpRequest.headers["x-amz-api-version"] && (e.httpRequest.headers["x-amz-api-version"] = t) } function d(e) { var t = e.error, n = e.httpResponse; if (t && ("InvalidEndpointException" === t.code || 421 === n.statusCode)) { var i = e.request, c = i.service.api.operations || {}, u = a(i, c[i.operation] ? c[i.operation].input : void 0), l = s(i); Object.keys(u).length > 0 && (l = r.update(l, u), c[i.operation] && (l.operation = c[i.operation].name)), o.endpointCache.remove(l) } } function f(e) { return ["false", "0"].indexOf(e) >= 0 } t.exports = { discoverEndpoint: function (e, t) { var s = e.service || {}; if (function (e) { if (e._originalConfig && e._originalConfig.endpoint && !0 === e._originalConfig.endpointDiscoveryEnabled) throw r.error(new Error, { code: "ConfigurationException", message: "Custom endpoint is supplied; endpointDiscoveryEnabled must not be true." }); var t = o.config[e.serviceIdentifier] || {}; return Boolean(o.config.endpoint || t.endpoint || e._originalConfig && e._originalConfig.endpoint) }(s) || e.isPresigned()) return t(); if (!function (e) { if (!0 === (e.service || {}).config.endpointDiscoveryEnabled) return !0; if (r.isBrowser()) return !1; for (var t = 0; t < i.length; t++) { var s = i[t]; if (Object.prototype.hasOwnProperty.call(n.env, s)) { if ("" === n.env[s] || void 0 === n.env[s]) throw r.error(new Error, { code: "ConfigurationException", message: "environmental variable " + s + " cannot be set to nothing" }); if (!f(n.env[s])) return !0 } } var c = {}; try { c = o.util.iniLoader ? o.util.iniLoader.loadFrom({ isConfig: !0, filename: n.env[o.util.sharedConfigFileEnv] }) : {} } catch (e) { } var a = c[n.env.AWS_PROFILE || o.util.defaultProfile] || {}; if (Object.prototype.hasOwnProperty.call(a, "endpoint_discovery_enabled")) { if (void 0 === a.endpoint_discovery_enabled) throw r.error(new Error, { code: "ConfigurationException", message: "config file entry 'endpoint_discovery_enabled' cannot be set to nothing" }); if (!f(a.endpoint_discovery_enabled)) return !0 } return !1 }(e)) return t(); e.httpRequest.appendToUserAgent("endpoint-discovery"); var c = (s.api.operations || {})[e.operation]; switch (c ? c.endpointDiscoveryRequired : "NULL") { case "OPTIONAL": u(e), e.addNamedListener("INVALIDATE_CACHED_ENDPOINTS", "extractError", d), t(); break; case "REQUIRED": e.addNamedListener("INVALIDATE_CACHED_ENDPOINTS", "extractError", d), p(e, t); break; default: t() } }, requiredDiscoverEndpoint: p, optionalDiscoverEndpoint: u, marshallCustomIdentifiers: a, getCacheKey: s, invalidateCachedEndpoint: d } }).call(this) }).call(this, e("_process")) }, { "./core": 18, "./util": 71, _process: 86 }], 27: [function (e, t, n) { var o = e("../event-stream/event-message-chunker").eventMessageChunker, r = e("./parse-event").parseEvent; t.exports = { createEventStream: function (e, t, n) { for (var i = o(e), s = [], c = 0; c < i.length; c++)s.push(r(t, i[c], n)); return s } } }, { "../event-stream/event-message-chunker": 28, "./parse-event": 30 }], 28: [function (e, t, n) { t.exports = { eventMessageChunker: function (e) { for (var t = [], n = 0; n < e.length;) { var o = e.readInt32BE(n), r = e.slice(n, o + n); n += o, t.push(r) } return t } } }, {}], 29: [function (e, t, n) { var o = e("../core").util, r = o.buffer.toBuffer; function i(e) { if (8 !== e.length) throw new Error("Int64 buffers must be exactly 8 bytes"); o.Buffer.isBuffer(e) || (e = r(e)), this.bytes = e } function s(e) { for (var t = 0; t < 8; t++)e[t] ^= 255; for (t = 7; t > -1 && (e[t]++, 0 === e[t]); t--); } i.fromNumber = function (e) { if (e > 0x8000000000000000 || e < -0x8000000000000000) throw new Error(e + " is too large (or, if negative, too small) to represent as an Int64"); for (var t = new Uint8Array(8), n = 7, o = Math.abs(Math.round(e)); n > -1 && o > 0; n--, o /= 256)t[n] = o; return e < 0 && s(t), new i(t) }, i.prototype.valueOf = function () { var e = this.bytes.slice(0), t = 128 & e[0]; return t && s(e), parseInt(e.toString("hex"), 16) * (t ? -1 : 1) }, i.prototype.toString = function () { return String(this.valueOf()) }, t.exports = { Int64: i } }, { "../core": 18 }], 30: [function (e, t, n) { var o = e("./parse-message").parseMessage; t.exports = { parseEvent: function (e, t, n) { var r = o(t), i = r.headers[":message-type"]; if (i) { if ("error" === i.value) throw function (e) { var t = e.headers[":error-code"], n = e.headers[":error-message"], o = new Error(n.value || n); return o.code = o.name = t.value || t, o }(r); if ("event" !== i.value) return } var s = r.headers[":event-type"], c = n.members[s.value]; if (c) { var a = {}, u = c.eventPayloadMemberName; if (u) { var l = c.members[u]; "binary" === l.type ? a[u] = r.body : a[u] = e.parse(r.body.toString(), l) } for (var p = c.eventHeaderMemberNames, h = 0; h < p.length; h++) { var d = p[h]; r.headers[d] && (a[d] = c.members[d].toType(r.headers[d].value)) } var f = {}; return f[s.value] = a, f } } } }, { "./parse-message": 31 }], 31: [function (e, t, n) { var o = e("./int64").Int64, r = e("./split-message").splitMessage, i = "boolean", s = "byte", c = "short", a = "integer", u = "long", l = "binary", p = "string", h = "timestamp", d = "uuid"; function f(e) { for (var t = {}, n = 0; n < e.length;) { var r = e.readUInt8(n++), f = e.slice(n, n + r).toString(); switch (n += r, e.readUInt8(n++)) { case 0: t[f] = { type: i, value: !0 }; break; case 1: t[f] = { type: i, value: !1 }; break; case 2: t[f] = { type: s, value: e.readInt8(n++) }; break; case 3: t[f] = { type: c, value: e.readInt16BE(n) }, n += 2; break; case 4: t[f] = { type: a, value: e.readInt32BE(n) }, n += 4; break; case 5: t[f] = { type: u, value: new o(e.slice(n, n + 8)) }, n += 8; break; case 6: var g = e.readUInt16BE(n); n += 2, t[f] = { type: l, value: e.slice(n, n + g) }, n += g; break; case 7: var m = e.readUInt16BE(n); n += 2, t[f] = { type: p, value: e.slice(n, n + m).toString() }, n += m; break; case 8: t[f] = { type: h, value: new Date(new o(e.slice(n, n + 8)).valueOf()) }, n += 8; break; case 9: var v = e.slice(n, n + 16).toString("hex"); n += 16, t[f] = { type: d, value: v.substr(0, 8) + "-" + v.substr(8, 4) + "-" + v.substr(12, 4) + "-" + v.substr(16, 4) + "-" + v.substr(20) }; break; default: throw new Error("Unrecognized header type tag") } } return t } t.exports = { parseMessage: function (e) { var t = r(e); return { headers: f(t.headers), body: t.body } } } }, { "./int64": 29, "./split-message": 32 }], 32: [function (e, t, n) { var o = e("../core").util, r = o.buffer.toBuffer; t.exports = { splitMessage: function (e) { if (o.Buffer.isBuffer(e) || (e = r(e)), e.length < 16) throw new Error("Provided message too short to accommodate event stream message overhead"); if (e.length !== e.readUInt32BE(0)) throw new Error("Reported message length does not match received message length"); var t = e.readUInt32BE(8); if (t !== o.crypto.crc32(e.slice(0, 8))) throw new Error("The prelude checksum specified in the message (" + t + ") does not match the calculated CRC32 checksum."); var n = e.readUInt32BE(e.length - 4); if (n !== o.crypto.crc32(e.slice(0, e.length - 4))) throw new Error("The message checksum did not match the expected value of " + n); var i = 12 + e.readUInt32BE(4); return { headers: e.slice(12, i), body: e.slice(i, e.length - 4) } } } }, { "../core": 18 }], 33: [function (e, t, n) { var o = e("./core"), r = e("./sequential_executor"), i = e("./discover_endpoint").discoverEndpoint; o.EventListeners = { Core: {} }, o.EventListeners = { Core: (new r).addNamedListeners((function (e, t) { t("VALIDATE_CREDENTIALS", "validate", (function (e, t) { if (!e.service.api.signatureVersion && !e.service.config.signatureVersion) return t(); e.service.config.getCredentials((function (n) { n && (e.response.error = o.util.error(n, { code: "CredentialsError", message: "Missing credentials in config" })), t() })) })), e("VALIDATE_REGION", "validate", (function (e) { e.service.config.region || e.service.isGlobalEndpoint || (e.response.error = o.util.error(new Error, { code: "ConfigError", message: "Missing region in config" })) })), e("BUILD_IDEMPOTENCY_TOKENS", "validate", (function (e) { if (e.service.api.operations) { var t = e.service.api.operations[e.operation]; if (t) { var n = t.idempotentMembers; if (n.length) { for (var r = o.util.copy(e.params), i = 0, s = n.length; i < s; i++)r[n[i]] || (r[n[i]] = o.util.uuid.v4()); e.params = r } } } })), e("VALIDATE_PARAMETERS", "validate", (function (e) { if (e.service.api.operations) { var t = e.service.api.operations[e.operation].input, n = e.service.config.paramValidation; new o.ParamValidator(n).validate(t, e.params) } })), t("COMPUTE_SHA256", "afterBuild", (function (e, t) { if (e.haltHandlersOnError(), e.service.api.operations) { var n = e.service.api.operations[e.operation], r = n ? n.authtype : ""; if (!e.service.api.signatureVersion && !r && !e.service.config.signatureVersion) return t(); if (e.service.getSignerClass(e) === o.Signers.V4) { var i = e.httpRequest.body || ""; if (r.indexOf("unsigned-body") >= 0) return e.httpRequest.headers["X-Amz-Content-Sha256"] = "UNSIGNED-PAYLOAD", t(); o.util.computeSha256(i, (function (n, o) { n ? t(n) : (e.httpRequest.headers["X-Amz-Content-Sha256"] = o, t()) })) } else t() } })), e("SET_CONTENT_LENGTH", "afterBuild", (function (e) { var t = function (e) { if (!e.service.api.operations) return ""; var t = e.service.api.operations[e.operation]; return t ? t.authtype : "" }(e), n = o.util.getRequestPayloadShape(e); if (void 0 === e.httpRequest.headers["Content-Length"]) try { var r = o.util.string.byteLength(e.httpRequest.body); e.httpRequest.headers["Content-Length"] = r } catch (o) { if (n && n.isStreaming) { if (n.requiresLength) throw o; if (t.indexOf("unsigned-body") >= 0) return void (e.httpRequest.headers["Transfer-Encoding"] = "chunked"); throw o } throw o } })), e("SET_HTTP_HOST", "afterBuild", (function (e) { e.httpRequest.headers.Host = e.httpRequest.endpoint.host })), e("RESTART", "restart", (function () { var e = this.response.error; e && e.retryable && (this.httpRequest = new o.HttpRequest(this.service.endpoint, this.service.region), this.response.retryCount < this.service.config.maxRetries ? this.response.retryCount++ : this.response.error = null) })), t("DISCOVER_ENDPOINT", "sign", i, !0), t("SIGN", "sign", (function (e, t) { var n = e.service, o = (e.service.api.operations || {})[e.operation], r = o ? o.authtype : ""; if (!n.api.signatureVersion && !r && !n.config.signatureVersion) return t(); n.config.getCredentials((function (r, i) { if (r) return e.response.error = r, t(); try { var s = n.getSkewCorrectedDate(), c = new (n.getSignerClass(e))(e.httpRequest, n.api.signingName || n.api.endpointPrefix, { signatureCache: n.config.signatureCache, operation: o, signatureVersion: n.api.signatureVersion }); c.setServiceClientId(n._clientId), delete e.httpRequest.headers.Authorization, delete e.httpRequest.headers.Date, delete e.httpRequest.headers["X-Amz-Date"], c.addAuthorization(i, s), e.signedAt = s } catch (t) { e.response.error = t } t() })) })), e("VALIDATE_RESPONSE", "validateResponse", (function (e) { this.service.successfulResponse(e, this) ? (e.data = {}, e.error = null) : (e.data = null, e.error = o.util.error(new Error, { code: "UnknownError", message: "An unknown error occurred." })) })), t("SEND", "send", (function (e, t) { function n(n) { e.httpResponse.stream = n; var r = e.request.httpRequest.stream, i = e.request.service, s = i.api, c = e.request.operation, a = s.operations[c] || {}; n.on("headers", (function (r, s, c) { if (e.request.emit("httpHeaders", [r, s, e, c]), !e.httpResponse.streaming) if (2 === o.HttpClient.streamsApiVersion) { if (a.hasEventOutput && i.successfulResponse(e)) return e.request.emit("httpDone"), void t(); n.on("readable", (function () { var t = n.read(); null !== t && e.request.emit("httpData", [t, e]) })) } else n.on("data", (function (t) { e.request.emit("httpData", [t, e]) })) })), n.on("end", (function () { if (!r || !r.didCallback) { if (2 === o.HttpClient.streamsApiVersion && a.hasEventOutput && i.successfulResponse(e)) return; e.request.emit("httpDone"), t() } })) } function r(n) { if ("RequestAbortedError" !== n.code) { var r = "TimeoutError" === n.code ? n.code : "NetworkingError"; n = o.util.error(n, { code: r, region: e.request.httpRequest.region, hostname: e.request.httpRequest.endpoint.hostname, retryable: !0 }) } e.error = n, e.request.emit("httpError", [e.error, e], (function () { t() })) } function i() { var t, i = o.HttpClient.getInstance(), s = e.request.service.config.httpOptions || {}; try { var c = i.handleRequest(e.request.httpRequest, s, n, r); (t = c).on("sendProgress", (function (t) { e.request.emit("httpUploadProgress", [t, e]) })), t.on("receiveProgress", (function (t) { e.request.emit("httpDownloadProgress", [t, e]) })) } catch (e) { r(e) } } e.httpResponse._abortCallback = t, e.error = null, e.data = null, (e.request.service.getSkewCorrectedDate() - this.signedAt) / 1e3 >= 600 ? this.emit("sign", [this], (function (e) { e ? t(e) : i() })) : i() })), e("HTTP_HEADERS", "httpHeaders", (function (e, t, n, r) { n.httpResponse.statusCode = e, n.httpResponse.statusMessage = r, n.httpResponse.headers = t, n.httpResponse.body = o.util.buffer.toBuffer(""), n.httpResponse.buffers = [], n.httpResponse.numBytes = 0; var i = t.date || t.Date, s = n.request.service; if (i) { var c = Date.parse(i); s.config.correctClockSkew && s.isClockSkewed(c) && s.applyClockOffset(c) } })), e("HTTP_DATA", "httpData", (function (e, t) { if (e) { if (o.util.isNode()) { t.httpResponse.numBytes += e.length; var n = t.httpResponse.headers["content-length"], r = { loaded: t.httpResponse.numBytes, total: n }; t.request.emit("httpDownloadProgress", [r, t]) } t.httpResponse.buffers.push(o.util.buffer.toBuffer(e)) } })), e("HTTP_DONE", "httpDone", (function (e) { if (e.httpResponse.buffers && e.httpResponse.buffers.length > 0) { var t = o.util.buffer.concat(e.httpResponse.buffers); e.httpResponse.body = t } delete e.httpResponse.numBytes, delete e.httpResponse.buffers })), e("FINALIZE_ERROR", "retry", (function (e) { e.httpResponse.statusCode && (e.error.statusCode = e.httpResponse.statusCode, void 0 === e.error.retryable && (e.error.retryable = this.service.retryableError(e.error, this))) })), e("INVALIDATE_CREDENTIALS", "retry", (function (e) { if (e.error) switch (e.error.code) { case "RequestExpired": case "ExpiredTokenException": case "ExpiredToken": e.error.retryable = !0, e.request.service.config.credentials.expired = !0 } })), e("EXPIRED_SIGNATURE", "retry", (function (e) { var t = e.error; t && "string" == typeof t.code && "string" == typeof t.message && t.code.match(/Signature/) && t.message.match(/expired/) && (e.error.retryable = !0) })), e("CLOCK_SKEWED", "retry", (function (e) { e.error && this.service.clockSkewError(e.error) && this.service.config.correctClockSkew && (e.error.retryable = !0) })), e("REDIRECT", "retry", (function (e) { e.error && e.error.statusCode >= 300 && e.error.statusCode < 400 && e.httpResponse.headers.location && (this.httpRequest.endpoint = new o.Endpoint(e.httpResponse.headers.location), this.httpRequest.headers.Host = this.httpRequest.endpoint.host, e.error.redirect = !0, e.error.retryable = !0) })), e("RETRY_CHECK", "retry", (function (e) { e.error && (e.error.redirect && e.redirectCount < e.maxRedirects ? e.error.retryDelay = 0 : e.retryCount < e.maxRetries && (e.error.retryDelay = this.service.retryDelays(e.retryCount) || 0)) })), t("RESET_RETRY_STATE", "afterRetry", (function (e, t) { var n, o = !1; e.error && (n = e.error.retryDelay || 0, e.error.retryable && e.retryCount < e.maxRetries ? (e.retryCount++, o = !0) : e.error.redirect && e.redirectCount < e.maxRedirects && (e.redirectCount++, o = !0)), o ? (e.error = null, setTimeout(t, n)) : t() })) })), CorePost: (new r).addNamedListeners((function (e) { e("EXTRACT_REQUEST_ID", "extractData", o.util.extractRequestId), e("EXTRACT_REQUEST_ID", "extractError", o.util.extractRequestId), e("ENOTFOUND_ERROR", "httpError", (function (e) { if ("NetworkingError" === e.code && "ENOTFOUND" === e.errno) { var t = "Inaccessible host: `" + e.hostname + "'. This service may not be available in the `" + e.region + "' region."; this.response.error = o.util.error(new Error(t), { code: "UnknownEndpoint", region: e.region, hostname: e.hostname, retryable: !0, originalError: e }) } })) })), Logger: (new r).addNamedListeners((function (t) { t("LOG_REQUEST", "complete", (function (t) { var n = t.request, r = n.service.config.logger; if (r) { var i = function () { var i = (t.request.service.getSkewCorrectedDate().getTime() - n.startTime.getTime()) / 1e3, c = !!r.isTTY, a = t.httpResponse.statusCode, u = n.params; n.service.api.operations && n.service.api.operations[n.operation] && n.service.api.operations[n.operation].input && (u = s(n.service.api.operations[n.operation].input, n.params)); var l = e("util").inspect(u, !0, null), p = ""; return c && (p += ""), p += "[AWS " + n.service.serviceIdentifier + " " + a, p += " " + i.toString() + "s " + t.retryCount + " retries]", c && (p += ""), p += " " + o.util.string.lowerFirst(n.operation), p += "(" + l + ")", c && (p += ""), p }(); "function" == typeof r.log ? r.log(i) : "function" == typeof r.write && r.write(i + "\n") } function s(e, t) { if (!t) return t; switch (e.type) { case "structure": var n = {}; return o.util.each(t, (function (t, o) { Object.prototype.hasOwnProperty.call(e.members, t) ? n[t] = s(e.members[t], o) : n[t] = o })), n; case "list": var r = []; return o.util.arrayEach(t, (function (t, n) { r.push(s(e.member, t)) })), r; case "map": var i = {}; return o.util.each(t, (function (t, n) { i[t] = s(e.value, n) })), i; default: return e.isSensitive ? "***SensitiveInformation***" : t } } })) })), Json: (new r).addNamedListeners((function (t) { var n = e("./protocol/json"); t("BUILD", "build", n.buildRequest), t("EXTRACT_DATA", "extractData", n.extractData), t("EXTRACT_ERROR", "extractError", n.extractError) })), Rest: (new r).addNamedListeners((function (t) { var n = e("./protocol/rest"); t("BUILD", "build", n.buildRequest), t("EXTRACT_DATA", "extractData", n.extractData), t("EXTRACT_ERROR", "extractError", n.extractError) })), RestJson: (new r).addNamedListeners((function (t) { var n = e("./protocol/rest_json"); t("BUILD", "build", n.buildRequest), t("EXTRACT_DATA", "extractData", n.extractData), t("EXTRACT_ERROR", "extractError", n.extractError) })), RestXml: (new r).addNamedListeners((function (t) { var n = e("./protocol/rest_xml"); t("BUILD", "build", n.buildRequest), t("EXTRACT_DATA", "extractData", n.extractData), t("EXTRACT_ERROR", "extractError", n.extractError) })), Query: (new r).addNamedListeners((function (t) { var n = e("./protocol/query"); t("BUILD", "build", n.buildRequest), t("EXTRACT_DATA", "extractData", n.extractData), t("EXTRACT_ERROR", "extractError", n.extractError) })) } }, { "./core": 18, "./discover_endpoint": 26, "./protocol/json": 46, "./protocol/query": 47, "./protocol/rest": 48, "./protocol/rest_json": 49, "./protocol/rest_xml": 50, "./sequential_executor": 58, util: 97 }], 34: [function (e, t, n) { var o = e("./core"), r = o.util.inherit; o.Endpoint = r({ constructor: function (e, t) { if (o.util.hideProperties(this, ["slashes", "auth", "hash", "search", "query"]), null == e) throw new Error("Invalid endpoint: " + e); if ("string" != typeof e) return o.util.copy(e); e.match(/^http/) || (e = ((t && void 0 !== t.sslEnabled ? t.sslEnabled : o.config.sslEnabled) ? "https" : "http") + "://" + e), o.util.update(this, o.util.urlParse(e)), this.port ? this.port = parseInt(this.port, 10) : this.port = "https:" === this.protocol ? 443 : 80 } }), o.HttpRequest = r({ constructor: function (e, t) { e = new o.Endpoint(e), this.method = "POST", this.path = e.path || "/", this.headers = {}, this.body = "", this.endpoint = e, this.region = t, this._userAgent = "", this.setUserAgent() }, setUserAgent: function () { this._userAgent = this.headers[this.getUserAgentHeaderName()] = o.util.userAgent() }, getUserAgentHeaderName: function () { return (o.util.isBrowser() ? "X-Amz-" : "") + "User-Agent" }, appendToUserAgent: function (e) { "string" == typeof e && e && (this._userAgent += " " + e), this.headers[this.getUserAgentHeaderName()] = this._userAgent }, getUserAgent: function () { return this._userAgent }, pathname: function () { return this.path.split("?", 1)[0] }, search: function () { var e = this.path.split("?", 2)[1]; return e ? (e = o.util.queryStringParse(e), o.util.queryParamsToString(e)) : "" }, updateEndpoint: function (e) { var t = new o.Endpoint(e); this.endpoint = t, this.path = t.path || "/" } }), o.HttpResponse = r({ constructor: function () { this.statusCode = void 0, this.headers = {}, this.body = void 0, this.streaming = !1, this.stream = null }, createUnbufferedStream: function () { return this.streaming = !0, this.stream } }), o.HttpClient = r({}), o.HttpClient.getInstance = function () { return void 0 === this.singleton && (this.singleton = new this), this.singleton } }, { "./core": 18 }], 35: [function (e, t, n) { var o = e("../core"), i = e("events").EventEmitter; e("../http"), o.XHRClient = o.util.inherit({ handleRequest: function (e, t, n, s) { var c = this, a = e.endpoint, u = new i, l = a.protocol + "//" + a.hostname; 80 !== a.port && 443 !== a.port && (l += ":" + a.port), l += e.path; var p = new XMLHttpRequest, h = !1; e.stream = p, p.addEventListener("readystatechange", (function () { try { if (0 === p.status) return } catch (e) { return } this.readyState >= this.HEADERS_RECEIVED && !h && (u.statusCode = p.status, u.headers = c.parseHeaders(p.getAllResponseHeaders()), u.emit("headers", u.statusCode, u.headers, p.statusText), h = !0), this.readyState === this.DONE && c.finishRequest(p, u) }), !1), p.upload.addEventListener("progress", (function (e) { u.emit("sendProgress", e) })), p.addEventListener("progress", (function (e) { u.emit("receiveProgress", e) }), !1), p.addEventListener("timeout", (function () { s(o.util.error(new Error("Timeout"), { code: "TimeoutError" })) }), !1), p.addEventListener("error", (function () { s(o.util.error(new Error("Network Failure"), { code: "NetworkingError" })) }), !1), p.addEventListener("abort", (function () { s(o.util.error(new Error("Request aborted"), { code: "RequestAbortedError" })) }), !1), n(u), p.open(e.method, l, !1 !== t.xhrAsync), o.util.each(e.headers, (function (e, t) { "Content-Length" !== e && "User-Agent" !== e && "Host" !== e && p.setRequestHeader(e, t) })), t.timeout && !1 !== t.xhrAsync && (p.timeout = t.timeout), t.xhrWithCredentials && (p.withCredentials = !0); try { p.responseType = "arraybuffer" } catch (e) { } try { e.body ? p.send(e.body) : p.send() } catch (t) { if (!e.body || "object" !== r(e.body.buffer)) throw t; p.send(e.body.buffer) } return u }, parseHeaders: function (e) { var t = {}; return o.util.arrayEach(e.split(/\r?\n/), (function (e) { var n = e.split(":", 1)[0], o = e.substring(n.length + 2); n.length > 0 && (t[n.toLowerCase()] = o) })), t }, finishRequest: function (e, t) { var n; if ("arraybuffer" === e.responseType && e.response) { var r = e.response; n = new o.util.Buffer(r.byteLength); for (var i = new Uint8Array(r), s = 0; s < n.length; ++s)n[s] = i[s] } try { n || "string" != typeof e.responseText || (n = new o.util.Buffer(e.responseText)) } catch (e) { } n && t.emit("data", n), t.emit("end") } }), o.HttpClient.prototype = o.XHRClient.prototype, o.HttpClient.streamsApiVersion = 1 }, { "../core": 18, "../http": 34, events: 82 }], 36: [function (e, t, n) { var o = e("../util"); function r() { } function i(e, t) { if (t && null != e) switch (t.type) { case "structure": return function (e, t) { var n = {}; return o.each(e, (function (e, o) { var r = t.members[e]; if (r) { if ("body" !== r.location) return; var s = r.isLocationName ? r.name : e, c = i(o, r); void 0 !== c && (n[s] = c) } })), n }(e, t); case "map": return function (e, t) { var n = {}; return o.each(e, (function (e, o) { var r = i(o, t.value); void 0 !== r && (n[e] = r) })), n }(e, t); case "list": return function (e, t) { var n = []; return o.arrayEach(e, (function (e) { var o = i(e, t.member); void 0 !== o && n.push(o) })), n }(e, t); default: return function (e, t) { return t.toWireFormat(e) }(e, t) } } r.prototype.build = function (e, t) { return JSON.stringify(i(e, t)) }, t.exports = r }, { "../util": 71 }], 37: [function (e, t, n) { var o = e("../util"); function r() { } function i(e, t) { if (t && void 0 !== e) switch (t.type) { case "structure": return function (e, t) { if (null != e) { var n = {}, r = t.members; return o.each(r, (function (t, o) { var r = o.isLocationName ? o.name : t; if (Object.prototype.hasOwnProperty.call(e, r)) { var s = i(e[r], o); void 0 !== s && (n[t] = s) } })), n } }(e, t); case "map": return function (e, t) { if (null != e) { var n = {}; return o.each(e, (function (e, o) { var r = i(o, t.value); n[e] = void 0 === r ? null : r })), n } }(e, t); case "list": return function (e, t) { if (null != e) { var n = []; return o.arrayEach(e, (function (e) { var o = i(e, t.member); void 0 === o ? n.push(null) : n.push(o) })), n } }(e, t); default: return function (e, t) { return t.toType(e) }(e, t) } } r.prototype.parse = function (e, t) { return i(JSON.parse(e), t) }, t.exports = r }, { "../util": 71 }], 38: [function (e, t, n) { var o = e("./collection"), r = e("./operation"), i = e("./shape"), s = e("./paginator"), c = e("./resource_waiter"), a = e("../util"), u = a.property, l = a.memoizedProperty; t.exports = function (e, t) { var n = this; e = e || {}, (t = t || {}).api = this, e.metadata = e.metadata || {}, u(this, "isApi", !0, !1), u(this, "apiVersion", e.metadata.apiVersion), u(this, "endpointPrefix", e.metadata.endpointPrefix), u(this, "signingName", e.metadata.signingName), u(this, "globalEndpoint", e.metadata.globalEndpoint), u(this, "signatureVersion", e.metadata.signatureVersion), u(this, "jsonVersion", e.metadata.jsonVersion), u(this, "targetPrefix", e.metadata.targetPrefix), u(this, "protocol", e.metadata.protocol), u(this, "timestampFormat", e.metadata.timestampFormat), u(this, "xmlNamespaceUri", e.metadata.xmlNamespace), u(this, "abbreviation", e.metadata.serviceAbbreviation), u(this, "fullName", e.metadata.serviceFullName), u(this, "serviceId", e.metadata.serviceId), l(this, "className", (function () { var t = e.metadata.serviceAbbreviation || e.metadata.serviceFullName; return t ? ("ElasticLoadBalancing" === (t = t.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, "")) && (t = "ELB"), t) : null })), u(this, "operations", new o(e.operations, t, (function (e, n) { return new r(e, n, t) }), a.string.lowerFirst, (function (e, t) { !0 === t.endpointoperation && u(n, "endpointOperation", a.string.lowerFirst(e)) }))), u(this, "shapes", new o(e.shapes, t, (function (e, n) { return i.create(n, t) }))), u(this, "paginators", new o(e.paginators, t, (function (e, n) { return new s(e, n, t) }))), u(this, "waiters", new o(e.waiters, t, (function (e, n) { return new c(e, n, t) }), a.string.lowerFirst)), t.documentation && (u(this, "documentation", e.documentation), u(this, "documentationUrl", e.documentationUrl)) } }, { "../util": 71, "./collection": 39, "./operation": 40, "./paginator": 41, "./resource_waiter": 42, "./shape": 43 }], 39: [function (e, t, n) { var o = e("../util").memoizedProperty; function r(e, t, n, r) { o(this, r(e), (function () { return n(e, t) })) } t.exports = function (e, t, n, o, i) { for (var s in o = o || String, e) Object.prototype.hasOwnProperty.call(e, s) && (r.call(this, s, e[s], n, o), i && i(s, e[s])) } }, { "../util": 71 }], 40: [function (e, t, n) { var o = e("./shape"), r = e("../util"), i = r.property, s = r.memoizedProperty; t.exports = function (e, t, n) { var r = this; n = n || {}, i(this, "name", t.name || e), i(this, "api", n.api, !1), t.http = t.http || {}, i(this, "endpoint", t.endpoint), i(this, "httpMethod", t.http.method || "POST"), i(this, "httpPath", t.http.requestUri || "/"), i(this, "authtype", t.authtype || ""), i(this, "endpointDiscoveryRequired", t.endpointdiscovery ? t.endpointdiscovery.required ? "REQUIRED" : "OPTIONAL" : "NULL"), s(this, "input", (function () { return t.input ? o.create(t.input, n) : new o.create({ type: "structure" }, n) })), s(this, "output", (function () { return t.output ? o.create(t.output, n) : new o.create({ type: "structure" }, n) })), s(this, "errors", (function () { var e = []; if (!t.errors) return null; for (var r = 0; r < t.errors.length; r++)e.push(o.create(t.errors[r], n)); return e })), s(this, "paginator", (function () { return n.api.paginators[e] })), n.documentation && (i(this, "documentation", t.documentation), i(this, "documentationUrl", t.documentationUrl)), s(this, "idempotentMembers", (function () { var e = [], t = r.input, n = t.members; if (!t.members) return e; for (var o in n) n.hasOwnProperty(o) && !0 === n[o].isIdempotent && e.push(o); return e })), s(this, "hasEventOutput", (function () { return function (e) { var t = e.members, n = e.payload; if (!e.members) return !1; if (n) return t[n].isEventStream; for (var o in t) if (!t.hasOwnProperty(o) && !0 === t[o].isEventStream) return !0; return !1 }(r.output) })) } }, { "../util": 71, "./shape": 43 }], 41: [function (e, t, n) { var o = e("../util").property; t.exports = function (e, t) { o(this, "inputToken", t.input_token), o(this, "limitKey", t.limit_key), o(this, "moreResults", t.more_results), o(this, "outputToken", t.output_token), o(this, "resultKey", t.result_key) } }, { "../util": 71 }], 42: [function (e, t, n) { var o = e("../util"), r = o.property; t.exports = function (e, t, n) { n = n || {}, r(this, "name", e), r(this, "api", n.api, !1), t.operation && r(this, "operation", o.string.lowerFirst(t.operation)); var i = this;["type", "description", "delay", "maxAttempts", "acceptors"].forEach((function (e) { var n = t[e]; n && r(i, e, n) })) } }, { "../util": 71 }], 43: [function (e, t, n) { var o = e("./collection"), i = e("../util"); function s(e, t, n) { null != n && i.property.apply(this, arguments) } function c(e, t) { e.constructor.prototype[t] || i.memoizedProperty.apply(this, arguments) } function a(e, t, n) { t = t || {}, s(this, "shape", e.shape), s(this, "api", t.api, !1), s(this, "type", e.type), s(this, "enum", e.enum), s(this, "min", e.min), s(this, "max", e.max), s(this, "pattern", e.pattern), s(this, "location", e.location || this.location || "body"), s(this, "name", this.name || e.xmlName || e.queryName || e.locationName || n), s(this, "isStreaming", e.streaming || this.isStreaming || !1), s(this, "requiresLength", e.requiresLength, !1), s(this, "isComposite", e.isComposite || !1), s(this, "isShape", !0, !1), s(this, "isQueryName", Boolean(e.queryName), !1), s(this, "isLocationName", Boolean(e.locationName), !1), s(this, "isIdempotent", !0 === e.idempotencyToken), s(this, "isJsonValue", !0 === e.jsonvalue), s(this, "isSensitive", !0 === e.sensitive || e.prototype && !0 === e.prototype.sensitive), s(this, "isEventStream", Boolean(e.eventstream), !1), s(this, "isEvent", Boolean(e.event), !1), s(this, "isEventPayload", Boolean(e.eventpayload), !1), s(this, "isEventHeader", Boolean(e.eventheader), !1), s(this, "isTimestampFormatSet", Boolean(e.timestampFormat) || e.prototype && !0 === e.prototype.isTimestampFormatSet, !1), s(this, "endpointDiscoveryId", Boolean(e.endpointdiscoveryid), !1), s(this, "hostLabel", Boolean(e.hostLabel), !1), t.documentation && (s(this, "documentation", e.documentation), s(this, "documentationUrl", e.documentationUrl)), e.xmlAttribute && s(this, "isXmlAttribute", e.xmlAttribute || !1), s(this, "defaultValue", null), this.toWireFormat = function (e) { return null == e ? "" : e }, this.toType = function (e) { return e } } function u(e) { a.apply(this, arguments), s(this, "isComposite", !0), e.flattened && s(this, "flattened", e.flattened || !1) } function l(e, t) { var n = this, i = null, l = !this.isShape; u.apply(this, arguments), l && (s(this, "defaultValue", (function () { return {} })), s(this, "members", {}), s(this, "memberNames", []), s(this, "required", []), s(this, "isRequired", (function () { return !1 }))), e.members && (s(this, "members", new o(e.members, t, (function (e, n) { return a.create(n, t, e) }))), c(this, "memberNames", (function () { return e.xmlOrder || Object.keys(e.members) })), e.event && (c(this, "eventPayloadMemberName", (function () { for (var e = n.members, t = n.memberNames, o = 0, r = t.length; o < r; o++)if (e[t[o]].isEventPayload) return t[o] })), c(this, "eventHeaderMemberNames", (function () { for (var e = n.members, t = n.memberNames, o = [], r = 0, i = t.length; r < i; r++)e[t[r]].isEventHeader && o.push(t[r]); return o })))), e.required && (s(this, "required", e.required), s(this, "isRequired", (function (t) { if (!i) { i = {}; for (var n = 0; n < e.required.length; n++)i[e.required[n]] = !0 } return i[t] }), !1, !0)), s(this, "resultWrapper", e.resultWrapper || null), e.payload && s(this, "payload", e.payload), "string" == typeof e.xmlNamespace ? s(this, "xmlNamespaceUri", e.xmlNamespace) : "object" === r(e.xmlNamespace) && (s(this, "xmlNamespacePrefix", e.xmlNamespace.prefix), s(this, "xmlNamespaceUri", e.xmlNamespace.uri)) } function p(e, t) { var n = this, o = !this.isShape; if (u.apply(this, arguments), o && s(this, "defaultValue", (function () { return [] })), e.member && c(this, "member", (function () { return a.create(e.member, t) })), this.flattened) { var r = this.name; c(this, "name", (function () { return n.member.name || r })) } } function h(e, t) { var n = !this.isShape; u.apply(this, arguments), n && (s(this, "defaultValue", (function () { return {} })), s(this, "key", a.create({ type: "string" }, t)), s(this, "value", a.create({ type: "string" }, t))), e.key && c(this, "key", (function () { return a.create(e.key, t) })), e.value && c(this, "value", (function () { return a.create(e.value, t) })) } function d() { a.apply(this, arguments); var e = ["rest-xml", "query", "ec2"]; this.toType = function (t) { return t = this.api && e.indexOf(this.api.protocol) > -1 ? t || "" : t, this.isJsonValue ? JSON.parse(t) : t && "function" == typeof t.toString ? t.toString() : t }, this.toWireFormat = function (e) { return this.isJsonValue ? JSON.stringify(e) : e } } function f() { a.apply(this, arguments), this.toType = function (e) { var t = i.base64.decode(e); if (this.isSensitive && i.isNode() && "function" == typeof i.Buffer.alloc) { var n = i.Buffer.alloc(t.length, t); t.fill(0), t = n } return t }, this.toWireFormat = i.base64.encode } function g() { f.apply(this, arguments) } function m() { a.apply(this, arguments), this.toType = function (e) { return "boolean" == typeof e ? e : null == e ? null : "true" === e } } a.normalizedTypes = { character: "string", double: "float", long: "integer", short: "integer", biginteger: "integer", bigdecimal: "float", blob: "binary" }, a.types = { structure: l, list: p, map: h, boolean: m, timestamp: function (e) { var t = this; if (a.apply(this, arguments), e.timestampFormat) s(this, "timestampFormat", e.timestampFormat); else if (t.isTimestampFormatSet && this.timestampFormat) s(this, "timestampFormat", this.timestampFormat); else if ("header" === this.location) s(this, "timestampFormat", "rfc822"); else if ("querystring" === this.location) s(this, "timestampFormat", "iso8601"); else if (this.api) switch (this.api.protocol) { case "json": case "rest-json": s(this, "timestampFormat", "unixTimestamp"); break; case "rest-xml": case "query": case "ec2": s(this, "timestampFormat", "iso8601") }this.toType = function (e) { return null == e ? null : "function" == typeof e.toUTCString ? e : "string" == typeof e || "number" == typeof e ? i.date.parseTimestamp(e) : null }, this.toWireFormat = function (e) { return i.date.format(e, t.timestampFormat) } }, float: function () { a.apply(this, arguments), this.toType = function (e) { return null == e ? null : parseFloat(e) }, this.toWireFormat = this.toType }, integer: function () { a.apply(this, arguments), this.toType = function (e) { return null == e ? null : parseInt(e, 10) }, this.toWireFormat = this.toType }, string: d, base64: g, binary: f }, a.resolve = function (e, t) { if (e.shape) { var n = t.api.shapes[e.shape]; if (!n) throw new Error("Cannot find shape reference: " + e.shape); return n } return null }, a.create = function (e, t, n) { if (e.isShape) return e; var o = a.resolve(e, t); if (o) { var r = Object.keys(e); t.documentation || (r = r.filter((function (e) { return !e.match(/documentation/) }))); var i = function () { o.constructor.call(this, e, t, n) }; return i.prototype = o, new i } e.type || (e.members ? e.type = "structure" : e.member ? e.type = "list" : e.key ? e.type = "map" : e.type = "string"); var s = e.type; if (a.normalizedTypes[e.type] && (e.type = a.normalizedTypes[e.type]), a.types[e.type]) return new a.types[e.type](e, t, n); throw new Error("Unrecognized shape type: " + s) }, a.shapes = { StructureShape: l, ListShape: p, MapShape: h, StringShape: d, BooleanShape: m, Base64Shape: g }, t.exports = a }, { "../util": 71, "./collection": 39 }], 44: [function (e, t, n) { var o = e("./core"); o.ParamValidator = o.util.inherit({ constructor: function (e) { !0 !== e && void 0 !== e || (e = { min: !0 }), this.validation = e }, validate: function (e, t, n) { if (this.errors = [], this.validateMember(e, t || {}, n || "params"), this.errors.length > 1) { var r = this.errors.join("\n* "); throw r = "There were " + this.errors.length + " validation errors:\n* " + r, o.util.error(new Error(r), { code: "MultipleValidationErrors", errors: this.errors }) } if (1 === this.errors.length) throw this.errors[0]; return !0 }, fail: function (e, t) { this.errors.push(o.util.error(new Error(t), { code: e })) }, validateStructure: function (e, t, n) { var o; this.validateType(t, n, ["object"], "structure"); for (var r = 0; e.required && r < e.required.length; r++) { var i = t[o = e.required[r]]; null == i && this.fail("MissingRequiredParameter", "Missing required key '" + o + "' in " + n) } for (o in t) if (Object.prototype.hasOwnProperty.call(t, o)) { var s = t[o], c = e.members[o]; if (void 0 !== c) { var a = [n, o].join("."); this.validateMember(c, s, a) } else this.fail("UnexpectedParameter", "Unexpected key '" + o + "' found in " + n) } return !0 }, validateMember: function (e, t, n) { switch (e.type) { case "structure": return this.validateStructure(e, t, n); case "list": return this.validateList(e, t, n); case "map": return this.validateMap(e, t, n); default: return this.validateScalar(e, t, n) } }, validateList: function (e, t, n) { if (this.validateType(t, n, [Array])) { this.validateRange(e, t.length, n, "list member count"); for (var o = 0; o < t.length; o++)this.validateMember(e.member, t[o], n + "[" + o + "]") } }, validateMap: function (e, t, n) { if (this.validateType(t, n, ["object"], "map")) { var o = 0; for (var r in t) Object.prototype.hasOwnProperty.call(t, r) && (this.validateMember(e.key, r, n + "[key='" + r + "']"), this.validateMember(e.value, t[r], n + "['" + r + "']"), o++); this.validateRange(e, o, n, "map member count") } }, validateScalar: function (e, t, n) { switch (e.type) { case null: case void 0: case "string": return this.validateString(e, t, n); case "base64": case "binary": return this.validatePayload(t, n); case "integer": case "float": return this.validateNumber(e, t, n); case "boolean": return this.validateType(t, n, ["boolean"]); case "timestamp": return this.validateType(t, n, [Date, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, "number"], "Date object, ISO-8601 string, or a UNIX timestamp"); default: return this.fail("UnkownType", "Unhandled type " + e.type + " for " + n) } }, validateString: function (e, t, n) { var o = ["string"]; e.isJsonValue && (o = o.concat(["number", "object", "boolean"])), null !== t && this.validateType(t, n, o) && (this.validateEnum(e, t, n), this.validateRange(e, t.length, n, "string length"), this.validatePattern(e, t, n), this.validateUri(e, t, n)) }, validateUri: function (e, t, n) { "uri" === e.location && 0 === t.length && this.fail("UriParameterError", 'Expected uri parameter to have length >= 1, but found "' + t + '" for ' + n) }, validatePattern: function (e, t, n) { this.validation.pattern && void 0 !== e.pattern && (new RegExp(e.pattern).test(t) || this.fail("PatternMatchError", 'Provided value "' + t + '" does not match regex pattern /' + e.pattern + "/ for " + n)) }, validateRange: function (e, t, n, o) { this.validation.min && void 0 !== e.min && t < e.min && this.fail("MinRangeError", "Expected " + o + " >= " + e.min + ", but found " + t + " for " + n), this.validation.max && void 0 !== e.max && t > e.max && this.fail("MaxRangeError", "Expected " + o + " <= " + e.max + ", but found " + t + " for " + n) }, validateEnum: function (e, t, n) { this.validation.enum && void 0 !== e.enum && -1 === e.enum.indexOf(t) && this.fail("EnumError", "Found string value of " + t + ", but expected " + e.enum.join("|") + " for " + n) }, validateType: function (e, t, n, i) { if (null == e) return !1; for (var s = !1, c = 0; c < n.length; c++) { if ("string" == typeof n[c]) { if (r(e) === n[c]) return !0 } else if (n[c] instanceof RegExp) { if ((e || "").toString().match(n[c])) return !0 } else { if (e instanceof n[c]) return !0; if (o.util.isType(e, n[c])) return !0; i || s || (n = n.slice()), n[c] = o.util.typeName(n[c]) } s = !0 } var a = i; a || (a = n.join(", ").replace(/,([^,]+)$/, ", or$1")); var u = a.match(/^[aeiou]/i) ? "n" : ""; return this.fail("InvalidParameterType", "Expected " + t + " to be a" + u + " " + a), !1 }, validateNumber: function (e, t, n) { if (null != t) { if ("string" == typeof t) { var o = parseFloat(t); o.toString() === t && (t = o) } this.validateType(t, n, ["number"]) && this.validateRange(e, t, n, "numeric value") } }, validatePayload: function (e, t) { if (null != e && "string" != typeof e && (!e || "number" != typeof e.byteLength)) { if (o.util.isNode()) { var n = o.util.stream.Stream; if (o.util.Buffer.isBuffer(e) || e instanceof n) return } else if (void 0 !== ("undefined" == typeof Blob ? "undefined" : r(Blob)) && e instanceof Blob) return; var i = ["Buffer", "Stream", "File", "Blob", "ArrayBuffer", "DataView"]; if (e) for (var s = 0; s < i.length; s++) { if (o.util.isType(e, i[s])) return; if (o.util.typeName(e.constructor) === i[s]) return } this.fail("InvalidParameterType", "Expected " + t + " to be a string, Buffer, Stream, Blob, or typed array object") } } }) }, { "./core": 18 }], 45: [function (e, t, n) { var o = e("../util"), r = e("../core"); t.exports = { populateHostPrefix: function (e) { if (!e.service.config.hostPrefixEnabled) return e; var t, n, i, s, c, a = e.service.api.operations[e.operation]; if (function (e) { var t = e.service.api, n = t.operations[e.operation], r = t.endpointOperation && t.endpointOperation === o.string.lowerFirst(n.name); return "NULL" !== n.endpointDiscoveryRequired || !0 === r }(e)) return e; if (a.endpoint && a.endpoint.hostPrefix) { var u = function (e, t, n) { return o.each(n.members, (function (n, r) { if (!0 === r.hostLabel) { if ("string" != typeof t[n] || "" === t[n]) throw o.error(new Error, { message: "Parameter " + n + " should be a non-empty string.", code: "InvalidParameter" }); var i = new RegExp("\\{" + n + "\\}", "g"); e = e.replace(i, t[n]) } })), e }(a.endpoint.hostPrefix, e.params, a.input); s = e.httpRequest.endpoint, c = u, s.host && (s.host = c + s.host), s.hostname && (s.hostname = c + s.hostname), t = e.httpRequest.endpoint.hostname, n = t.split("."), i = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/, o.arrayEach(n, (function (e) { if (!e.length || e.length < 1 || e.length > 63) throw o.error(new Error, { code: "ValidationError", message: "Hostname label length should be between 1 to 63 characters, inclusive." }); if (!i.test(e)) throw r.util.error(new Error, { code: "ValidationError", message: e + " is not hostname compatible." }) })) } return e } } }, { "../core": 18, "../util": 71 }], 46: [function (e, t, n) { var o = e("../util"), r = e("../json/builder"), i = e("../json/parser"), s = e("./helpers").populateHostPrefix; t.exports = { buildRequest: function (e) { var t = e.httpRequest, n = e.service.api, o = n.targetPrefix + "." + n.operations[e.operation].name, i = n.jsonVersion || "1.0", c = n.operations[e.operation].input, a = new r; 1 === i && (i = "1.0"), t.body = a.build(e.params || {}, c), t.headers["Content-Type"] = "application/x-amz-json-" + i, t.headers["X-Amz-Target"] = o, s(e) }, extractError: function (e) { var t = {}, n = e.httpResponse; if (t.code = n.headers["x-amzn-errortype"] || "UnknownError", "string" == typeof t.code && (t.code = t.code.split(":")[0]), n.body.length > 0) try { var r = JSON.parse(n.body.toString()); (r.__type || r.code) && (t.code = (r.__type || r.code).split("#").pop()), "RequestEntityTooLarge" === t.code ? t.message = "Request body must be less than 1 MB" : t.message = r.message || r.Message || null } catch (r) { t.statusCode = n.statusCode, t.message = n.statusMessage } else t.statusCode = n.statusCode, t.message = n.statusCode.toString(); e.error = o.error(new Error, t) }, extractData: function (e) { var t = e.httpResponse.body.toString() || "{}"; if (!1 === e.request.service.config.convertResponseTypes) e.data = JSON.parse(t); else { var n = e.request.service.api.operations[e.request.operation].output || {}, o = new i; e.data = o.parse(t, n) } } } }, { "../json/builder": 36, "../json/parser": 37, "../util": 71, "./helpers": 45 }], 47: [function (e, t, n) { var o = e("../core"), r = e("../util"), i = e("../query/query_param_serializer"), s = e("../model/shape"), c = e("./helpers").populateHostPrefix; t.exports = { buildRequest: function (e) { var t = e.service.api.operations[e.operation], n = e.httpRequest; n.headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8", n.params = { Version: e.service.api.apiVersion, Action: t.name }, (new i).serialize(e.params, t.input, (function (e, t) { n.params[e] = t })), n.body = r.queryParamsToString(n.params), c(e) }, extractError: function (e) { var t, n = e.httpResponse.body.toString(); if (n.match("= 0 ? "&" : "?"; var a = []; o.arrayEach(Object.keys(s).sort(), (function (e) { Array.isArray(s[e]) || (s[e] = [s[e]]); for (var t = 0; t < s[e].length; t++)a.push(o.uriEscape(String(e)) + "=" + s[e][t]) })), i += a.join("&") } return i } t.exports = { buildRequest: function (e) { !function (e) { e.httpRequest.method = e.service.api.operations[e.operation].httpMethod }(e), function (e) { var t = e.service.api.operations[e.operation], n = t.input, o = i(e.httpRequest.endpoint.path, t.httpPath, n, e.params); e.httpRequest.path = o }(e), function (e) { var t = e.service.api.operations[e.operation]; o.each(t.input.members, (function (t, n) { var r = e.params[t]; null != r && ("headers" === n.location && "map" === n.type ? o.each(r, (function (t, o) { e.httpRequest.headers[n.name + t] = o })) : "header" === n.location && (r = n.toWireFormat(r).toString(), n.isJsonValue && (r = o.base64.encode(r)), e.httpRequest.headers[n.name] = r)) })) }(e), r(e) }, extractError: function () { }, extractData: function (e) { var t = e.request, n = {}, r = e.httpResponse, i = t.service.api.operations[t.operation].output, s = {}; o.each(r.headers, (function (e, t) { s[e.toLowerCase()] = t })), o.each(i.members, (function (e, t) { var i = (t.name || e).toLowerCase(); if ("headers" === t.location && "map" === t.type) { n[e] = {}; var c = t.isLocationName ? t.name : "", a = new RegExp("^" + c + "(.+)", "i"); o.each(r.headers, (function (t, o) { var r = t.match(a); null !== r && (n[e][r[1]] = o) })) } else if ("header" === t.location) { if (void 0 !== s[i]) { var u = t.isJsonValue ? o.base64.decode(s[i]) : s[i]; n[e] = t.toType(u) } } else "statusCode" === t.location && (n[e] = parseInt(r.statusCode, 10)) })), e.data = n }, generateURI: i } }, { "../util": 71, "./helpers": 45 }], 49: [function (e, t, n) { var o = e("../util"), r = e("./rest"), i = e("./json"), s = e("../json/builder"), c = e("../json/parser"); function a(e, t) { if (e.service.api.operations[e.operation].input, !e.httpRequest.headers["Content-Type"]) { var n = t ? "binary/octet-stream" : "application/json"; e.httpRequest.headers["Content-Type"] = n } } t.exports = { buildRequest: function (e) { r.buildRequest(e), ["HEAD", "DELETE"].indexOf(e.httpRequest.method) < 0 && function (e) { var t = new s, n = e.service.api.operations[e.operation].input; if (n.payload) { var o, r = n.members[n.payload]; if (void 0 === (o = e.params[n.payload])) return; "structure" === r.type ? (e.httpRequest.body = t.build(o, r), a(e)) : (e.httpRequest.body = o, ("binary" === r.type || r.isStreaming) && a(e, !0)) } else { var i = t.build(e.params, n); "{}" === i && "GET" === e.httpRequest.method || (e.httpRequest.body = i), a(e) } }(e) }, extractError: function (e) { i.extractError(e) }, extractData: function (e) { r.extractData(e); var t = e.request, n = t.service.api.operations[t.operation], s = t.service.api.operations[t.operation].output || {}; if (n.hasEventOutput, s.payload) { var a = s.members[s.payload], u = e.httpResponse.body; if (a.isEventStream) l = new c, e.data[payload] = o.createEventStream(2 === AWS.HttpClient.streamsApiVersion ? e.httpResponse.stream : u, l, a); else if ("structure" === a.type || "list" === a.type) { var l = new c; e.data[s.payload] = l.parse(u, a) } else "binary" === a.type || a.isStreaming ? e.data[s.payload] = u : e.data[s.payload] = a.toType(u) } else { var p = e.data; i.extractData(e), e.data = o.merge(p, e.data) } } } }, { "../json/builder": 36, "../json/parser": 37, "../util": 71, "./json": 46, "./rest": 48 }], 50: [function (e, t, n) { var o = e("../core"), r = e("../util"), i = e("./rest"); t.exports = { buildRequest: function (e) { i.buildRequest(e), ["GET", "HEAD"].indexOf(e.httpRequest.method) < 0 && function (e) { var t = e.service.api.operations[e.operation].input, n = new o.XML.Builder, i = e.params, s = t.payload; if (s) { var c = t.members[s]; if (void 0 === (i = i[s])) return; if ("structure" === c.type) { var a = c.name; e.httpRequest.body = n.toXML(i, c, a, !0) } else e.httpRequest.body = i } else e.httpRequest.body = n.toXML(i, t, t.name || t.shape || r.string.upperFirst(e.operation) + "Request") }(e) }, extractError: function (e) { var t; i.extractError(e); try { t = (new o.XML.Parser).parse(e.httpResponse.body.toString()) } catch (n) { t = { Code: e.httpResponse.statusCode, Message: e.httpResponse.statusMessage } } t.Errors && (t = t.Errors), t.Error && (t = t.Error), t.Code ? e.error = r.error(new Error, { code: t.Code, message: t.Message }) : e.error = r.error(new Error, { code: e.httpResponse.statusCode, message: null }) }, extractData: function (e) { var t; i.extractData(e); var n = e.request, s = e.httpResponse.body, c = n.service.api.operations[n.operation], a = c.output, u = (c.hasEventOutput, a.payload); if (u) { var l = a.members[u]; l.isEventStream ? (t = new o.XML.Parser, e.data[u] = r.createEventStream(2 === o.HttpClient.streamsApiVersion ? e.httpResponse.stream : e.httpResponse.body, t, l)) : "structure" === l.type ? (t = new o.XML.Parser, e.data[u] = t.parse(s.toString(), l)) : "binary" === l.type || l.isStreaming ? e.data[u] = s : e.data[u] = l.toType(s) } else if (s.length > 0) { var p = (t = new o.XML.Parser).parse(s.toString(), a); r.update(e.data, p) } } } }, { "../core": 18, "../util": 71, "./rest": 48 }], 51: [function (e, t, n) { var o = e("../util"); function r() { } function i(e) { return e.isQueryName || "ec2" !== e.api.protocol ? e.name : e.name[0].toUpperCase() + e.name.substr(1) } function s(e, t, n, r) { o.each(n.members, (function (n, o) { var s = t[n]; if (null != s) { var a = i(o); c(a = e ? e + "." + a : a, s, o, r) } })) } function c(e, t, n, r) { null != t && ("structure" === n.type ? s(e, t, n, r) : "list" === n.type ? function (e, t, n, r) { var s = n.member || {}; 0 !== t.length ? o.arrayEach(t, (function (t, o) { var a = "." + (o + 1); if ("ec2" === n.api.protocol) a += ""; else if (n.flattened) { if (s.name) { var u = e.split("."); u.pop(), u.push(i(s)), e = u.join(".") } } else a = "." + (s.name ? s.name : "member") + a; c(e + a, t, s, r) })) : r.call(this, e, null) }(e, t, n, r) : "map" === n.type ? function (e, t, n, r) { var i = 1; o.each(t, (function (t, o) { var s = (n.flattened ? "." : ".entry.") + i++ + ".", a = s + (n.key.name || "key"), u = s + (n.value.name || "value"); c(e + a, t, n.key, r), c(e + u, o, n.value, r) })) }(e, t, n, r) : r(e, n.toWireFormat(t).toString())) } r.prototype.serialize = function (e, t, n) { s("", e, t, n) }, t.exports = r }, { "../util": 71 }], 52: [function (e, t, n) { t.exports = { now: function () { return "undefined" != typeof performance && "function" == typeof performance.now ? performance.now() : Date.now() } } }, {}], 53: [function (e, t, n) { var o = e("./util"), r = e("./region_config_data.json"); function i(e, t) { o.each(t, (function (t, n) { "globalEndpoint" !== t && (void 0 !== e.config[t] && null !== e.config[t] || (e.config[t] = n)) })) } t.exports = function (e) { for (var t = function (e) { var t = e.config.region, n = function (e) { if (!e) return null; var t = e.split("-"); return t.length < 3 ? null : t.slice(0, t.length - 2).join("-") + "-*" }(t), o = e.api.endpointPrefix; return [[t, o], [n, o], [t, "*"], [n, "*"], ["*", o], ["*", "*"]].map((function (e) { return e[0] && e[1] ? e.join("/") : null })) }(e), n = 0; n < t.length; n++) { var s = t[n]; if (s && Object.prototype.hasOwnProperty.call(r.rules, s)) { var c = r.rules[s]; return "string" == typeof c && (c = r.patterns[c]), e.config.useDualstack && o.isDualstackAvailable(e) && ((c = o.copy(c)).endpoint = "{service}.dualstack.{region}.amazonaws.com"), e.isGlobalEndpoint = !!c.globalEndpoint, c.signatureVersion || (c.signatureVersion = "v4"), void i(e, c) } } } }, { "./region_config_data.json": 54, "./util": 71 }], 54: [function (e, t, n) { t.exports = { rules: { "*/*": { endpoint: "{service}.{region}.amazonaws.com" }, "cn-*/*": { endpoint: "{service}.{region}.amazonaws.com.cn" }, "*/budgets": "globalSSL", "*/cloudfront": "globalSSL", "*/iam": "globalSSL", "*/sts": "globalSSL", "*/importexport": { endpoint: "{service}.amazonaws.com", signatureVersion: "v2", globalEndpoint: !0 }, "*/route53": { endpoint: "https://{service}.amazonaws.com", signatureVersion: "v3https", globalEndpoint: !0 }, "*/waf": "globalSSL", "us-gov-*/iam": "globalGovCloud", "us-gov-*/sts": { endpoint: "{service}.{region}.amazonaws.com" }, "us-gov-west-1/s3": "s3signature", "us-west-1/s3": "s3signature", "us-west-2/s3": "s3signature", "eu-west-1/s3": "s3signature", "ap-southeast-1/s3": "s3signature", "ap-southeast-2/s3": "s3signature", "ap-northeast-1/s3": "s3signature", "sa-east-1/s3": "s3signature", "us-east-1/s3": { endpoint: "{service}.amazonaws.com", signatureVersion: "s3" }, "us-east-1/sdb": { endpoint: "{service}.amazonaws.com", signatureVersion: "v2" }, "*/sdb": { endpoint: "{service}.{region}.amazonaws.com", signatureVersion: "v2" } }, patterns: { globalSSL: { endpoint: "https://{service}.amazonaws.com", globalEndpoint: !0 }, globalGovCloud: { endpoint: "{service}.us-gov.amazonaws.com" }, s3signature: { endpoint: "{service}.{region}.amazonaws.com", signatureVersion: "s3" } } } }, {}], 55: [function (e, t, n) { (function (t) { (function () { var n = e("./core"), o = e("./state_machine"), r = n.util.inherit, i = n.util.domain, s = e("jmespath"), c = { success: 1, error: 1, complete: 1 }, a = new o; a.setupStates = function () { var e = function (e, t) { var n = this; n._haltHandlersOnError = !1, n.emit(n._asm.currentState, (function (e) { if (e) if (o = n, Object.prototype.hasOwnProperty.call(c, o._asm.currentState)) { if (!(i && n.domain instanceof i.Domain)) throw e; e.domainEmitter = n, e.domain = n.domain, e.domainThrown = !1, n.domain.emit("error", e) } else n.response.error = e, t(e); else t(n.response.error); var o })) }; this.addState("validate", "build", "error", e), this.addState("build", "afterBuild", "restart", e), this.addState("afterBuild", "sign", "restart", e), this.addState("sign", "send", "retry", e), this.addState("retry", "afterRetry", "afterRetry", e), this.addState("afterRetry", "sign", "error", e), this.addState("send", "validateResponse", "retry", e), this.addState("validateResponse", "extractData", "extractError", e), this.addState("extractError", "extractData", "retry", e), this.addState("extractData", "success", "retry", e), this.addState("restart", "build", "error", e), this.addState("success", "complete", "complete", e), this.addState("error", "complete", "complete", e), this.addState("complete", null, null, e) }, a.setupStates(), n.Request = r({ constructor: function (e, t, r) { var s = e.endpoint, c = e.config.region, u = e.config.customUserAgent; e.isGlobalEndpoint && (c = "us-east-1"), this.domain = i && i.active, this.service = e, this.operation = t, this.params = r || {}, this.httpRequest = new n.HttpRequest(s, c), this.httpRequest.appendToUserAgent(u), this.startTime = e.getSkewCorrectedDate(), this.response = new n.Response(this), this._asm = new o(a.states, "validate"), this._haltHandlersOnError = !1, n.SequentialExecutor.call(this), this.emit = this.emitEvent }, send: function (e) { return e && (this.httpRequest.appendToUserAgent("callback"), this.on("complete", (function (t) { e.call(t, t.error, t.data) }))), this.runTo(), this.response }, build: function (e) { return this.runTo("send", e) }, runTo: function (e, t) { return this._asm.runTo(e, t, this), this }, abort: function () { return this.removeAllListeners("validateResponse"), this.removeAllListeners("extractError"), this.on("validateResponse", (function (e) { e.error = n.util.error(new Error("Request aborted by user"), { code: "RequestAbortedError", retryable: !1 }) })), this.httpRequest.stream && !this.httpRequest.stream.didCallback && (this.httpRequest.stream.abort(), this.httpRequest._abortCallback ? this.httpRequest._abortCallback() : this.removeAllListeners("send")), this }, eachPage: function (e) { e = n.util.fn.makeAsync(e, 3), this.on("complete", (function t(o) { e.call(o, o.error, o.data, (function (r) { !1 !== r && (o.hasNextPage() ? o.nextPage().on("complete", t).send() : e.call(o, null, null, n.util.fn.noop)) })) })).send() }, eachItem: function (e) { var t = this; this.eachPage((function (o, r) { if (o) return e(o, null); if (null === r) return e(null, null); var i = t.service.paginationConfig(t.operation).resultKey; Array.isArray(i) && (i = i[0]); var c = s.search(r, i), a = !0; return n.util.arrayEach(c, (function (t) { if (!1 === (a = e(null, t))) return n.util.abort })), a })) }, isPageable: function () { return !!this.service.paginationConfig(this.operation) }, createReadStream: function () { var e = n.util.stream, o = this, r = null; return 2 === n.HttpClient.streamsApiVersion ? (r = new e.PassThrough, t.nextTick((function () { o.send() }))) : ((r = new e.Stream).readable = !0, r.sent = !1, r.on("newListener", (function (e) { r.sent || "data" !== e || (r.sent = !0, t.nextTick((function () { o.send() }))) }))), this.on("error", (function (e) { r.emit("error", e) })), this.on("httpHeaders", (function (t, i, s) { if (t < 300) { o.removeListener("httpData", n.EventListeners.Core.HTTP_DATA), o.removeListener("httpError", n.EventListeners.Core.HTTP_ERROR), o.on("httpError", (function (e) { s.error = e, s.error.retryable = !1 })); var c, a = !1; if ("HEAD" !== o.httpRequest.method && (c = parseInt(i["content-length"], 10)), void 0 !== c && !isNaN(c) && c >= 0) { a = !0; var u = 0 } var l = function () { a && u !== c ? r.emit("error", n.util.error(new Error("Stream content length mismatch. Received " + u + " of " + c + " bytes."), { code: "StreamContentLengthMismatch" })) : 2 === n.HttpClient.streamsApiVersion ? r.end() : r.emit("end") }, p = s.httpResponse.createUnbufferedStream(); if (2 === n.HttpClient.streamsApiVersion) if (a) { var h = new e.PassThrough; h._write = function (t) { return t && t.length && (u += t.length), e.PassThrough.prototype._write.apply(this, arguments) }, h.on("end", l), r.on("error", (function (e) { a = !1, p.unpipe(h), h.emit("end"), h.end() })), p.pipe(h).pipe(r, { end: !1 }) } else p.pipe(r); else a && p.on("data", (function (e) { e && e.length && (u += e.length) })), p.on("data", (function (e) { r.emit("data", e) })), p.on("end", l); p.on("error", (function (e) { a = !1, r.emit("error", e) })) } })), r }, emitEvent: function (e, t, o) { "function" == typeof t && (o = t, t = null), o || (o = function () { }), t || (t = this.eventParameters(e, this.response)), n.SequentialExecutor.prototype.emit.call(this, e, t, (function (e) { e && (this.response.error = e), o.call(this, e) })) }, eventParameters: function (e) { switch (e) { case "restart": case "validate": case "sign": case "build": case "afterValidate": case "afterBuild": return [this]; case "error": return [this.response.error, this.response]; default: return [this.response] } }, presign: function (e, t) { return t || "function" != typeof e || (t = e, e = null), (new n.Signers.Presign).sign(this.toGet(), e, t) }, isPresigned: function () { return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, "presigned-expires") }, toUnauthenticated: function () { return this._unAuthenticated = !0, this.removeListener("validate", n.EventListeners.Core.VALIDATE_CREDENTIALS), this.removeListener("sign", n.EventListeners.Core.SIGN), this }, toGet: function () { return "query" !== this.service.api.protocol && "ec2" !== this.service.api.protocol || (this.removeListener("build", this.buildAsGet), this.addListener("build", this.buildAsGet)), this }, buildAsGet: function (e) { e.httpRequest.method = "GET", e.httpRequest.path = e.service.endpoint.path + "?" + e.httpRequest.body, e.httpRequest.body = "", delete e.httpRequest.headers["Content-Length"], delete e.httpRequest.headers["Content-Type"] }, haltHandlersOnError: function () { this._haltHandlersOnError = !0 } }), n.Request.addPromisesToClass = function (e) { this.prototype.promise = function () { var t = this; return this.httpRequest.appendToUserAgent("promise"), new e((function (e, n) { t.on("complete", (function (t) { t.error ? n(t.error) : e(Object.defineProperty(t.data || {}, "$response", { value: t })) })), t.runTo() })) } }, n.Request.deletePromisesFromClass = function () { delete this.prototype.promise }, n.util.addPromises(n.Request), n.util.mixin(n.Request, n.SequentialExecutor) }).call(this) }).call(this, e("_process")) }, { "./core": 18, "./state_machine": 70, _process: 86, jmespath: 85 }], 56: [function (e, t, n) { var o = e("./core"), r = o.util.inherit, i = e("jmespath"); function s(e) { var t = e.request._waiter, n = t.config.acceptors, o = !1, r = "retry"; n.forEach((function (n) { if (!o) { var i = t.matchers[n.matcher]; i && i(e, n.expected, n.argument) && (o = !0, r = n.state) } })), !o && e.error && (r = "failure"), "success" === r ? t.setSuccess(e) : t.setError(e, "retry" === r) } o.ResourceWaiter = r({ constructor: function (e, t) { this.service = e, this.state = t, this.loadWaiterConfig(this.state) }, service: null, state: null, config: null, matchers: { path: function (e, t, n) { try { var o = i.search(e.data, n) } catch (e) { return !1 } return i.strictDeepEqual(o, t) }, pathAll: function (e, t, n) { try { var o = i.search(e.data, n) } catch (e) { return !1 } Array.isArray(o) || (o = [o]); var r = o.length; if (!r) return !1; for (var s = 0; s < r; s++)if (!i.strictDeepEqual(o[s], t)) return !1; return !0 }, pathAny: function (e, t, n) { try { var o = i.search(e.data, n) } catch (e) { return !1 } Array.isArray(o) || (o = [o]); for (var r = o.length, s = 0; s < r; s++)if (i.strictDeepEqual(o[s], t)) return !0; return !1 }, status: function (e, t) { var n = e.httpResponse.statusCode; return "number" == typeof n && n === t }, error: function (e, t) { return "string" == typeof t && e.error ? t === e.error.code : t === !!e.error } }, listeners: (new o.SequentialExecutor).addNamedListeners((function (e) { e("RETRY_CHECK", "retry", (function (e) { var t = e.request._waiter; e.error && "ResourceNotReady" === e.error.code && (e.error.retryDelay = 1e3 * (t.config.delay || 0)) })), e("CHECK_OUTPUT", "extractData", s), e("CHECK_ERROR", "extractError", s) })), wait: function (e, t) { "function" == typeof e && (t = e, e = void 0), e && e.$waiter && ("number" == typeof (e = o.util.copy(e)).$waiter.delay && (this.config.delay = e.$waiter.delay), "number" == typeof e.$waiter.maxAttempts && (this.config.maxAttempts = e.$waiter.maxAttempts), delete e.$waiter); var n = this.service.makeRequest(this.config.operation, e); return n._waiter = this, n.response.maxRetries = this.config.maxAttempts, n.addListeners(this.listeners), t && n.send(t), n }, setSuccess: function (e) { e.error = null, e.data = e.data || {}, e.request.removeAllListeners("extractData") }, setError: function (e, t) { e.data = null, e.error = o.util.error(e.error || new Error, { code: "ResourceNotReady", message: "Resource is not in the state " + this.state, retryable: t }) }, loadWaiterConfig: function (e) { if (!this.service.api.waiters[e]) throw new o.util.error(new Error, { code: "StateNotFoundError", message: "State " + e + " not found." }); this.config = o.util.copy(this.service.api.waiters[e]) } }) }, { "./core": 18, jmespath: 85 }], 57: [function (e, t, n) { var o = e("./core"), r = o.util.inherit, i = e("jmespath"); o.Response = r({ constructor: function (e) { this.request = e, this.data = null, this.error = null, this.retryCount = 0, this.redirectCount = 0, this.httpResponse = new o.HttpResponse, e && (this.maxRetries = e.service.numRetries(), this.maxRedirects = e.service.config.maxRedirects) }, nextPage: function (e) { var t, n = this.request.service, r = this.request.operation; try { t = n.paginationConfig(r, !0) } catch (e) { this.error = e } if (!this.hasNextPage()) { if (e) e(this.error, null); else if (this.error) throw this.error; return null } var i = o.util.copy(this.request.params); if (this.nextPageTokens) { var s = t.inputToken; "string" == typeof s && (s = [s]); for (var c = 0; c < s.length; c++)i[s[c]] = this.nextPageTokens[c]; return n.makeRequest(this.request.operation, i, e) } return e ? e(null, null) : null }, hasNextPage: function () { return this.cacheNextPageTokens(), !!this.nextPageTokens || void 0 === this.nextPageTokens && void 0 }, cacheNextPageTokens: function () { if (Object.prototype.hasOwnProperty.call(this, "nextPageTokens")) return this.nextPageTokens; this.nextPageTokens = void 0; var e = this.request.service.paginationConfig(this.request.operation); if (!e) return this.nextPageTokens; if (this.nextPageTokens = null, e.moreResults && !i.search(this.data, e.moreResults)) return this.nextPageTokens; var t = e.outputToken; return "string" == typeof t && (t = [t]), o.util.arrayEach.call(this, t, (function (e) { var t = i.search(this.data, e); t && (this.nextPageTokens = this.nextPageTokens || [], this.nextPageTokens.push(t)) })), this.nextPageTokens } }) }, { "./core": 18, jmespath: 85 }], 58: [function (e, t, n) { var o = e("./core"); o.SequentialExecutor = o.util.inherit({ constructor: function () { this._events = {} }, listeners: function (e) { return this._events[e] ? this._events[e].slice(0) : [] }, on: function (e, t, n) { return this._events[e] ? n ? this._events[e].unshift(t) : this._events[e].push(t) : this._events[e] = [t], this }, onAsync: function (e, t, n) { return t._isAsync = !0, this.on(e, t, n) }, removeListener: function (e, t) { var n = this._events[e]; if (n) { for (var o = n.length, r = -1, i = 0; i < o; ++i)n[i] === t && (r = i); r > -1 && n.splice(r, 1) } return this }, removeAllListeners: function (e) { return e ? delete this._events[e] : this._events = {}, this }, emit: function (e, t, n) { n || (n = function () { }); var o = this.listeners(e), r = o.length; return this.callListeners(o, t, n), r > 0 }, callListeners: function (e, t, n, r) { var i = this, s = r || null; function c(r) { if (r && (s = o.util.error(s || new Error, r), i._haltHandlersOnError)) return n.call(i, s); i.callListeners(e, t, n, s) } for (; e.length > 0;) { var a = e.shift(); if (a._isAsync) return void a.apply(i, t.concat([c])); try { a.apply(i, t) } catch (e) { s = o.util.error(s || new Error, e) } if (s && i._haltHandlersOnError) return void n.call(i, s) } n.call(i, s) }, addListeners: function (e) { var t = this; return e._events && (e = e._events), o.util.each(e, (function (e, n) { "function" == typeof n && (n = [n]), o.util.arrayEach(n, (function (n) { t.on(e, n) })) })), t }, addNamedListener: function (e, t, n, o) { return this[e] = n, this.addListener(t, n, o), this }, addNamedAsyncListener: function (e, t, n, o) { return n._isAsync = !0, this.addNamedListener(e, t, n, o) }, addNamedListeners: function (e) { var t = this; return e((function () { t.addNamedListener.apply(t, arguments) }), (function () { t.addNamedAsyncListener.apply(t, arguments) })), this } }), o.SequentialExecutor.prototype.addListener = o.SequentialExecutor.prototype.on, t.exports = o.SequentialExecutor }, { "./core": 18 }], 59: [function (e, t, n) { (function (n) { (function () { var o = e("./core"), i = e("./model/api"), s = e("./region_config"), c = o.util.inherit, a = 0; o.Service = c({ constructor: function (e) { if (!this.loadServiceClass) throw o.util.error(new Error, "Service must be constructed with `new' operator"); var t = this.loadServiceClass(e || {}); if (t) { var n = o.util.copy(e), r = new t(e); return Object.defineProperty(r, "_originalConfig", { get: function () { return n }, enumerable: !1, configurable: !0 }), r._clientId = ++a, r } this.initialize(e) }, initialize: function (e) { var t = o.config[this.serviceIdentifier]; if (this.config = new o.Config(o.config), t && this.config.update(t, !0), e && this.config.update(e, !0), this.validateService(), this.config.endpoint || s(this), this.config.endpoint = this.endpointFromTemplate(this.config.endpoint), this.setEndpoint(this.config.endpoint), o.SequentialExecutor.call(this), o.Service.addDefaultMonitoringListeners(this), (this.config.clientSideMonitoring || o.Service._clientSideMonitoring) && this.publisher) { var r = this.publisher; this.addNamedListener("PUBLISH_API_CALL", "apiCall", (function (e) { n.nextTick((function () { r.eventHandler(e) })) })), this.addNamedListener("PUBLISH_API_ATTEMPT", "apiCallAttempt", (function (e) { n.nextTick((function () { r.eventHandler(e) })) })) } }, validateService: function () { }, loadServiceClass: function (e) { var t = e; if (o.util.isEmpty(this.api)) { if (t.apiConfig) return o.Service.defineServiceApi(this.constructor, t.apiConfig); if (this.constructor.services) { (t = new o.Config(o.config)).update(e, !0); var n = t.apiVersions[this.constructor.serviceIdentifier]; return n = n || t.apiVersion, this.getLatestServiceClass(n) } return null } return null }, getLatestServiceClass: function (e) { return e = this.getLatestServiceVersion(e), null === this.constructor.services[e] && o.Service.defineServiceApi(this.constructor, e), this.constructor.services[e] }, getLatestServiceVersion: function (e) { if (!this.constructor.services || 0 === this.constructor.services.length) throw new Error("No services defined on " + this.constructor.serviceIdentifier); if (e ? o.util.isType(e, Date) && (e = o.util.date.iso8601(e).split("T")[0]) : e = "latest", Object.hasOwnProperty(this.constructor.services, e)) return e; for (var t = Object.keys(this.constructor.services).sort(), n = null, r = t.length - 1; r >= 0; r--)if ("*" !== t[r][t[r].length - 1] && (n = t[r]), t[r].substr(0, 10) <= e) return n; throw new Error("Could not find " + this.constructor.serviceIdentifier + " API to satisfy version constraint `" + e + "'") }, api: {}, defaultRetryCount: 3, customizeRequests: function (e) { if (e) { if ("function" != typeof e) throw new Error("Invalid callback type '" + r(e) + "' provided in customizeRequests"); this.customRequestHandler = e } else this.customRequestHandler = null }, makeRequest: function (e, t, n) { if ("function" == typeof t && (n = t, t = null), t = t || {}, this.config.params) { var r = this.api.operations[e]; r && (t = o.util.copy(t), o.util.each(this.config.params, (function (e, n) { r.input.members[e] && (void 0 !== t[e] && null !== t[e] || (t[e] = n)) }))) } var i = new o.Request(this, e, t); return this.addAllRequestListeners(i), this.attachMonitoringEmitter(i), n && i.send(n), i }, makeUnauthenticatedRequest: function (e, t, n) { "function" == typeof t && (n = t, t = {}); var o = this.makeRequest(e, t).toUnauthenticated(); return n ? o.send(n) : o }, waitFor: function (e, t, n) { return new o.ResourceWaiter(this, e).wait(t, n) }, addAllRequestListeners: function (e) { for (var t = [o.events, o.EventListeners.Core, this.serviceInterface(), o.EventListeners.CorePost], n = 0; n < t.length; n++)t[n] && e.addListeners(t[n]); this.config.paramValidation || e.removeListener("validate", o.EventListeners.Core.VALIDATE_PARAMETERS), this.config.logger && e.addListeners(o.EventListeners.Logger), this.setupRequestListeners(e), "function" == typeof this.constructor.prototype.customRequestHandler && this.constructor.prototype.customRequestHandler(e), Object.prototype.hasOwnProperty.call(this, "customRequestHandler") && "function" == typeof this.customRequestHandler && this.customRequestHandler(e) }, apiCallEvent: function (e) { var t = e.service.api.operations[e.operation], n = { Type: "ApiCall", Api: t ? t.name : e.operation, Version: 1, Service: e.service.api.serviceId || e.service.api.endpointPrefix, Region: e.httpRequest.region, MaxRetriesExceeded: 0, UserAgent: e.httpRequest.getUserAgent() }, o = e.response; if (o.httpResponse.statusCode && (n.FinalHttpStatusCode = o.httpResponse.statusCode), o.error) { var r = o.error; o.httpResponse.statusCode > 299 ? (r.code && (n.FinalAwsException = r.code), r.message && (n.FinalAwsExceptionMessage = r.message)) : ((r.code || r.name) && (n.FinalSdkException = r.code || r.name), r.message && (n.FinalSdkExceptionMessage = r.message)) } return n }, apiAttemptEvent: function (e) { var t = e.service.api.operations[e.operation], n = { Type: "ApiCallAttempt", Api: t ? t.name : e.operation, Version: 1, Service: e.service.api.serviceId || e.service.api.endpointPrefix, Fqdn: e.httpRequest.endpoint.hostname, UserAgent: e.httpRequest.getUserAgent() }, o = e.response; return o.httpResponse.statusCode && (n.HttpStatusCode = o.httpResponse.statusCode), !e._unAuthenticated && e.service.config.credentials && e.service.config.credentials.accessKeyId && (n.AccessKey = e.service.config.credentials.accessKeyId), o.httpResponse.headers ? (e.httpRequest.headers["x-amz-security-token"] && (n.SessionToken = e.httpRequest.headers["x-amz-security-token"]), o.httpResponse.headers["x-amzn-requestid"] && (n.XAmznRequestId = o.httpResponse.headers["x-amzn-requestid"]), o.httpResponse.headers["x-amz-request-id"] && (n.XAmzRequestId = o.httpResponse.headers["x-amz-request-id"]), o.httpResponse.headers["x-amz-id-2"] && (n.XAmzId2 = o.httpResponse.headers["x-amz-id-2"]), n) : n }, attemptFailEvent: function (e) { var t = this.apiAttemptEvent(e), n = e.response, o = n.error; return n.httpResponse.statusCode > 299 ? (o.code && (t.AwsException = o.code), o.message && (t.AwsExceptionMessage = o.message)) : ((o.code || o.name) && (t.SdkException = o.code || o.name), o.message && (t.SdkExceptionMessage = o.message)), t }, attachMonitoringEmitter: function (e) { var t, n, r, i, s, c, a = 0, u = this; e.on("validate", (function () { i = o.util.realClock.now(), c = Date.now() }), !0), e.on("sign", (function () { n = o.util.realClock.now(), t = Date.now(), s = e.httpRequest.region, a++ }), !0), e.on("validateResponse", (function () { r = Math.round(o.util.realClock.now() - n) })), e.addNamedListener("API_CALL_ATTEMPT", "success", (function () { var n = u.apiAttemptEvent(e); n.Timestamp = t, n.AttemptLatency = r >= 0 ? r : 0, n.Region = s, u.emit("apiCallAttempt", [n]) })), e.addNamedListener("API_CALL_ATTEMPT_RETRY", "retry", (function () { var i = u.attemptFailEvent(e); i.Timestamp = t, r = r || Math.round(o.util.realClock.now() - n), i.AttemptLatency = r >= 0 ? r : 0, i.Region = s, u.emit("apiCallAttempt", [i]) })), e.addNamedListener("API_CALL", "complete", (function () { var t = u.apiCallEvent(e); if (t.AttemptCount = a, !(t.AttemptCount <= 0)) { t.Timestamp = c; var n = Math.round(o.util.realClock.now() - i); t.Latency = n >= 0 ? n : 0; var r = e.response; "number" == typeof r.retryCount && "number" == typeof r.maxRetries && r.retryCount >= r.maxRetries && (t.MaxRetriesExceeded = 1), u.emit("apiCall", [t]) } })) }, setupRequestListeners: function (e) { }, getSignerClass: function (e) { var t, n = null, r = ""; return e && (r = (n = (e.service.api.operations || {})[e.operation] || null) ? n.authtype : ""), t = this.config.signatureVersion ? this.config.signatureVersion : "v4" === r || "v4-unsigned-body" === r ? "v4" : this.api.signatureVersion, o.Signers.RequestSigner.getVersion(t) }, serviceInterface: function () { switch (this.api.protocol) { case "ec2": case "query": return o.EventListeners.Query; case "json": return o.EventListeners.Json; case "rest-json": return o.EventListeners.RestJson; case "rest-xml": return o.EventListeners.RestXml }if (this.api.protocol) throw new Error("Invalid service `protocol' " + this.api.protocol + " in API config") }, successfulResponse: function (e) { return e.httpResponse.statusCode < 300 }, numRetries: function () { return void 0 !== this.config.maxRetries ? this.config.maxRetries : this.defaultRetryCount }, retryDelays: function (e) { return o.util.calculateRetryDelay(e, this.config.retryDelayOptions) }, retryableError: function (e) { return !!this.timeoutError(e) || !!this.networkingError(e) || !!this.expiredCredentialsError(e) || !!this.throttledError(e) || e.statusCode >= 500 }, networkingError: function (e) { return "NetworkingError" === e.code }, timeoutError: function (e) { return "TimeoutError" === e.code }, expiredCredentialsError: function (e) { return "ExpiredTokenException" === e.code }, clockSkewError: function (e) { switch (e.code) { case "RequestTimeTooSkewed": case "RequestExpired": case "InvalidSignatureException": case "SignatureDoesNotMatch": case "AuthFailure": case "RequestInTheFuture": return !0; default: return !1 } }, getSkewCorrectedDate: function () { return new Date(Date.now() + this.config.systemClockOffset) }, applyClockOffset: function (e) { e && (this.config.systemClockOffset = e - Date.now()) }, isClockSkewed: function (e) { if (e) return Math.abs(this.getSkewCorrectedDate().getTime() - e) >= 3e4 }, throttledError: function (e) { if (429 === e.statusCode) return !0; switch (e.code) { case "ProvisionedThroughputExceededException": case "Throttling": case "ThrottlingException": case "RequestLimitExceeded": case "RequestThrottled": case "RequestThrottledException": case "TooManyRequestsException": case "TransactionInProgressException": return !0; default: return !1 } }, endpointFromTemplate: function (e) { if ("string" != typeof e) return e; var t = e; return t = (t = (t = t.replace(/\{service\}/g, this.api.endpointPrefix)).replace(/\{region\}/g, this.config.region)).replace(/\{scheme\}/g, this.config.sslEnabled ? "https" : "http") }, setEndpoint: function (e) { this.endpoint = new o.Endpoint(e, this.config) }, paginationConfig: function (e, t) { var n = this.api.operations[e].paginator; if (!n) { if (t) { var r = new Error; throw o.util.error(r, "No pagination configuration for " + e) } return null } return n } }), o.util.update(o.Service, { defineMethods: function (e) { o.util.each(e.prototype.api.operations, (function (t) { e.prototype[t] || ("none" === e.prototype.api.operations[t].authtype ? e.prototype[t] = function (e, n) { return this.makeUnauthenticatedRequest(t, e, n) } : e.prototype[t] = function (e, n) { return this.makeRequest(t, e, n) }) })) }, defineService: function (e, t, n) { o.Service._serviceMap[e] = !0, Array.isArray(t) || (n = t, t = []); var r = c(o.Service, n || {}); if ("string" == typeof e) { o.Service.addVersions(r, t); var i = r.serviceIdentifier || e; r.serviceIdentifier = i } else r.prototype.api = e, o.Service.defineMethods(r); if (o.SequentialExecutor.call(this.prototype), !this.prototype.publisher && o.util.clientSideMonitoring) { var s = o.util.clientSideMonitoring.Publisher, a = (0, o.util.clientSideMonitoring.configProvider)(); this.prototype.publisher = new s(a), a.enabled && (o.Service._clientSideMonitoring = !0) } return o.SequentialExecutor.call(r.prototype), o.Service.addDefaultMonitoringListeners(r.prototype), r }, addVersions: function (e, t) { Array.isArray(t) || (t = [t]), e.services = e.services || {}; for (var n = 0; n < t.length; n++)void 0 === e.services[t[n]] && (e.services[t[n]] = null); e.apiVersions = Object.keys(e.services).sort() }, defineServiceApi: function (e, t, n) { var r = c(e, { serviceIdentifier: e.serviceIdentifier }); function s(e) { e.isApi ? r.prototype.api = e : r.prototype.api = new i(e) } if ("string" == typeof t) { if (n) s(n); else try { s(o.apiLoader(e.serviceIdentifier, t)) } catch (n) { throw o.util.error(n, { message: "Could not find API configuration " + e.serviceIdentifier + "-" + t }) } Object.prototype.hasOwnProperty.call(e.services, t) || (e.apiVersions = e.apiVersions.concat(t).sort()), e.services[t] = r } else s(t); return o.Service.defineMethods(r), r }, hasService: function (e) { return Object.prototype.hasOwnProperty.call(o.Service._serviceMap, e) }, addDefaultMonitoringListeners: function (e) { e.addNamedListener("MONITOR_EVENTS_BUBBLE", "apiCallAttempt", (function (t) { var n = Object.getPrototypeOf(e); n._events && n.emit("apiCallAttempt", [t]) })), e.addNamedListener("CALL_EVENTS_BUBBLE", "apiCall", (function (t) { var n = Object.getPrototypeOf(e); n._events && n.emit("apiCall", [t]) })) }, _serviceMap: {} }), o.util.mixin(o.Service, o.SequentialExecutor), t.exports = o.Service }).call(this) }).call(this, e("_process")) }, { "./core": 18, "./model/api": 38, "./region_config": 53, _process: 86 }], 60: [function (e, t, n) { var o = e("../core"); o.util.update(o.CognitoIdentity.prototype, { getOpenIdToken: function (e, t) { return this.makeUnauthenticatedRequest("getOpenIdToken", e, t) }, getId: function (e, t) { return this.makeUnauthenticatedRequest("getId", e, t) }, getCredentialsForIdentity: function (e, t) { return this.makeUnauthenticatedRequest("getCredentialsForIdentity", e, t) } }) }, { "../core": 18 }], 61: [function (e, t, n) { (function (t) { (function () { var n = e("../core"), o = e("../region_config"), r = "AWS_STS_REGIONAL_ENDPOINTS", i = "sts_regional_endpoints"; n.util.update(n.STS.prototype, { credentialsFrom: function (e, t) { return e ? (t || (t = new n.TemporaryCredentials), t.expired = !1, t.accessKeyId = e.Credentials.AccessKeyId, t.secretAccessKey = e.Credentials.SecretAccessKey, t.sessionToken = e.Credentials.SessionToken, t.expireTime = e.Credentials.Expiration, t) : null }, assumeRoleWithWebIdentity: function (e, t) { return this.makeUnauthenticatedRequest("assumeRoleWithWebIdentity", e, t) }, assumeRoleWithSAML: function (e, t) { return this.makeUnauthenticatedRequest("assumeRoleWithSAML", e, t) }, validateRegionalEndpointsFlagValue: function (e, t) { if (!("string" == typeof e && ["legacy", "regional"].indexOf(e.toLowerCase()) >= 0)) throw n.util.error(new Error, t); this.config.stsRegionalEndpoints = e.toLowerCase() }, validateRegionalEndpointsFlag: function () { var e = this.config; if (e.stsRegionalEndpoints && this.validateRegionalEndpointsFlagValue(e.stsRegionalEndpoints, { code: "InvalidConfiguration", message: 'invalid "stsRegionalEndpoints" configuration. Expect "legacy" or "regional". Got "' + e.stsRegionalEndpoints + '".' }), n.util.isNode()) { if (Object.prototype.hasOwnProperty.call(t.env, r)) { var o = t.env[r]; this.validateRegionalEndpointsFlagValue(o, { code: "InvalidEnvironmentalVariable", message: "invalid " + r + ' environmental variable. Expect "legacy" or "regional". Got "' + t.env[r] + '".' }) } var s = {}; try { s = n.util.getProfilesFromSharedConfig(n.util.iniLoader)[t.env.AWS_PROFILE || n.util.defaultProfile] } catch (e) { } if (s && Object.prototype.hasOwnProperty.call(s, i)) { var c = s[i]; this.validateRegionalEndpointsFlagValue(c, { code: "InvalidConfiguration", message: "invalid " + i + ' profile config. Expect "legacy" or "regional". Got "' + s[i] + '".' }) } } }, optInRegionalEndpoint: function () { this.validateRegionalEndpointsFlag(); var e = this.config; if ("regional" === e.stsRegionalEndpoints) { if (o(this), !this.isGlobalEndpoint) return; if (this.isGlobalEndpoint = !1, !e.region) throw n.util.error(new Error, { code: "ConfigError", message: "Missing region in config" }); var t = e.endpoint.indexOf(".amazonaws.com"); e.endpoint = e.endpoint.substring(0, t) + "." + e.region + e.endpoint.substring(t) } }, validateService: function () { this.optInRegionalEndpoint() } }) }).call(this) }).call(this, e("_process")) }, { "../core": 18, "../region_config": 53, _process: 86 }], 62: [function (e, t, n) { var o = e("../core"), r = o.util.inherit, i = "presigned-expires"; function s(e) { var t = e.httpRequest.headers[i], n = e.service.getSignerClass(e); if (delete e.httpRequest.headers["User-Agent"], delete e.httpRequest.headers["X-Amz-User-Agent"], n === o.Signers.V4) { if (t > 604800) throw o.util.error(new Error, { code: "InvalidExpiryTime", message: "Presigning does not support expiry time greater than a week with SigV4 signing.", retryable: !1 }); e.httpRequest.headers[i] = t } else { if (n !== o.Signers.S3) throw o.util.error(new Error, { message: "Presigning only supports S3 or SigV4 signing.", code: "UnsupportedSigner", retryable: !1 }); var r = e.service ? e.service.getSkewCorrectedDate() : o.util.date.getDate(); e.httpRequest.headers[i] = parseInt(o.util.date.unixTimestamp(r) + t, 10).toString() } } function c(e) { var t = e.httpRequest.endpoint, n = o.util.urlParse(e.httpRequest.path), r = {}; n.search && (r = o.util.queryStringParse(n.search.substr(1))); var s = e.httpRequest.headers.Authorization.split(" "); if ("AWS" === s[0]) s = s[1].split(":"), r.AWSAccessKeyId = s[0], r.Signature = s[1], o.util.each(e.httpRequest.headers, (function (e, t) { e === i && (e = "Expires"), 0 === e.indexOf("x-amz-meta-") && (delete r[e], e = e.toLowerCase()), r[e] = t })), delete e.httpRequest.headers[i], delete r.Authorization, delete r.Host; else if ("AWS4-HMAC-SHA256" === s[0]) { s.shift(); var c = s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1]; r["X-Amz-Signature"] = c, delete r.Expires } t.pathname = n.pathname, t.search = o.util.queryParamsToString(r) } o.Signers.Presign = r({ sign: function (e, t, n) { if (e.httpRequest.headers[i] = t || 3600, e.on("build", s), e.on("sign", c), e.removeListener("afterBuild", o.EventListeners.Core.SET_CONTENT_LENGTH), e.removeListener("afterBuild", o.EventListeners.Core.COMPUTE_SHA256), e.emit("beforePresign", [e]), !n) { if (e.build(), e.response.error) throw e.response.error; return o.util.urlFormat(e.httpRequest.endpoint) } e.build((function () { this.response.error ? n(this.response.error) : n(null, o.util.urlFormat(e.httpRequest.endpoint)) })) } }), t.exports = o.Signers.Presign }, { "../core": 18 }], 63: [function (e, t, n) { var o = e("../core"), r = o.util.inherit; o.Signers.RequestSigner = r({ constructor: function (e) { this.request = e }, setServiceClientId: function (e) { this.serviceClientId = e }, getServiceClientId: function () { return this.serviceClientId } }), o.Signers.RequestSigner.getVersion = function (e) { switch (e) { case "v2": return o.Signers.V2; case "v3": return o.Signers.V3; case "s3v4": case "v4": return o.Signers.V4; case "s3": return o.Signers.S3; case "v3https": return o.Signers.V3Https }throw new Error("Unknown signing version " + e) }, e("./v2"), e("./v3"), e("./v3https"), e("./v4"), e("./s3"), e("./presign") }, { "../core": 18, "./presign": 62, "./s3": 64, "./v2": 65, "./v3": 66, "./v3https": 67, "./v4": 68 }], 64: [function (e, t, n) { var o = e("../core"), r = o.util.inherit; o.Signers.S3 = r(o.Signers.RequestSigner, { subResources: { acl: 1, accelerate: 1, analytics: 1, cors: 1, lifecycle: 1, delete: 1, inventory: 1, location: 1, logging: 1, metrics: 1, notification: 1, partNumber: 1, policy: 1, requestPayment: 1, replication: 1, restore: 1, tagging: 1, torrent: 1, uploadId: 1, uploads: 1, versionId: 1, versioning: 1, versions: 1, website: 1 }, responseHeaders: { "response-content-type": 1, "response-content-language": 1, "response-expires": 1, "response-cache-control": 1, "response-content-disposition": 1, "response-content-encoding": 1 }, addAuthorization: function (e, t) { this.request.headers["presigned-expires"] || (this.request.headers["X-Amz-Date"] = o.util.date.rfc822(t)), e.sessionToken && (this.request.headers["x-amz-security-token"] = e.sessionToken); var n = this.sign(e.secretAccessKey, this.stringToSign()), r = "AWS " + e.accessKeyId + ":" + n; this.request.headers.Authorization = r }, stringToSign: function () { var e = this.request, t = []; t.push(e.method), t.push(e.headers["Content-MD5"] || ""), t.push(e.headers["Content-Type"] || ""), t.push(e.headers["presigned-expires"] || ""); var n = this.canonicalizedAmzHeaders(); return n && t.push(n), t.push(this.canonicalizedResource()), t.join("\n") }, canonicalizedAmzHeaders: function () { var e = []; o.util.each(this.request.headers, (function (t) { t.match(/^x-amz-/i) && e.push(t) })), e.sort((function (e, t) { return e.toLowerCase() < t.toLowerCase() ? -1 : 1 })); var t = []; return o.util.arrayEach.call(this, e, (function (e) { t.push(e.toLowerCase() + ":" + String(this.request.headers[e])) })), t.join("\n") }, canonicalizedResource: function () { var e = this.request, t = e.path.split("?"), n = t[0], r = t[1], i = ""; if (e.virtualHostedBucket && (i += "/" + e.virtualHostedBucket), i += n, r) { var s = []; o.util.arrayEach.call(this, r.split("&"), (function (e) { var t = e.split("=")[0], n = e.split("=")[1]; if (this.subResources[t] || this.responseHeaders[t]) { var o = { name: t }; void 0 !== n && (this.subResources[t] ? o.value = n : o.value = decodeURIComponent(n)), s.push(o) } })), s.sort((function (e, t) { return e.name < t.name ? -1 : 1 })), s.length && (r = [], o.util.arrayEach(s, (function (e) { void 0 === e.value ? r.push(e.name) : r.push(e.name + "=" + e.value) })), i += "?" + r.join("&")) } return i }, sign: function (e, t) { return o.util.crypto.hmac(e, t, "base64", "sha1") } }), t.exports = o.Signers.S3 }, { "../core": 18 }], 65: [function (e, t, n) { var o = e("../core"), r = o.util.inherit; o.Signers.V2 = r(o.Signers.RequestSigner, { addAuthorization: function (e, t) { t || (t = o.util.date.getDate()); var n = this.request; n.params.Timestamp = o.util.date.iso8601(t), n.params.SignatureVersion = "2", n.params.SignatureMethod = "HmacSHA256", n.params.AWSAccessKeyId = e.accessKeyId, e.sessionToken && (n.params.SecurityToken = e.sessionToken), delete n.params.Signature, n.params.Signature = this.signature(e), n.body = o.util.queryParamsToString(n.params), n.headers["Content-Length"] = n.body.length }, signature: function (e) { return o.util.crypto.hmac(e.secretAccessKey, this.stringToSign(), "base64") }, stringToSign: function () { var e = []; return e.push(this.request.method), e.push(this.request.endpoint.host.toLowerCase()), e.push(this.request.pathname()), e.push(o.util.queryParamsToString(this.request.params)), e.join("\n") } }), t.exports = o.Signers.V2 }, { "../core": 18 }], 66: [function (e, t, n) { var o = e("../core"), r = o.util.inherit; o.Signers.V3 = r(o.Signers.RequestSigner, { addAuthorization: function (e, t) { var n = o.util.date.rfc822(t); this.request.headers["X-Amz-Date"] = n, e.sessionToken && (this.request.headers["x-amz-security-token"] = e.sessionToken), this.request.headers["X-Amzn-Authorization"] = this.authorization(e, n) }, authorization: function (e) { return "AWS3 AWSAccessKeyId=" + e.accessKeyId + ",Algorithm=HmacSHA256,SignedHeaders=" + this.signedHeaders() + ",Signature=" + this.signature(e) }, signedHeaders: function () { var e = []; return o.util.arrayEach(this.headersToSign(), (function (t) { e.push(t.toLowerCase()) })), e.sort().join(";") }, canonicalHeaders: function () { var e = this.request.headers, t = []; return o.util.arrayEach(this.headersToSign(), (function (n) { t.push(n.toLowerCase().trim() + ":" + String(e[n]).trim()) })), t.sort().join("\n") + "\n" }, headersToSign: function () { var e = []; return o.util.each(this.request.headers, (function (t) { ("Host" === t || "Content-Encoding" === t || t.match(/^X-Amz/i)) && e.push(t) })), e }, signature: function (e) { return o.util.crypto.hmac(e.secretAccessKey, this.stringToSign(), "base64") }, stringToSign: function () { var e = []; return e.push(this.request.method), e.push("/"), e.push(""), e.push(this.canonicalHeaders()), e.push(this.request.body), o.util.crypto.sha256(e.join("\n")) } }), t.exports = o.Signers.V3 }, { "../core": 18 }], 67: [function (e, t, n) { var o = e("../core"), r = o.util.inherit; e("./v3"), o.Signers.V3Https = r(o.Signers.V3, { authorization: function (e) { return "AWS3-HTTPS AWSAccessKeyId=" + e.accessKeyId + ",Algorithm=HmacSHA256,Signature=" + this.signature(e) }, stringToSign: function () { return this.request.headers["X-Amz-Date"] } }), t.exports = o.Signers.V3Https }, { "../core": 18, "./v3": 66 }], 68: [function (e, t, n) { var o = e("../core"), r = e("./v4_credentials"), i = o.util.inherit, s = "presigned-expires"; o.Signers.V4 = i(o.Signers.RequestSigner, { constructor: function (e, t, n) { o.Signers.RequestSigner.call(this, e), this.serviceName = t, n = n || {}, this.signatureCache = "boolean" != typeof n.signatureCache || n.signatureCache, this.operation = n.operation, this.signatureVersion = n.signatureVersion }, algorithm: "AWS4-HMAC-SHA256", addAuthorization: function (e, t) { var n = o.util.date.iso8601(t).replace(/[:\-]|\.\d{3}/g, ""); this.isPresigned() ? this.updateForPresigned(e, n) : this.addHeaders(e, n), this.request.headers.Authorization = this.authorization(e, n) }, addHeaders: function (e, t) { this.request.headers["X-Amz-Date"] = t, e.sessionToken && (this.request.headers["x-amz-security-token"] = e.sessionToken) }, updateForPresigned: function (e, t) { var n = this.credentialString(t), r = { "X-Amz-Date": t, "X-Amz-Algorithm": this.algorithm, "X-Amz-Credential": e.accessKeyId + "/" + n, "X-Amz-Expires": this.request.headers[s], "X-Amz-SignedHeaders": this.signedHeaders() }; e.sessionToken && (r["X-Amz-Security-Token"] = e.sessionToken), this.request.headers["Content-Type"] && (r["Content-Type"] = this.request.headers["Content-Type"]), this.request.headers["Content-MD5"] && (r["Content-MD5"] = this.request.headers["Content-MD5"]), this.request.headers["Cache-Control"] && (r["Cache-Control"] = this.request.headers["Cache-Control"]), o.util.each.call(this, this.request.headers, (function (e, t) { if (e !== s && this.isSignableHeader(e)) { var n = e.toLowerCase(); 0 === n.indexOf("x-amz-meta-") ? r[n] = t : 0 === n.indexOf("x-amz-") && (r[e] = t) } })); var i = this.request.path.indexOf("?") >= 0 ? "&" : "?"; this.request.path += i + o.util.queryParamsToString(r) }, authorization: function (e, t) { var n = [], o = this.credentialString(t); return n.push(this.algorithm + " Credential=" + e.accessKeyId + "/" + o), n.push("SignedHeaders=" + this.signedHeaders()), n.push("Signature=" + this.signature(e, t)), n.join(", ") }, signature: function (e, t) { var n = r.getSigningKey(e, t.substr(0, 8), this.request.region, this.serviceName, this.signatureCache); return o.util.crypto.hmac(n, this.stringToSign(t), "hex") }, stringToSign: function (e) { var t = []; return t.push("AWS4-HMAC-SHA256"), t.push(e), t.push(this.credentialString(e)), t.push(this.hexEncodedHash(this.canonicalString())), t.join("\n") }, canonicalString: function () { var e = [], t = this.request.pathname(); return "s3" !== this.serviceName && "s3v4" !== this.signatureVersion && (t = o.util.uriEscapePath(t)), e.push(this.request.method), e.push(t), e.push(this.request.search()), e.push(this.canonicalHeaders() + "\n"), e.push(this.signedHeaders()), e.push(this.hexEncodedBodyHash()), e.join("\n") }, canonicalHeaders: function () { var e = []; o.util.each.call(this, this.request.headers, (function (t, n) { e.push([t, n]) })), e.sort((function (e, t) { return e[0].toLowerCase() < t[0].toLowerCase() ? -1 : 1 })); var t = []; return o.util.arrayEach.call(this, e, (function (e) { var n = e[0].toLowerCase(); if (this.isSignableHeader(n)) { var r = e[1]; if (null == r || "function" != typeof r.toString) throw o.util.error(new Error("Header " + n + " contains invalid value"), { code: "InvalidHeader" }); t.push(n + ":" + this.canonicalHeaderValues(r.toString())) } })), t.join("\n") }, canonicalHeaderValues: function (e) { return e.replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "") }, signedHeaders: function () { var e = []; return o.util.each.call(this, this.request.headers, (function (t) { t = t.toLowerCase(), this.isSignableHeader(t) && e.push(t) })), e.sort().join(";") }, credentialString: function (e) { return r.createScope(e.substr(0, 8), this.request.region, this.serviceName) }, hexEncodedHash: function (e) { return o.util.crypto.sha256(e, "hex") }, hexEncodedBodyHash: function () { var e = this.request; return this.isPresigned() && "s3" === this.serviceName && !e.body ? "UNSIGNED-PAYLOAD" : e.headers["X-Amz-Content-Sha256"] ? e.headers["X-Amz-Content-Sha256"] : this.hexEncodedHash(this.request.body || "") }, unsignableHeaders: ["authorization", "content-type", "content-length", "user-agent", s, "expect", "x-amzn-trace-id"], isSignableHeader: function (e) { return 0 === e.toLowerCase().indexOf("x-amz-") || this.unsignableHeaders.indexOf(e) < 0 }, isPresigned: function () { return !!this.request.headers[s] } }), t.exports = o.Signers.V4 }, { "../core": 18, "./v4_credentials": 69 }], 69: [function (e, t, n) { var o = e("../core"), r = {}, i = [], s = "aws4_request"; t.exports = { createScope: function (e, t, n) { return [e.substr(0, 8), t, n, s].join("/") }, getSigningKey: function (e, t, n, c, a) { var u = [o.util.crypto.hmac(e.secretAccessKey, e.accessKeyId, "base64"), t, n, c].join("_"); if ((a = !1 !== a) && u in r) return r[u]; var l = o.util.crypto.hmac("AWS4" + e.secretAccessKey, t, "buffer"), p = o.util.crypto.hmac(l, n, "buffer"), h = o.util.crypto.hmac(p, c, "buffer"), d = o.util.crypto.hmac(h, s, "buffer"); return a && (r[u] = d, i.push(u), i.length > 50 && delete r[i.shift()]), d }, emptyCache: function () { r = {}, i = [] } } }, { "../core": 18 }], 70: [function (e, t, n) { function o(e, t) { this.currentState = t || null, this.states = e || {} } o.prototype.runTo = function (e, t, n, o) { "function" == typeof e && (o = n, n = t, t = e, e = null); var r = this, i = r.states[r.currentState]; i.fn.call(n || r, o, (function (o) { if (o) { if (!i.fail) return t ? t.call(n, o) : null; r.currentState = i.fail } else { if (!i.accept) return t ? t.call(n) : null; r.currentState = i.accept } if (r.currentState === e) return t ? t.call(n, o) : null; r.runTo(e, t, n, o) })) }, o.prototype.addState = function (e, t, n, o) { return "function" == typeof t ? (o = t, t = null, n = null) : "function" == typeof n && (o = n, n = null), this.currentState || (this.currentState = e), this.states[e] = { accept: t, fail: n, fn: o }, this }, t.exports = o }, {}], 71: [function (e, t, n) { (function (n, o) { (function () { var i, s = { environment: "nodejs", engine: function () { if (s.isBrowser() && "undefined" != typeof navigator) return navigator.userAgent; var e = n.platform + "/" + n.version; return n.env.AWS_EXECUTION_ENV && (e += " exec-env/" + n.env.AWS_EXECUTION_ENV), e }, userAgent: function () { var t = s.environment, n = "aws-sdk-" + t + "/" + e("./core").VERSION; return "nodejs" === t && (n += " " + s.engine()), n }, uriEscape: function (e) { var t = encodeURIComponent(e); return t = (t = t.replace(/[^A-Za-z0-9_.~\-%]+/g, escape)).replace(/[*]/g, (function (e) { return "%" + e.charCodeAt(0).toString(16).toUpperCase() })) }, uriEscapePath: function (e) { var t = []; return s.arrayEach(e.split("/"), (function (e) { t.push(s.uriEscape(e)) })), t.join("/") }, urlParse: function (e) { return s.url.parse(e) }, urlFormat: function (e) { return s.url.format(e) }, queryStringParse: function (e) { return s.querystring.parse(e) }, queryParamsToString: function (e) { var t = [], n = s.uriEscape, o = Object.keys(e).sort(); return s.arrayEach(o, (function (o) { var r = e[o], i = n(o), c = i + "="; if (Array.isArray(r)) { var a = []; s.arrayEach(r, (function (e) { a.push(n(e)) })), c = i + "=" + a.sort().join("&" + i + "=") } else null != r && (c = i + "=" + n(r)); t.push(c) })), t.join("&") }, readFileSync: function (t) { return s.isBrowser() ? null : e("fs").readFileSync(t, "utf-8") }, base64: { encode: function (e) { if ("number" == typeof e) throw s.error(new Error("Cannot base64 encode number " + e)); return null == e ? e : s.buffer.toBuffer(e).toString("base64") }, decode: function (e) { if ("number" == typeof e) throw s.error(new Error("Cannot base64 decode number " + e)); return null == e ? e : s.buffer.toBuffer(e, "base64") } }, buffer: { toBuffer: function (e, t) { return "function" == typeof s.Buffer.from && s.Buffer.from !== Uint8Array.from ? s.Buffer.from(e, t) : new s.Buffer(e, t) }, alloc: function (e, t, n) { if ("number" != typeof e) throw new Error("size passed to alloc must be a number."); if ("function" == typeof s.Buffer.alloc) return s.Buffer.alloc(e, t, n); var o = new s.Buffer(e); return void 0 !== t && "function" == typeof o.fill && o.fill(t, void 0, void 0, n), o }, toStream: function (e) { s.Buffer.isBuffer(e) || (e = s.buffer.toBuffer(e)); var t = new s.stream.Readable, n = 0; return t._read = function (o) { if (n >= e.length) return t.push(null); var r = n + o; r > e.length && (r = e.length), t.push(e.slice(n, r)), n = r }, t }, concat: function (e) { var t, n, o = 0, r = 0; for (n = 0; n < e.length; n++)o += e[n].length; for (t = s.buffer.alloc(o), n = 0; n < e.length; n++)e[n].copy(t, r), r += e[n].length; return t } }, string: { byteLength: function (t) { if (null == t) return 0; if ("string" == typeof t && (t = s.buffer.toBuffer(t)), "number" == typeof t.byteLength) return t.byteLength; if ("number" == typeof t.length) return t.length; if ("number" == typeof t.size) return t.size; if ("string" == typeof t.path) return e("fs").lstatSync(t.path).size; throw s.error(new Error("Cannot determine length of " + t), { object: t }) }, upperFirst: function (e) { return e[0].toUpperCase() + e.substr(1) }, lowerFirst: function (e) { return e[0].toLowerCase() + e.substr(1) } }, ini: { parse: function (e) { var t, n = {}; return s.arrayEach(e.split(/\r?\n/), (function (e) { var o = (e = e.split(/(^|\s)[;#]/)[0]).match(/^\s*\[([^\[\]]+)\]\s*$/); if (o) t = o[1]; else if (t) { var r = e.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); r && (n[t] = n[t] || {}, n[t][r[1]] = r[2]) } })), n } }, fn: { noop: function () { }, callback: function (e) { if (e) throw e }, makeAsync: function (e, t) { return t && t <= e.length ? e : function () { var t = Array.prototype.slice.call(arguments, 0); t.pop()(e.apply(null, t)) } } }, date: { getDate: function () { return i || (i = e("./core")), i.config.systemClockOffset ? new Date((new Date).getTime() + i.config.systemClockOffset) : new Date }, iso8601: function (e) { return void 0 === e && (e = s.date.getDate()), e.toISOString().replace(/\.\d{3}Z$/, "Z") }, rfc822: function (e) { return void 0 === e && (e = s.date.getDate()), e.toUTCString() }, unixTimestamp: function (e) { return void 0 === e && (e = s.date.getDate()), e.getTime() / 1e3 }, from: function (e) { return "number" == typeof e ? new Date(1e3 * e) : new Date(e) }, format: function (e, t) { return t || (t = "iso8601"), s.date[t](s.date.from(e)) }, parseTimestamp: function (e) { if ("number" == typeof e) return new Date(1e3 * e); if (e.match(/^\d+$/)) return new Date(1e3 * e); if (e.match(/^\d{4}/)) return new Date(e); if (e.match(/^\w{3},/)) return new Date(e); throw s.error(new Error("unhandled timestamp format: " + e), { code: "TimestampParserError" }) } }, crypto: { crc32Table: [0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117], crc32: function (e) { var t = s.crypto.crc32Table, n = -1; "string" == typeof e && (e = s.buffer.toBuffer(e)); for (var o = 0; o < e.length; o++)n = n >>> 8 ^ t[255 & (n ^ e.readUInt8(o))]; return (-1 ^ n) >>> 0 }, hmac: function (e, t, n, o) { return n || (n = "binary"), "buffer" === n && (n = void 0), o || (o = "sha256"), "string" == typeof t && (t = s.buffer.toBuffer(t)), s.crypto.lib.createHmac(o, e).update(t).digest(n) }, md5: function (e, t, n) { return s.crypto.hash("md5", e, t, n) }, sha256: function (e, t, n) { return s.crypto.hash("sha256", e, t, n) }, hash: function (e, t, n, o) { var i = s.crypto.createHash(e); n || (n = "binary"), "buffer" === n && (n = void 0), "string" == typeof t && (t = s.buffer.toBuffer(t)); var c = s.arraySliceFn(t), a = s.Buffer.isBuffer(t); if (s.isBrowser() && "undefined" != typeof ArrayBuffer && t && t.buffer instanceof ArrayBuffer && (a = !0), o && "object" === r(t) && "function" == typeof t.on && !a) t.on("data", (function (e) { i.update(e) })), t.on("error", (function (e) { o(e) })), t.on("end", (function () { o(null, i.digest(n)) })); else { if (!o || !c || a || "undefined" == typeof FileReader) { s.isBrowser() && "object" === r(t) && !a && (t = new s.Buffer(new Uint8Array(t))); var u = i.update(t).digest(n); return o && o(null, u), u } var l = 0, p = new FileReader; p.onerror = function () { o(new Error("Failed to read data.")) }, p.onload = function () { var e = new s.Buffer(new Uint8Array(p.result)); i.update(e), l += e.length, p._continueReading() }, p._continueReading = function () { if (l >= t.size) o(null, i.digest(n)); else { var e = l + 524288; e > t.size && (e = t.size), p.readAsArrayBuffer(c.call(t, l, e)) } }, p._continueReading() } }, toHex: function (e) { for (var t = [], n = 0; n < e.length; n++)t.push(("0" + e.charCodeAt(n).toString(16)).substr(-2, 2)); return t.join("") }, createHash: function (e) { return s.crypto.lib.createHash(e) } }, abort: {}, each: function (e, t) { for (var n in e) if (Object.prototype.hasOwnProperty.call(e, n) && t.call(this, n, e[n]) === s.abort) break }, arrayEach: function (e, t) { for (var n in e) if (Object.prototype.hasOwnProperty.call(e, n) && t.call(this, e[n], parseInt(n, 10)) === s.abort) break }, update: function (e, t) { return s.each(t, (function (t, n) { e[t] = n })), e }, merge: function (e, t) { return s.update(s.copy(e), t) }, copy: function (e) { if (null == e) return e; var t = {}; for (var n in e) t[n] = e[n]; return t }, isEmpty: function (e) { for (var t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1; return !0 }, arraySliceFn: function (e) { var t = e.slice || e.webkitSlice || e.mozSlice; return "function" == typeof t ? t : null }, isType: function (e, t) { return "function" == typeof t && (t = s.typeName(t)), Object.prototype.toString.call(e) === "[object " + t + "]" }, typeName: function (e) { if (Object.prototype.hasOwnProperty.call(e, "name")) return e.name; var t = e.toString(), n = t.match(/^\s*function (.+)\(/); return n ? n[1] : t }, error: function (e, t) { var n = null; return "string" == typeof e.message && "" !== e.message && ("string" == typeof t || t && t.message) && ((n = s.copy(e)).message = e.message), e.message = e.message || null, "string" == typeof t ? e.message = t : "object" === r(t) && null !== t && (s.update(e, t), t.message && (e.message = t.message), (t.code || t.name) && (e.code = t.code || t.name), t.stack && (e.stack = t.stack)), "function" == typeof Object.defineProperty && (Object.defineProperty(e, "name", { writable: !0, enumerable: !1 }), Object.defineProperty(e, "message", { enumerable: !0 })), e.name = t && t.name || e.name || e.code || "Error", e.time = new Date, n && (e.originalError = n), e }, inherit: function (e, t) { var n = null; if (void 0 === t) t = e, e = Object, n = {}; else { var o = function () { }; o.prototype = e.prototype, n = new o } return t.constructor === Object && (t.constructor = function () { if (e !== Object) return e.apply(this, arguments) }), t.constructor.prototype = n, s.update(t.constructor.prototype, t), t.constructor.__super__ = e, t.constructor }, mixin: function () { for (var e = arguments[0], t = 1; t < arguments.length; t++)for (var n in arguments[t].prototype) { var o = arguments[t].prototype[n]; "constructor" !== n && (e.prototype[n] = o) } return e }, hideProperties: function (e, t) { "function" == typeof Object.defineProperty && s.arrayEach(t, (function (t) { Object.defineProperty(e, t, { enumerable: !1, writable: !0, configurable: !0 }) })) }, property: function (e, t, n, o, r) { var i = { configurable: !0, enumerable: void 0 === o || o }; "function" != typeof n || r ? (i.value = n, i.writable = !0) : i.get = n, Object.defineProperty(e, t, i) }, memoizedProperty: function (e, t, n, o) { var r = null; s.property(e, t, (function () { return null === r && (r = n()), r }), o) }, hoistPayloadMember: function (e) { var t = e.request, n = t.operation, o = t.service.api.operations[n], r = o.output; if (r.payload && !o.hasEventOutput) { var i = r.members[r.payload], c = e.data[r.payload]; "structure" === i.type && s.each(c, (function (t, n) { s.property(e.data, t, n, !1) })) } }, computeSha256: function (t, n) { if (s.isNode()) { var o = s.stream.Stream, r = e("fs"); if ("function" == typeof o && t instanceof o) { if ("string" != typeof t.path) return n(new Error("Non-file stream objects are not supported with SigV4")); var i = {}; "number" == typeof t.start && (i.start = t.start), "number" == typeof t.end && (i.end = t.end), t = r.createReadStream(t.path, i) } } s.crypto.sha256(t, "hex", (function (e, t) { e ? n(e) : n(null, t) })) }, isClockSkewed: function (e) { if (e) return s.property(i.config, "isClockSkewed", Math.abs((new Date).getTime() - e) >= 3e5, !1), i.config.isClockSkewed }, applyClockOffset: function (e) { e && (i.config.systemClockOffset = e - (new Date).getTime()) }, extractRequestId: function (e) { var t = e.httpResponse.headers["x-amz-request-id"] || e.httpResponse.headers["x-amzn-requestid"]; !t && e.data && e.data.ResponseMetadata && (t = e.data.ResponseMetadata.RequestId), t && (e.requestId = t), e.error && (e.error.requestId = t) }, addPromises: function (e, t) { var n = !1; void 0 === t && i && i.config && (t = i.config.getPromisesDependency()), void 0 === t && "undefined" != typeof Promise && (t = Promise), "function" != typeof t && (n = !0), Array.isArray(e) || (e = [e]); for (var o = 0; o < e.length; o++) { var r = e[o]; n ? r.deletePromisesFromClass && r.deletePromisesFromClass() : r.addPromisesToClass && r.addPromisesToClass(t) } }, promisifyMethod: function (e, t) { return function () { var n = this, o = Array.prototype.slice.call(arguments); return new t((function (t, r) { o.push((function (e, n) { e ? r(e) : t(n) })), n[e].apply(n, o) })) } }, isDualstackAvailable: function (t) { if (!t) return !1; var n = e("../apis/metadata.json"); return "string" != typeof t && (t = t.serviceIdentifier), !("string" != typeof t || !n.hasOwnProperty(t) || !n[t].dualstackAvailable) }, calculateRetryDelay: function (e, t) { t || (t = {}); var n = t.customBackoff || null; if ("function" == typeof n) return n(e); var o = "number" == typeof t.base ? t.base : 100; return Math.random() * (Math.pow(2, e) * o) }, handleRequestWithRetries: function (e, t, n) { t || (t = {}); var o = i.HttpClient.getInstance(), r = t.httpOptions || {}, c = 0, a = function (e) { var o = t.maxRetries || 0; if (e && "TimeoutError" === e.code && (e.retryable = !0), e && e.retryable && c < o) { c++; var r = s.calculateRetryDelay(c, t.retryDelayOptions); setTimeout(u, r + (e.retryAfter || 0)) } else n(e) }, u = function () { var t = ""; o.handleRequest(e, r, (function (e) { e.on("data", (function (e) { t += e.toString() })), e.on("end", (function () { var o = e.statusCode; if (o < 300) n(null, t); else { var r = 1e3 * parseInt(e.headers["retry-after"], 10) || 0, i = s.error(new Error, { retryable: o >= 500 || 429 === o }); r && i.retryable && (i.retryAfter = r), a(i) } })) }), a) }; i.util.defer(u) }, uuid: { v4: function () { return e("uuid").v4() } }, convertPayloadToString: function (e) { var t = e.request, n = t.operation, o = t.service.api.operations[n].output || {}; o.payload && e.data[o.payload] && (e.data[o.payload] = e.data[o.payload].toString()) }, defer: function (e) { "object" === r(n) && "function" == typeof n.nextTick ? n.nextTick(e) : "function" == typeof o ? o(e) : setTimeout(e, 0) }, getRequestPayloadShape: function (e) { var t = e.service.api.operations; if (t) { var n = (t || {})[e.operation]; if (n && n.input && n.input.payload) return n.input.members[n.input.payload] } }, getProfilesFromSharedConfig: function (e, t) { var o = {}, r = {}; n.env[s.configOptInEnv] && (r = e.loadFrom({ isConfig: !0, filename: n.env[s.sharedConfigFileEnv] })); for (var i = e.loadFrom({ filename: t || n.env[s.configOptInEnv] && n.env[s.sharedCredentialsFileEnv] }), c = 0, a = Object.keys(r); c < a.length; c++)o[a[c]] = r[a[c]]; for (c = 0, a = Object.keys(i); c < a.length; c++)o[a[c]] = i[a[c]]; return o }, defaultProfile: "default", configOptInEnv: "AWS_SDK_LOAD_CONFIG", sharedCredentialsFileEnv: "AWS_SHARED_CREDENTIALS_FILE", sharedConfigFileEnv: "AWS_CONFIG_FILE", imdsDisabledEnv: "AWS_EC2_METADATA_DISABLED" }; t.exports = s }).call(this) }).call(this, e("_process"), e("timers").setImmediate) }, { "../apis/metadata.json": 4, "./core": 18, _process: 86, fs: 79, timers: 93, uuid: 98 }], 72: [function (e, t, n) { var o = e("../util"), r = e("../model/shape"); function i() { } function s(e, t) { for (var n = e.getElementsByTagName(t), o = 0, r = n.length; o < r; o++)if (n[o].parentNode === e) return n[o] } function c(e, t) { switch (t || (t = {}), t.type) { case "structure": return a(e, t); case "map": return function (e, t) { for (var n = {}, o = t.key.name || "key", r = t.value.name || "value", i = t.flattened ? t.name : "entry", a = e.firstElementChild; a;) { if (a.nodeName === i) { var u = s(a, o).textContent, l = s(a, r); n[u] = c(l, t.value) } a = a.nextElementSibling } return n }(e, t); case "list": return function (e, t) { for (var n = [], o = t.flattened ? t.name : t.member.name || "member", r = e.firstElementChild; r;)r.nodeName === o && n.push(c(r, t.member)), r = r.nextElementSibling; return n }(e, t); case void 0: case null: return function (e) { if (null == e) return ""; if (!e.firstElementChild) return null === e.parentNode.parentNode ? {} : 0 === e.childNodes.length ? "" : e.textContent; for (var t = { type: "structure", members: {} }, n = e.firstElementChild; n;) { var o = n.nodeName; Object.prototype.hasOwnProperty.call(t.members, o) ? t.members[o].type = "list" : t.members[o] = { name: o }, n = n.nextElementSibling } return a(e, t) }(e); default: return function (e, t) { if (e.getAttribute) { var n = e.getAttribute("encoding"); "base64" === n && (t = new r.create({ type: n })) } var o = e.textContent; return "" === o && (o = null), "function" == typeof t.toType ? t.toType(o) : o }(e, t) } } function a(e, t) { var n = {}; return null === e || o.each(t.members, (function (t, o) { if (o.isXmlAttribute) { if (Object.prototype.hasOwnProperty.call(e.attributes, o.name)) { var r = e.attributes[o.name].value; n[t] = c({ textContent: r }, o) } } else { var i = o.flattened ? e : s(e, o.name); i ? n[t] = c(i, o) : o.flattened || "list" !== o.type || (n[t] = o.defaultValue) } })), n } i.prototype.parse = function (e, t) { if ("" === e.replace(/^\s+/, "")) return {}; var n, r; try { if (window.DOMParser) { try { n = (new DOMParser).parseFromString(e, "text/xml") } catch (e) { throw o.error(new Error("Parse error in document"), { originalError: e, code: "XMLParserError", retryable: !0 }) } if (null === n.documentElement) throw o.error(new Error("Cannot parse empty document."), { code: "XMLParserError", retryable: !0 }); var i = n.getElementsByTagName("parsererror")[0]; if (i && (i.parentNode === n || "body" === i.parentNode.nodeName || i.parentNode.parentNode === n || "body" === i.parentNode.parentNode.nodeName)) { var a = i.getElementsByTagName("div")[0] || i; throw o.error(new Error(a.textContent || "Parser error in document"), { code: "XMLParserError", retryable: !0 }) } } else { if (!window.ActiveXObject) throw new Error("Cannot load XML parser"); if ((n = new window.ActiveXObject("Microsoft.XMLDOM")).async = !1, !n.loadXML(e)) throw o.error(new Error("Parse error in document"), { code: "XMLParserError", retryable: !0 }) } } catch (e) { r = e } if (n && n.documentElement && !r) { var u = c(n.documentElement, t), l = s(n.documentElement, "ResponseMetadata"); return l && (u.ResponseMetadata = c(l, {})), u } if (r) throw o.error(r || new Error, { code: "XMLParserError", retryable: !0 }); return {} }, t.exports = i }, { "../model/shape": 43, "../util": 71 }], 73: [function (e, t, n) { var o = e("../util"), r = e("./xml-node").XmlNode, i = e("./xml-text").XmlText; function s() { } function c(e, t, n) { switch (n.type) { case "structure": return function (e, t, n) { o.arrayEach(n.memberNames, (function (o) { var i = n.members[o]; if ("body" === i.location) { var s = t[o], u = i.name; if (null != s) if (i.isXmlAttribute) e.addAttribute(u, s); else if (i.flattened) c(e, s, i); else { var l = new r(u); e.addChildNode(l), a(l, i), c(l, s, i) } } })) }(e, t, n); case "map": return function (e, t, n) { var i = n.key.name || "key", s = n.value.name || "value"; o.each(t, (function (t, o) { var a = new r(n.flattened ? n.name : "entry"); e.addChildNode(a); var u = new r(i), l = new r(s); a.addChildNode(u), a.addChildNode(l), c(u, t, n.key), c(l, o, n.value) })) }(e, t, n); case "list": return function (e, t, n) { n.flattened ? o.arrayEach(t, (function (t) { var o = n.member.name || n.name, i = new r(o); e.addChildNode(i), c(i, t, n.member) })) : o.arrayEach(t, (function (t) { var o = n.member.name || "member", i = new r(o); e.addChildNode(i), c(i, t, n.member) })) }(e, t, n); default: return function (e, t, n) { e.addChildNode(new i(n.toWireFormat(t))) }(e, t, n) } } function a(e, t, n) { var o, r = "xmlns"; t.xmlNamespaceUri ? (o = t.xmlNamespaceUri, t.xmlNamespacePrefix && (r += ":" + t.xmlNamespacePrefix)) : n && t.api.xmlNamespaceUri && (o = t.api.xmlNamespaceUri), o && e.addAttribute(r, o) } s.prototype.toXML = function (e, t, n, o) { var i = new r(n); return a(i, t, !0), c(i, e, t), i.children.length > 0 || o ? i.toString() : "" }, t.exports = s }, { "../util": 71, "./xml-node": 76, "./xml-text": 77 }], 74: [function (e, t, n) { t.exports = { escapeAttribute: function (e) { return e.replace(/&/g, "&").replace(/'/g, "'").replace(//g, ">").replace(/"/g, """) } } }, {}], 75: [function (e, t, n) { t.exports = { escapeElement: function (e) { return e.replace(/&/g, "&").replace(//g, ">") } } }, {}], 76: [function (e, t, n) { var o = e("./escape-attribute").escapeAttribute; function r(e, t) { void 0 === t && (t = []), this.name = e, this.children = t, this.attributes = {} } r.prototype.addAttribute = function (e, t) { return this.attributes[e] = t, this }, r.prototype.addChildNode = function (e) { return this.children.push(e), this }, r.prototype.removeAttribute = function (e) { return delete this.attributes[e], this }, r.prototype.toString = function () { for (var e = Boolean(this.children.length), t = "<" + this.name, n = this.attributes, r = 0, i = Object.keys(n); r < i.length; r++) { var s = i[r], c = n[s]; null != c && (t += " " + s + '="' + o("" + c) + '"') } return t + (e ? ">" + this.children.map((function (e) { return e.toString() })).join("") + "" : "/>") }, t.exports = { XmlNode: r } }, { "./escape-attribute": 74 }], 77: [function (e, t, n) { var o = e("./escape-element").escapeElement; function r(e) { this.value = e } r.prototype.toString = function () { return o("" + this.value) }, t.exports = { XmlText: r } }, { "./escape-element": 75 }], 78: [function (e, t, n) { "use strict"; n.byteLength = function (e) { var t = a(e), n = t[0], o = t[1]; return 3 * (n + o) / 4 - o }, n.toByteArray = function (e) { var t, n, o = a(e), s = o[0], c = o[1], u = new i(function (e, t, n) { return 3 * (t + n) / 4 - n }(0, s, c)), l = 0, p = c > 0 ? s - 4 : s; for (n = 0; n < p; n += 4)t = r[e.charCodeAt(n)] << 18 | r[e.charCodeAt(n + 1)] << 12 | r[e.charCodeAt(n + 2)] << 6 | r[e.charCodeAt(n + 3)], u[l++] = t >> 16 & 255, u[l++] = t >> 8 & 255, u[l++] = 255 & t; return 2 === c && (t = r[e.charCodeAt(n)] << 2 | r[e.charCodeAt(n + 1)] >> 4, u[l++] = 255 & t), 1 === c && (t = r[e.charCodeAt(n)] << 10 | r[e.charCodeAt(n + 1)] << 4 | r[e.charCodeAt(n + 2)] >> 2, u[l++] = t >> 8 & 255, u[l++] = 255 & t), u }, n.fromByteArray = function (e) { for (var t, n = e.length, r = n % 3, i = [], s = 16383, c = 0, a = n - r; c < a; c += s)i.push(u(e, c, c + s > a ? a : c + s)); return 1 === r ? (t = e[n - 1], i.push(o[t >> 2] + o[t << 4 & 63] + "==")) : 2 === r && (t = (e[n - 2] << 8) + e[n - 1], i.push(o[t >> 10] + o[t >> 4 & 63] + o[t << 2 & 63] + "=")), i.join("") }; for (var o = [], r = [], i = "undefined" != typeof Uint8Array ? Uint8Array : Array, s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", c = 0; c < 64; ++c)o[c] = s[c], r[s.charCodeAt(c)] = c; function a(e) { var t = e.length; if (t % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4"); var n = e.indexOf("="); return -1 === n && (n = t), [n, n === t ? 0 : 4 - n % 4] } function u(e, t, n) { for (var r, i, s = [], c = t; c < n; c += 3)r = (e[c] << 16 & 16711680) + (e[c + 1] << 8 & 65280) + (255 & e[c + 2]), s.push(o[(i = r) >> 18 & 63] + o[i >> 12 & 63] + o[i >> 6 & 63] + o[63 & i]); return s.join("") } r["-".charCodeAt(0)] = 62, r["_".charCodeAt(0)] = 63 }, {}], 79: [function (e, t, n) { }, {}], 80: [function (e, t, i) { (function (e) { (function () { !function (s) { var c = "object" == r(i) && i && !i.nodeType && i, a = "object" == r(t) && t && !t.nodeType && t, u = "object" == r(e) && e; u.global !== u && u.window !== u && u.self !== u || (s = u); var l, p, h = 2147483647, d = 36, f = 1, g = 26, m = 38, v = 700, y = 72, E = 128, S = "-", b = /^xn--/, C = /[^\x20-\x7E]/, T = /[\x2E\u3002\uFF0E\uFF61]/g, I = { overflow: "Overflow: input needs wider integers to process", "not-basic": "Illegal input >= 0x80 (not a basic code point)", "invalid-input": "Invalid input" }, A = d - f, _ = Math.floor, w = String.fromCharCode; function R(e) { throw RangeError(I[e]) } function N(e, t) { for (var n = e.length, o = []; n--;)o[n] = t(e[n]); return o } function k(e, t) { var n = e.split("@"), o = ""; return n.length > 1 && (o = n[0] + "@", e = n[1]), o + N((e = e.replace(T, ".")).split("."), t).join(".") } function O(e) { for (var t, n, o = [], r = 0, i = e.length; r < i;)(t = e.charCodeAt(r++)) >= 55296 && t <= 56319 && r < i ? 56320 == (64512 & (n = e.charCodeAt(r++))) ? o.push(((1023 & t) << 10) + (1023 & n) + 65536) : (o.push(t), r--) : o.push(t); return o } function L(e) { return N(e, (function (e) { var t = ""; return e > 65535 && (t += w((e -= 65536) >>> 10 & 1023 | 55296), e = 56320 | 1023 & e), t += w(e) })).join("") } function D(e, t) { return e + 22 + 75 * (e < 26) - ((0 != t) << 5) } function P(e, t, n) { var o = 0; for (e = n ? _(e / v) : e >> 1, e += _(e / t); e > A * g >> 1; o += d)e = _(e / A); return _(o + (A + 1) * e / (e + m)) } function x(e) { var t, n, o, r, i, s, c, a, u, l, p, m = [], v = e.length, b = 0, C = E, T = y; for ((n = e.lastIndexOf(S)) < 0 && (n = 0), o = 0; o < n; ++o)e.charCodeAt(o) >= 128 && R("not-basic"), m.push(e.charCodeAt(o)); for (r = n > 0 ? n + 1 : 0; r < v;) { for (i = b, s = 1, c = d; r >= v && R("invalid-input"), ((a = (p = e.charCodeAt(r++)) - 48 < 10 ? p - 22 : p - 65 < 26 ? p - 65 : p - 97 < 26 ? p - 97 : d) >= d || a > _((h - b) / s)) && R("overflow"), b += a * s, !(a < (u = c <= T ? f : c >= T + g ? g : c - T)); c += d)s > _(h / (l = d - u)) && R("overflow"), s *= l; T = P(b - i, t = m.length + 1, 0 == i), _(b / t) > h - C && R("overflow"), C += _(b / t), b %= t, m.splice(b++, 0, C) } return L(m) } function M(e) { var t, n, o, r, i, s, c, a, u, l, p, m, v, b, C, T = []; for (m = (e = O(e)).length, t = E, n = 0, i = y, s = 0; s < m; ++s)(p = e[s]) < 128 && T.push(w(p)); for (o = r = T.length, r && T.push(S); o < m;) { for (c = h, s = 0; s < m; ++s)(p = e[s]) >= t && p < c && (c = p); for (c - t > _((h - n) / (v = o + 1)) && R("overflow"), n += (c - t) * v, t = c, s = 0; s < m; ++s)if ((p = e[s]) < t && ++n > h && R("overflow"), p == t) { for (a = n, u = d; !(a < (l = u <= i ? f : u >= i + g ? g : u - i)); u += d)C = a - l, b = d - l, T.push(w(D(l + C % b, 0))), a = _(C / b); T.push(w(D(a, 0))), i = P(n, v, o == r), n = 0, ++o } ++n, ++t } return T.join("") } if (l = { version: "1.3.2", ucs2: { decode: O, encode: L }, decode: x, encode: M, toASCII: function (e) { return k(e, (function (e) { return C.test(e) ? "xn--" + M(e) : e })) }, toUnicode: function (e) { return k(e, (function (e) { return b.test(e) ? x(e.slice(4).toLowerCase()) : e })) } }, "object" == r(n.amdO) && n.amdO) void 0 === (o = function () { return l }.call(i, n, i, t)) || (t.exports = o); else if (c && a) if (t.exports == c) a.exports = l; else for (p in l) l.hasOwnProperty(p) && (c[p] = l[p]); else s.punycode = l }(this) }).call(this) }).call(this, void 0 !== n.g ? n.g : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}) }, {}], 81: [function (e, t, o) { (function (t, n) { (function () { "use strict"; var n = e("base64-js"), r = e("ieee754"), i = e("isarray"); function s() { return a.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823 } function c(e, t) { if (s() < t) throw new RangeError("Invalid typed array length"); return a.TYPED_ARRAY_SUPPORT ? (e = new Uint8Array(t)).__proto__ = a.prototype : (null === e && (e = new a(t)), e.length = t), e } function a(e, t, n) { if (!(a.TYPED_ARRAY_SUPPORT || this instanceof a)) return new a(e, t, n); if ("number" == typeof e) { if ("string" == typeof t) throw new Error("If encoding is specified then the first argument must be a string"); return p(this, e) } return u(this, e, t, n) } function u(e, t, n, o) { if ("number" == typeof t) throw new TypeError('"value" argument must not be a number'); return "undefined" != typeof ArrayBuffer && t instanceof ArrayBuffer ? function (e, t, n, o) { if (t.byteLength, n < 0 || t.byteLength < n) throw new RangeError("'offset' is out of bounds"); if (t.byteLength < n + (o || 0)) throw new RangeError("'length' is out of bounds"); return t = void 0 === n && void 0 === o ? new Uint8Array(t) : void 0 === o ? new Uint8Array(t, n) : new Uint8Array(t, n, o), a.TYPED_ARRAY_SUPPORT ? (e = t).__proto__ = a.prototype : e = h(e, t), e }(e, t, n, o) : "string" == typeof t ? function (e, t, n) { if ("string" == typeof n && "" !== n || (n = "utf8"), !a.isEncoding(n)) throw new TypeError('"encoding" must be a valid string encoding'); var o = 0 | f(t, n), r = (e = c(e, o)).write(t, n); return r !== o && (e = e.slice(0, r)), e }(e, t, n) : function (e, t) { if (a.isBuffer(t)) { var n = 0 | d(t.length); return 0 === (e = c(e, n)).length || t.copy(e, 0, 0, n), e } if (t) { if ("undefined" != typeof ArrayBuffer && t.buffer instanceof ArrayBuffer || "length" in t) return "number" != typeof t.length || (o = t.length) != o ? c(e, 0) : h(e, t); if ("Buffer" === t.type && i(t.data)) return h(e, t.data) } var o; throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.") }(e, t) } function l(e) { if ("number" != typeof e) throw new TypeError('"size" argument must be a number'); if (e < 0) throw new RangeError('"size" argument must not be negative') } function p(e, t) { if (l(t), e = c(e, t < 0 ? 0 : 0 | d(t)), !a.TYPED_ARRAY_SUPPORT) for (var n = 0; n < t; ++n)e[n] = 0; return e } function h(e, t) { var n = t.length < 0 ? 0 : 0 | d(t.length); e = c(e, n); for (var o = 0; o < n; o += 1)e[o] = 255 & t[o]; return e } function d(e) { if (e >= s()) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + s().toString(16) + " bytes"); return 0 | e } function f(e, t) { if (a.isBuffer(e)) return e.length; if ("undefined" != typeof ArrayBuffer && "function" == typeof ArrayBuffer.isView && (ArrayBuffer.isView(e) || e instanceof ArrayBuffer)) return e.byteLength; "string" != typeof e && (e = "" + e); var n = e.length; if (0 === n) return 0; for (var o = !1; ;)switch (t) { case "ascii": case "latin1": case "binary": return n; case "utf8": case "utf-8": case void 0: return j(e).length; case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return 2 * n; case "hex": return n >>> 1; case "base64": return B(e).length; default: if (o) return j(e).length; t = ("" + t).toLowerCase(), o = !0 } } function g(e, t, n) { var o = !1; if ((void 0 === t || t < 0) && (t = 0), t > this.length) return ""; if ((void 0 === n || n > this.length) && (n = this.length), n <= 0) return ""; if ((n >>>= 0) <= (t >>>= 0)) return ""; for (e || (e = "utf8"); ;)switch (e) { case "hex": return k(this, t, n); case "utf8": case "utf-8": return _(this, t, n); case "ascii": return R(this, t, n); case "latin1": case "binary": return N(this, t, n); case "base64": return A(this, t, n); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return O(this, t, n); default: if (o) throw new TypeError("Unknown encoding: " + e); e = (e + "").toLowerCase(), o = !0 } } function m(e, t, n) { var o = e[t]; e[t] = e[n], e[n] = o } function v(e, t, n, o, r) { if (0 === e.length) return -1; if ("string" == typeof n ? (o = n, n = 0) : n > 2147483647 ? n = 2147483647 : n < -2147483648 && (n = -2147483648), n = +n, isNaN(n) && (n = r ? 0 : e.length - 1), n < 0 && (n = e.length + n), n >= e.length) { if (r) return -1; n = e.length - 1 } else if (n < 0) { if (!r) return -1; n = 0 } if ("string" == typeof t && (t = a.from(t, o)), a.isBuffer(t)) return 0 === t.length ? -1 : y(e, t, n, o, r); if ("number" == typeof t) return t &= 255, a.TYPED_ARRAY_SUPPORT && "function" == typeof Uint8Array.prototype.indexOf ? r ? Uint8Array.prototype.indexOf.call(e, t, n) : Uint8Array.prototype.lastIndexOf.call(e, t, n) : y(e, [t], n, o, r); throw new TypeError("val must be string, number or Buffer") } function y(e, t, n, o, r) { var i, s = 1, c = e.length, a = t.length; if (void 0 !== o && ("ucs2" === (o = String(o).toLowerCase()) || "ucs-2" === o || "utf16le" === o || "utf-16le" === o)) { if (e.length < 2 || t.length < 2) return -1; s = 2, c /= 2, a /= 2, n /= 2 } function u(e, t) { return 1 === s ? e[t] : e.readUInt16BE(t * s) } if (r) { var l = -1; for (i = n; i < c; i++)if (u(e, i) === u(t, -1 === l ? 0 : i - l)) { if (-1 === l && (l = i), i - l + 1 === a) return l * s } else -1 !== l && (i -= i - l), l = -1 } else for (n + a > c && (n = c - a), i = n; i >= 0; i--) { for (var p = !0, h = 0; h < a; h++)if (u(e, i + h) !== u(t, h)) { p = !1; break } if (p) return i } return -1 } function E(e, t, n, o) { n = Number(n) || 0; var r = e.length - n; o ? (o = Number(o)) > r && (o = r) : o = r; var i = t.length; if (i % 2 != 0) throw new TypeError("Invalid hex string"); o > i / 2 && (o = i / 2); for (var s = 0; s < o; ++s) { var c = parseInt(t.substr(2 * s, 2), 16); if (isNaN(c)) return s; e[n + s] = c } return s } function S(e, t, n, o) { return V(j(t, e.length - n), e, n, o) } function b(e, t, n, o) { return V(function (e) { for (var t = [], n = 0; n < e.length; ++n)t.push(255 & e.charCodeAt(n)); return t }(t), e, n, o) } function C(e, t, n, o) { return b(e, t, n, o) } function T(e, t, n, o) { return V(B(t), e, n, o) } function I(e, t, n, o) { return V(function (e, t) { for (var n, o, r, i = [], s = 0; s < e.length && !((t -= 2) < 0); ++s)o = (n = e.charCodeAt(s)) >> 8, r = n % 256, i.push(r), i.push(o); return i }(t, e.length - n), e, n, o) } function A(e, t, o) { return 0 === t && o === e.length ? n.fromByteArray(e) : n.fromByteArray(e.slice(t, o)) } function _(e, t, n) { n = Math.min(e.length, n); for (var o = [], r = t; r < n;) { var i, s, c, a, u = e[r], l = null, p = u > 239 ? 4 : u > 223 ? 3 : u > 191 ? 2 : 1; if (r + p <= n) switch (p) { case 1: u < 128 && (l = u); break; case 2: 128 == (192 & (i = e[r + 1])) && (a = (31 & u) << 6 | 63 & i) > 127 && (l = a); break; case 3: i = e[r + 1], s = e[r + 2], 128 == (192 & i) && 128 == (192 & s) && (a = (15 & u) << 12 | (63 & i) << 6 | 63 & s) > 2047 && (a < 55296 || a > 57343) && (l = a); break; case 4: i = e[r + 1], s = e[r + 2], c = e[r + 3], 128 == (192 & i) && 128 == (192 & s) && 128 == (192 & c) && (a = (15 & u) << 18 | (63 & i) << 12 | (63 & s) << 6 | 63 & c) > 65535 && a < 1114112 && (l = a) }null === l ? (l = 65533, p = 1) : l > 65535 && (l -= 65536, o.push(l >>> 10 & 1023 | 55296), l = 56320 | 1023 & l), o.push(l), r += p } return function (e) { var t = e.length; if (t <= w) return String.fromCharCode.apply(String, e); for (var n = "", o = 0; o < t;)n += String.fromCharCode.apply(String, e.slice(o, o += w)); return n }(o) } o.Buffer = a, o.SlowBuffer = function (e) { return +e != e && (e = 0), a.alloc(+e) }, o.INSPECT_MAX_BYTES = 50, a.TYPED_ARRAY_SUPPORT = void 0 !== t.TYPED_ARRAY_SUPPORT ? t.TYPED_ARRAY_SUPPORT : function () { try { var e = new Uint8Array(1); return e.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }, 42 === e.foo() && "function" == typeof e.subarray && 0 === e.subarray(1, 1).byteLength } catch (e) { return !1 } }(), o.kMaxLength = s(), a.poolSize = 8192, a._augment = function (e) { return e.__proto__ = a.prototype, e }, a.from = function (e, t, n) { return u(null, e, t, n) }, a.TYPED_ARRAY_SUPPORT && (a.prototype.__proto__ = Uint8Array.prototype, a.__proto__ = Uint8Array, "undefined" != typeof Symbol && Symbol.species && a[Symbol.species] === a && Object.defineProperty(a, Symbol.species, { value: null, configurable: !0 })), a.alloc = function (e, t, n) { return function (e, t, n, o) { return l(t), t <= 0 ? c(e, t) : void 0 !== n ? "string" == typeof o ? c(e, t).fill(n, o) : c(e, t).fill(n) : c(e, t) }(null, e, t, n) }, a.allocUnsafe = function (e) { return p(null, e) }, a.allocUnsafeSlow = function (e) { return p(null, e) }, a.isBuffer = function (e) { return !(null == e || !e._isBuffer) }, a.compare = function (e, t) { if (!a.isBuffer(e) || !a.isBuffer(t)) throw new TypeError("Arguments must be Buffers"); if (e === t) return 0; for (var n = e.length, o = t.length, r = 0, i = Math.min(n, o); r < i; ++r)if (e[r] !== t[r]) { n = e[r], o = t[r]; break } return n < o ? -1 : o < n ? 1 : 0 }, a.isEncoding = function (e) { switch (String(e).toLowerCase()) { case "hex": case "utf8": case "utf-8": case "ascii": case "latin1": case "binary": case "base64": case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return !0; default: return !1 } }, a.concat = function (e, t) { if (!i(e)) throw new TypeError('"list" argument must be an Array of Buffers'); if (0 === e.length) return a.alloc(0); var n; if (void 0 === t) for (t = 0, n = 0; n < e.length; ++n)t += e[n].length; var o = a.allocUnsafe(t), r = 0; for (n = 0; n < e.length; ++n) { var s = e[n]; if (!a.isBuffer(s)) throw new TypeError('"list" argument must be an Array of Buffers'); s.copy(o, r), r += s.length } return o }, a.byteLength = f, a.prototype._isBuffer = !0, a.prototype.swap16 = function () { var e = this.length; if (e % 2 != 0) throw new RangeError("Buffer size must be a multiple of 16-bits"); for (var t = 0; t < e; t += 2)m(this, t, t + 1); return this }, a.prototype.swap32 = function () { var e = this.length; if (e % 4 != 0) throw new RangeError("Buffer size must be a multiple of 32-bits"); for (var t = 0; t < e; t += 4)m(this, t, t + 3), m(this, t + 1, t + 2); return this }, a.prototype.swap64 = function () { var e = this.length; if (e % 8 != 0) throw new RangeError("Buffer size must be a multiple of 64-bits"); for (var t = 0; t < e; t += 8)m(this, t, t + 7), m(this, t + 1, t + 6), m(this, t + 2, t + 5), m(this, t + 3, t + 4); return this }, a.prototype.toString = function () { var e = 0 | this.length; return 0 === e ? "" : 0 === arguments.length ? _(this, 0, e) : g.apply(this, arguments) }, a.prototype.equals = function (e) { if (!a.isBuffer(e)) throw new TypeError("Argument must be a Buffer"); return this === e || 0 === a.compare(this, e) }, a.prototype.inspect = function () { var e = "", t = o.INSPECT_MAX_BYTES; return this.length > 0 && (e = this.toString("hex", 0, t).match(/.{2}/g).join(" "), this.length > t && (e += " ... ")), "" }, a.prototype.compare = function (e, t, n, o, r) { if (!a.isBuffer(e)) throw new TypeError("Argument must be a Buffer"); if (void 0 === t && (t = 0), void 0 === n && (n = e ? e.length : 0), void 0 === o && (o = 0), void 0 === r && (r = this.length), t < 0 || n > e.length || o < 0 || r > this.length) throw new RangeError("out of range index"); if (o >= r && t >= n) return 0; if (o >= r) return -1; if (t >= n) return 1; if (this === e) return 0; for (var i = (r >>>= 0) - (o >>>= 0), s = (n >>>= 0) - (t >>>= 0), c = Math.min(i, s), u = this.slice(o, r), l = e.slice(t, n), p = 0; p < c; ++p)if (u[p] !== l[p]) { i = u[p], s = l[p]; break } return i < s ? -1 : s < i ? 1 : 0 }, a.prototype.includes = function (e, t, n) { return -1 !== this.indexOf(e, t, n) }, a.prototype.indexOf = function (e, t, n) { return v(this, e, t, n, !0) }, a.prototype.lastIndexOf = function (e, t, n) { return v(this, e, t, n, !1) }, a.prototype.write = function (e, t, n, o) { if (void 0 === t) o = "utf8", n = this.length, t = 0; else if (void 0 === n && "string" == typeof t) o = t, n = this.length, t = 0; else { if (!isFinite(t)) throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); t |= 0, isFinite(n) ? (n |= 0, void 0 === o && (o = "utf8")) : (o = n, n = void 0) } var r = this.length - t; if ((void 0 === n || n > r) && (n = r), e.length > 0 && (n < 0 || t < 0) || t > this.length) throw new RangeError("Attempt to write outside buffer bounds"); o || (o = "utf8"); for (var i = !1; ;)switch (o) { case "hex": return E(this, e, t, n); case "utf8": case "utf-8": return S(this, e, t, n); case "ascii": return b(this, e, t, n); case "latin1": case "binary": return C(this, e, t, n); case "base64": return T(this, e, t, n); case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return I(this, e, t, n); default: if (i) throw new TypeError("Unknown encoding: " + o); o = ("" + o).toLowerCase(), i = !0 } }, a.prototype.toJSON = function () { return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) } }; var w = 4096; function R(e, t, n) { var o = ""; n = Math.min(e.length, n); for (var r = t; r < n; ++r)o += String.fromCharCode(127 & e[r]); return o } function N(e, t, n) { var o = ""; n = Math.min(e.length, n); for (var r = t; r < n; ++r)o += String.fromCharCode(e[r]); return o } function k(e, t, n) { var o, r = e.length; (!t || t < 0) && (t = 0), (!n || n < 0 || n > r) && (n = r); for (var i = "", s = t; s < n; ++s)i += (o = e[s]) < 16 ? "0" + o.toString(16) : o.toString(16); return i } function O(e, t, n) { for (var o = e.slice(t, n), r = "", i = 0; i < o.length; i += 2)r += String.fromCharCode(o[i] + 256 * o[i + 1]); return r } function L(e, t, n) { if (e % 1 != 0 || e < 0) throw new RangeError("offset is not uint"); if (e + t > n) throw new RangeError("Trying to access beyond buffer length") } function D(e, t, n, o, r, i) { if (!a.isBuffer(e)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (t > r || t < i) throw new RangeError('"value" argument is out of bounds'); if (n + o > e.length) throw new RangeError("Index out of range") } function P(e, t, n, o) { t < 0 && (t = 65535 + t + 1); for (var r = 0, i = Math.min(e.length - n, 2); r < i; ++r)e[n + r] = (t & 255 << 8 * (o ? r : 1 - r)) >>> 8 * (o ? r : 1 - r) } function x(e, t, n, o) { t < 0 && (t = 4294967295 + t + 1); for (var r = 0, i = Math.min(e.length - n, 4); r < i; ++r)e[n + r] = t >>> 8 * (o ? r : 3 - r) & 255 } function M(e, t, n, o, r, i) { if (n + o > e.length) throw new RangeError("Index out of range"); if (n < 0) throw new RangeError("Index out of range") } function U(e, t, n, o, i) { return i || M(e, 0, n, 4), r.write(e, t, n, o, 23, 4), n + 4 } function q(e, t, n, o, i) { return i || M(e, 0, n, 8), r.write(e, t, n, o, 52, 8), n + 8 } a.prototype.slice = function (e, t) { var n, o = this.length; if ((e = ~~e) < 0 ? (e += o) < 0 && (e = 0) : e > o && (e = o), (t = void 0 === t ? o : ~~t) < 0 ? (t += o) < 0 && (t = 0) : t > o && (t = o), t < e && (t = e), a.TYPED_ARRAY_SUPPORT) (n = this.subarray(e, t)).__proto__ = a.prototype; else { var r = t - e; n = new a(r, void 0); for (var i = 0; i < r; ++i)n[i] = this[i + e] } return n }, a.prototype.readUIntLE = function (e, t, n) { e |= 0, t |= 0, n || L(e, t, this.length); for (var o = this[e], r = 1, i = 0; ++i < t && (r *= 256);)o += this[e + i] * r; return o }, a.prototype.readUIntBE = function (e, t, n) { e |= 0, t |= 0, n || L(e, t, this.length); for (var o = this[e + --t], r = 1; t > 0 && (r *= 256);)o += this[e + --t] * r; return o }, a.prototype.readUInt8 = function (e, t) { return t || L(e, 1, this.length), this[e] }, a.prototype.readUInt16LE = function (e, t) { return t || L(e, 2, this.length), this[e] | this[e + 1] << 8 }, a.prototype.readUInt16BE = function (e, t) { return t || L(e, 2, this.length), this[e] << 8 | this[e + 1] }, a.prototype.readUInt32LE = function (e, t) { return t || L(e, 4, this.length), (this[e] | this[e + 1] << 8 | this[e + 2] << 16) + 16777216 * this[e + 3] }, a.prototype.readUInt32BE = function (e, t) { return t || L(e, 4, this.length), 16777216 * this[e] + (this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3]) }, a.prototype.readIntLE = function (e, t, n) { e |= 0, t |= 0, n || L(e, t, this.length); for (var o = this[e], r = 1, i = 0; ++i < t && (r *= 256);)o += this[e + i] * r; return o >= (r *= 128) && (o -= Math.pow(2, 8 * t)), o }, a.prototype.readIntBE = function (e, t, n) { e |= 0, t |= 0, n || L(e, t, this.length); for (var o = t, r = 1, i = this[e + --o]; o > 0 && (r *= 256);)i += this[e + --o] * r; return i >= (r *= 128) && (i -= Math.pow(2, 8 * t)), i }, a.prototype.readInt8 = function (e, t) { return t || L(e, 1, this.length), 128 & this[e] ? -1 * (255 - this[e] + 1) : this[e] }, a.prototype.readInt16LE = function (e, t) { t || L(e, 2, this.length); var n = this[e] | this[e + 1] << 8; return 32768 & n ? 4294901760 | n : n }, a.prototype.readInt16BE = function (e, t) { t || L(e, 2, this.length); var n = this[e + 1] | this[e] << 8; return 32768 & n ? 4294901760 | n : n }, a.prototype.readInt32LE = function (e, t) { return t || L(e, 4, this.length), this[e] | this[e + 1] << 8 | this[e + 2] << 16 | this[e + 3] << 24 }, a.prototype.readInt32BE = function (e, t) { return t || L(e, 4, this.length), this[e] << 24 | this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3] }, a.prototype.readFloatLE = function (e, t) { return t || L(e, 4, this.length), r.read(this, e, !0, 23, 4) }, a.prototype.readFloatBE = function (e, t) { return t || L(e, 4, this.length), r.read(this, e, !1, 23, 4) }, a.prototype.readDoubleLE = function (e, t) { return t || L(e, 8, this.length), r.read(this, e, !0, 52, 8) }, a.prototype.readDoubleBE = function (e, t) { return t || L(e, 8, this.length), r.read(this, e, !1, 52, 8) }, a.prototype.writeUIntLE = function (e, t, n, o) { e = +e, t |= 0, n |= 0, o || D(this, e, t, n, Math.pow(2, 8 * n) - 1, 0); var r = 1, i = 0; for (this[t] = 255 & e; ++i < n && (r *= 256);)this[t + i] = e / r & 255; return t + n }, a.prototype.writeUIntBE = function (e, t, n, o) { e = +e, t |= 0, n |= 0, o || D(this, e, t, n, Math.pow(2, 8 * n) - 1, 0); var r = n - 1, i = 1; for (this[t + r] = 255 & e; --r >= 0 && (i *= 256);)this[t + r] = e / i & 255; return t + n }, a.prototype.writeUInt8 = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 1, 255, 0), a.TYPED_ARRAY_SUPPORT || (e = Math.floor(e)), this[t] = 255 & e, t + 1 }, a.prototype.writeUInt16LE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 2, 65535, 0), a.TYPED_ARRAY_SUPPORT ? (this[t] = 255 & e, this[t + 1] = e >>> 8) : P(this, e, t, !0), t + 2 }, a.prototype.writeUInt16BE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 2, 65535, 0), a.TYPED_ARRAY_SUPPORT ? (this[t] = e >>> 8, this[t + 1] = 255 & e) : P(this, e, t, !1), t + 2 }, a.prototype.writeUInt32LE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 4, 4294967295, 0), a.TYPED_ARRAY_SUPPORT ? (this[t + 3] = e >>> 24, this[t + 2] = e >>> 16, this[t + 1] = e >>> 8, this[t] = 255 & e) : x(this, e, t, !0), t + 4 }, a.prototype.writeUInt32BE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 4, 4294967295, 0), a.TYPED_ARRAY_SUPPORT ? (this[t] = e >>> 24, this[t + 1] = e >>> 16, this[t + 2] = e >>> 8, this[t + 3] = 255 & e) : x(this, e, t, !1), t + 4 }, a.prototype.writeIntLE = function (e, t, n, o) { if (e = +e, t |= 0, !o) { var r = Math.pow(2, 8 * n - 1); D(this, e, t, n, r - 1, -r) } var i = 0, s = 1, c = 0; for (this[t] = 255 & e; ++i < n && (s *= 256);)e < 0 && 0 === c && 0 !== this[t + i - 1] && (c = 1), this[t + i] = (e / s >> 0) - c & 255; return t + n }, a.prototype.writeIntBE = function (e, t, n, o) { if (e = +e, t |= 0, !o) { var r = Math.pow(2, 8 * n - 1); D(this, e, t, n, r - 1, -r) } var i = n - 1, s = 1, c = 0; for (this[t + i] = 255 & e; --i >= 0 && (s *= 256);)e < 0 && 0 === c && 0 !== this[t + i + 1] && (c = 1), this[t + i] = (e / s >> 0) - c & 255; return t + n }, a.prototype.writeInt8 = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 1, 127, -128), a.TYPED_ARRAY_SUPPORT || (e = Math.floor(e)), e < 0 && (e = 255 + e + 1), this[t] = 255 & e, t + 1 }, a.prototype.writeInt16LE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 2, 32767, -32768), a.TYPED_ARRAY_SUPPORT ? (this[t] = 255 & e, this[t + 1] = e >>> 8) : P(this, e, t, !0), t + 2 }, a.prototype.writeInt16BE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 2, 32767, -32768), a.TYPED_ARRAY_SUPPORT ? (this[t] = e >>> 8, this[t + 1] = 255 & e) : P(this, e, t, !1), t + 2 }, a.prototype.writeInt32LE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 4, 2147483647, -2147483648), a.TYPED_ARRAY_SUPPORT ? (this[t] = 255 & e, this[t + 1] = e >>> 8, this[t + 2] = e >>> 16, this[t + 3] = e >>> 24) : x(this, e, t, !0), t + 4 }, a.prototype.writeInt32BE = function (e, t, n) { return e = +e, t |= 0, n || D(this, e, t, 4, 2147483647, -2147483648), e < 0 && (e = 4294967295 + e + 1), a.TYPED_ARRAY_SUPPORT ? (this[t] = e >>> 24, this[t + 1] = e >>> 16, this[t + 2] = e >>> 8, this[t + 3] = 255 & e) : x(this, e, t, !1), t + 4 }, a.prototype.writeFloatLE = function (e, t, n) { return U(this, e, t, !0, n) }, a.prototype.writeFloatBE = function (e, t, n) { return U(this, e, t, !1, n) }, a.prototype.writeDoubleLE = function (e, t, n) { return q(this, e, t, !0, n) }, a.prototype.writeDoubleBE = function (e, t, n) { return q(this, e, t, !1, n) }, a.prototype.copy = function (e, t, n, o) { if (n || (n = 0), o || 0 === o || (o = this.length), t >= e.length && (t = e.length), t || (t = 0), o > 0 && o < n && (o = n), o === n) return 0; if (0 === e.length || 0 === this.length) return 0; if (t < 0) throw new RangeError("targetStart out of bounds"); if (n < 0 || n >= this.length) throw new RangeError("sourceStart out of bounds"); if (o < 0) throw new RangeError("sourceEnd out of bounds"); o > this.length && (o = this.length), e.length - t < o - n && (o = e.length - t + n); var r, i = o - n; if (this === e && n < t && t < o) for (r = i - 1; r >= 0; --r)e[r + t] = this[r + n]; else if (i < 1e3 || !a.TYPED_ARRAY_SUPPORT) for (r = 0; r < i; ++r)e[r + t] = this[r + n]; else Uint8Array.prototype.set.call(e, this.subarray(n, n + i), t); return i }, a.prototype.fill = function (e, t, n, o) { if ("string" == typeof e) { if ("string" == typeof t ? (o = t, t = 0, n = this.length) : "string" == typeof n && (o = n, n = this.length), 1 === e.length) { var r = e.charCodeAt(0); r < 256 && (e = r) } if (void 0 !== o && "string" != typeof o) throw new TypeError("encoding must be a string"); if ("string" == typeof o && !a.isEncoding(o)) throw new TypeError("Unknown encoding: " + o) } else "number" == typeof e && (e &= 255); if (t < 0 || this.length < t || this.length < n) throw new RangeError("Out of range index"); if (n <= t) return this; var i; if (t >>>= 0, n = void 0 === n ? this.length : n >>> 0, e || (e = 0), "number" == typeof e) for (i = t; i < n; ++i)this[i] = e; else { var s = a.isBuffer(e) ? e : j(new a(e, o).toString()), c = s.length; for (i = 0; i < n - t; ++i)this[i + t] = s[i % c] } return this }; var F = /[^+\/0-9A-Za-z-_]/g; function j(e, t) { var n; t = t || 1 / 0; for (var o = e.length, r = null, i = [], s = 0; s < o; ++s) { if ((n = e.charCodeAt(s)) > 55295 && n < 57344) { if (!r) { if (n > 56319) { (t -= 3) > -1 && i.push(239, 191, 189); continue } if (s + 1 === o) { (t -= 3) > -1 && i.push(239, 191, 189); continue } r = n; continue } if (n < 56320) { (t -= 3) > -1 && i.push(239, 191, 189), r = n; continue } n = 65536 + (r - 55296 << 10 | n - 56320) } else r && (t -= 3) > -1 && i.push(239, 191, 189); if (r = null, n < 128) { if ((t -= 1) < 0) break; i.push(n) } else if (n < 2048) { if ((t -= 2) < 0) break; i.push(n >> 6 | 192, 63 & n | 128) } else if (n < 65536) { if ((t -= 3) < 0) break; i.push(n >> 12 | 224, n >> 6 & 63 | 128, 63 & n | 128) } else { if (!(n < 1114112)) throw new Error("Invalid code point"); if ((t -= 4) < 0) break; i.push(n >> 18 | 240, n >> 12 & 63 | 128, n >> 6 & 63 | 128, 63 & n | 128) } } return i } function B(e) { return n.toByteArray(function (e) { if ((e = function (e) { return e.trim ? e.trim() : e.replace(/^\s+|\s+$/g, "") }(e).replace(F, "")).length < 2) return ""; for (; e.length % 4 != 0;)e += "="; return e }(e)) } function V(e, t, n, o) { for (var r = 0; r < o && !(r + n >= t.length || r >= e.length); ++r)t[r + n] = e[r]; return r } }).call(this) }).call(this, void 0 !== n.g ? n.g : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, e("buffer").Buffer) }, { "base64-js": 78, buffer: 81, ieee754: 83, isarray: 84 }], 82: [function (e, t, n) { function o() { this._events = this._events || {}, this._maxListeners = this._maxListeners || void 0 } function i(e) { return "function" == typeof e } function s(e) { return "object" === r(e) && null !== e } function c(e) { return void 0 === e } t.exports = o, o.EventEmitter = o, o.prototype._events = void 0, o.prototype._maxListeners = void 0, o.defaultMaxListeners = 10, o.prototype.setMaxListeners = function (e) { if ("number" != typeof e || e < 0 || isNaN(e)) throw TypeError("n must be a positive number"); return this._maxListeners = e, this }, o.prototype.emit = function (e) { var t, n, o, r, a, u; if (this._events || (this._events = {}), "error" === e && (!this._events.error || s(this._events.error) && !this._events.error.length)) { if ((t = arguments[1]) instanceof Error) throw t; var l = new Error('Uncaught, unspecified "error" event. (' + t + ")"); throw l.context = t, l } if (c(n = this._events[e])) return !1; if (i(n)) switch (arguments.length) { case 1: n.call(this); break; case 2: n.call(this, arguments[1]); break; case 3: n.call(this, arguments[1], arguments[2]); break; default: r = Array.prototype.slice.call(arguments, 1), n.apply(this, r) } else if (s(n)) for (r = Array.prototype.slice.call(arguments, 1), o = (u = n.slice()).length, a = 0; a < o; a++)u[a].apply(this, r); return !0 }, o.prototype.addListener = function (e, t) { var n; if (!i(t)) throw TypeError("listener must be a function"); return this._events || (this._events = {}), this._events.newListener && this.emit("newListener", e, i(t.listener) ? t.listener : t), this._events[e] ? s(this._events[e]) ? this._events[e].push(t) : this._events[e] = [this._events[e], t] : this._events[e] = t, s(this._events[e]) && !this._events[e].warned && (n = c(this._maxListeners) ? o.defaultMaxListeners : this._maxListeners) && n > 0 && this._events[e].length > n && (this._events[e].warned = !0, console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.", this._events[e].length), "function" == typeof console.trace && console.trace()), this }, o.prototype.on = o.prototype.addListener, o.prototype.once = function (e, t) { if (!i(t)) throw TypeError("listener must be a function"); var n = !1; function o() { this.removeListener(e, o), n || (n = !0, t.apply(this, arguments)) } return o.listener = t, this.on(e, o), this }, o.prototype.removeListener = function (e, t) { var n, o, r, c; if (!i(t)) throw TypeError("listener must be a function"); if (!this._events || !this._events[e]) return this; if (r = (n = this._events[e]).length, o = -1, n === t || i(n.listener) && n.listener === t) delete this._events[e], this._events.removeListener && this.emit("removeListener", e, t); else if (s(n)) { for (c = r; c-- > 0;)if (n[c] === t || n[c].listener && n[c].listener === t) { o = c; break } if (o < 0) return this; 1 === n.length ? (n.length = 0, delete this._events[e]) : n.splice(o, 1), this._events.removeListener && this.emit("removeListener", e, t) } return this }, o.prototype.removeAllListeners = function (e) { var t, n; if (!this._events) return this; if (!this._events.removeListener) return 0 === arguments.length ? this._events = {} : this._events[e] && delete this._events[e], this; if (0 === arguments.length) { for (t in this._events) "removeListener" !== t && this.removeAllListeners(t); return this.removeAllListeners("removeListener"), this._events = {}, this } if (i(n = this._events[e])) this.removeListener(e, n); else if (n) for (; n.length;)this.removeListener(e, n[n.length - 1]); return delete this._events[e], this }, o.prototype.listeners = function (e) { return this._events && this._events[e] ? i(this._events[e]) ? [this._events[e]] : this._events[e].slice() : [] }, o.prototype.listenerCount = function (e) { if (this._events) { var t = this._events[e]; if (i(t)) return 1; if (t) return t.length } return 0 }, o.listenerCount = function (e, t) { return e.listenerCount(t) } }, {}], 83: [function (e, t, n) { n.read = function (e, t, n, o, r) { var i, s, c = 8 * r - o - 1, a = (1 << c) - 1, u = a >> 1, l = -7, p = n ? r - 1 : 0, h = n ? -1 : 1, d = e[t + p]; for (p += h, i = d & (1 << -l) - 1, d >>= -l, l += c; l > 0; i = 256 * i + e[t + p], p += h, l -= 8); for (s = i & (1 << -l) - 1, i >>= -l, l += o; l > 0; s = 256 * s + e[t + p], p += h, l -= 8); if (0 === i) i = 1 - u; else { if (i === a) return s ? NaN : 1 / 0 * (d ? -1 : 1); s += Math.pow(2, o), i -= u } return (d ? -1 : 1) * s * Math.pow(2, i - o) }, n.write = function (e, t, n, o, r, i) { var s, c, a, u = 8 * i - r - 1, l = (1 << u) - 1, p = l >> 1, h = 23 === r ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = o ? 0 : i - 1, f = o ? 1 : -1, g = t < 0 || 0 === t && 1 / t < 0 ? 1 : 0; for (t = Math.abs(t), isNaN(t) || t === 1 / 0 ? (c = isNaN(t) ? 1 : 0, s = l) : (s = Math.floor(Math.log(t) / Math.LN2), t * (a = Math.pow(2, -s)) < 1 && (s--, a *= 2), (t += s + p >= 1 ? h / a : h * Math.pow(2, 1 - p)) * a >= 2 && (s++, a /= 2), s + p >= l ? (c = 0, s = l) : s + p >= 1 ? (c = (t * a - 1) * Math.pow(2, r), s += p) : (c = t * Math.pow(2, p - 1) * Math.pow(2, r), s = 0)); r >= 8; e[n + d] = 255 & c, d += f, c /= 256, r -= 8); for (s = s << r | c, u += r; u > 0; e[n + d] = 255 & s, d += f, s /= 256, u -= 8); e[n + d - f] |= 128 * g } }, {}], 84: [function (e, t, n) { var o = {}.toString; t.exports = Array.isArray || function (e) { return "[object Array]" == o.call(e) } }, {}], 85: [function (e, t, n) { !function (e) { "use strict"; function t(e) { return null !== e && "[object Array]" === Object.prototype.toString.call(e) } function n(e) { return null !== e && "[object Object]" === Object.prototype.toString.call(e) } function o(e, r) { if (e === r) return !0; if (Object.prototype.toString.call(e) !== Object.prototype.toString.call(r)) return !1; if (!0 === t(e)) { if (e.length !== r.length) return !1; for (var i = 0; i < e.length; i++)if (!1 === o(e[i], r[i])) return !1; return !0 } if (!0 === n(e)) { var s = {}; for (var c in e) if (hasOwnProperty.call(e, c)) { if (!1 === o(e[c], r[c])) return !1; s[c] = !0 } for (var a in r) if (hasOwnProperty.call(r, a) && !0 !== s[a]) return !1; return !0 } return !1 } function r(e) { if ("" === e || !1 === e || null === e) return !0; if (t(e) && 0 === e.length) return !0; if (n(e)) { for (var o in e) if (e.hasOwnProperty(o)) return !1; return !0 } return !1 } var i; i = "function" == typeof String.prototype.trimLeft ? function (e) { return e.trimLeft() } : function (e) { return e.match(/^\s*(.*)/)[1] }; var s = 0, c = 1, a = 2, u = 3, l = 4, p = 6, h = 8, d = 9, f = "EOF", g = "UnquotedIdentifier", m = "QuotedIdentifier", v = "Rbracket", y = "Rparen", E = "Comma", S = "Colon", b = "Rbrace", C = "Number", T = "Current", I = "Expref", A = "Pipe", _ = "Or", w = "And", R = "EQ", N = "GT", k = "LT", O = "GTE", L = "LTE", D = "NE", P = "Flatten", x = "Star", M = "Filter", U = "Dot", q = "Not", F = "Lbrace", j = "Lbracket", B = "Lparen", V = "Literal", H = { ".": U, "*": x, ",": E, ":": S, "{": F, "}": b, "]": v, "(": B, ")": y, "@": T }, W = { "<": !0, ">": !0, "=": !0, "!": !0 }, G = { " ": !0, "\t": !0, "\n": !0 }; function z(e) { return e >= "0" && e <= "9" || "-" === e } function K() { } K.prototype = { tokenize: function (e) { var t, n, o, r, i = []; for (this._current = 0; this._current < e.length;)if ((r = e[this._current]) >= "a" && r <= "z" || r >= "A" && r <= "Z" || "_" === r) t = this._current, n = this._consumeUnquotedIdentifier(e), i.push({ type: g, value: n, start: t }); else if (void 0 !== H[e[this._current]]) i.push({ type: H[e[this._current]], value: e[this._current], start: this._current }), this._current++; else if (z(e[this._current])) o = this._consumeNumber(e), i.push(o); else if ("[" === e[this._current]) o = this._consumeLBracket(e), i.push(o); else if ('"' === e[this._current]) t = this._current, n = this._consumeQuotedIdentifier(e), i.push({ type: m, value: n, start: t }); else if ("'" === e[this._current]) t = this._current, n = this._consumeRawStringLiteral(e), i.push({ type: V, value: n, start: t }); else if ("`" === e[this._current]) { t = this._current; var s = this._consumeLiteral(e); i.push({ type: V, value: s, start: t }) } else if (void 0 !== W[e[this._current]]) i.push(this._consumeOperator(e)); else if (void 0 !== G[e[this._current]]) this._current++; else if ("&" === e[this._current]) t = this._current, this._current++, "&" === e[this._current] ? (this._current++, i.push({ type: w, value: "&&", start: t })) : i.push({ type: I, value: "&", start: t }); else { if ("|" !== e[this._current]) { var c = new Error("Unknown character:" + e[this._current]); throw c.name = "LexerError", c } t = this._current, this._current++, "|" === e[this._current] ? (this._current++, i.push({ type: _, value: "||", start: t })) : i.push({ type: A, value: "|", start: t }) } return i }, _consumeUnquotedIdentifier: function (e) { var t, n = this._current; for (this._current++; this._current < e.length && ((t = e[this._current]) >= "a" && t <= "z" || t >= "A" && t <= "Z" || t >= "0" && t <= "9" || "_" === t);)this._current++; return e.slice(n, this._current) }, _consumeQuotedIdentifier: function (e) { var t = this._current; this._current++; for (var n = e.length; '"' !== e[this._current] && this._current < n;) { var o = this._current; "\\" !== e[o] || "\\" !== e[o + 1] && '"' !== e[o + 1] ? o++ : o += 2, this._current = o } return this._current++, JSON.parse(e.slice(t, this._current)) }, _consumeRawStringLiteral: function (e) { var t = this._current; this._current++; for (var n = e.length; "'" !== e[this._current] && this._current < n;) { var o = this._current; "\\" !== e[o] || "\\" !== e[o + 1] && "'" !== e[o + 1] ? o++ : o += 2, this._current = o } return this._current++, e.slice(t + 1, this._current - 1).replace("\\'", "'") }, _consumeNumber: function (e) { var t = this._current; this._current++; for (var n = e.length; z(e[this._current]) && this._current < n;)this._current++; var o = parseInt(e.slice(t, this._current)); return { type: C, value: o, start: t } }, _consumeLBracket: function (e) { var t = this._current; return this._current++, "?" === e[this._current] ? (this._current++, { type: M, value: "[?", start: t }) : "]" === e[this._current] ? (this._current++, { type: P, value: "[]", start: t }) : { type: j, value: "[", start: t } }, _consumeOperator: function (e) { var t = this._current, n = e[t]; return this._current++, "!" === n ? "=" === e[this._current] ? (this._current++, { type: D, value: "!=", start: t }) : { type: q, value: "!", start: t } : "<" === n ? "=" === e[this._current] ? (this._current++, { type: L, value: "<=", start: t }) : { type: k, value: "<", start: t } : ">" === n ? "=" === e[this._current] ? (this._current++, { type: O, value: ">=", start: t }) : { type: N, value: ">", start: t } : "=" === n && "=" === e[this._current] ? (this._current++, { type: R, value: "==", start: t }) : void 0 }, _consumeLiteral: function (e) { this._current++; for (var t, n = this._current, o = e.length; "`" !== e[this._current] && this._current < o;) { var r = this._current; "\\" !== e[r] || "\\" !== e[r + 1] && "`" !== e[r + 1] ? r++ : r += 2, this._current = r } var s = i(e.slice(n, this._current)); return s = s.replace("\\`", "`"), t = this._looksLikeJSON(s) ? JSON.parse(s) : JSON.parse('"' + s + '"'), this._current++, t }, _looksLikeJSON: function (e) { if ("" === e) return !1; if ('[{"'.indexOf(e[0]) >= 0) return !0; if (["true", "false", "null"].indexOf(e) >= 0) return !0; if (!("-0123456789".indexOf(e[0]) >= 0)) return !1; try { return JSON.parse(e), !0 } catch (e) { return !1 } } }; var Y = {}; function X() { } function J(e) { this.runtime = e } function Q(e) { this._interpreter = e, this.functionTable = { abs: { _func: this._functionAbs, _signature: [{ types: [s] }] }, avg: { _func: this._functionAvg, _signature: [{ types: [h] }] }, ceil: { _func: this._functionCeil, _signature: [{ types: [s] }] }, contains: { _func: this._functionContains, _signature: [{ types: [a, u] }, { types: [c] }] }, ends_with: { _func: this._functionEndsWith, _signature: [{ types: [a] }, { types: [a] }] }, floor: { _func: this._functionFloor, _signature: [{ types: [s] }] }, length: { _func: this._functionLength, _signature: [{ types: [a, u, l] }] }, map: { _func: this._functionMap, _signature: [{ types: [p] }, { types: [u] }] }, max: { _func: this._functionMax, _signature: [{ types: [h, d] }] }, merge: { _func: this._functionMerge, _signature: [{ types: [l], variadic: !0 }] }, max_by: { _func: this._functionMaxBy, _signature: [{ types: [u] }, { types: [p] }] }, sum: { _func: this._functionSum, _signature: [{ types: [h] }] }, starts_with: { _func: this._functionStartsWith, _signature: [{ types: [a] }, { types: [a] }] }, min: { _func: this._functionMin, _signature: [{ types: [h, d] }] }, min_by: { _func: this._functionMinBy, _signature: [{ types: [u] }, { types: [p] }] }, type: { _func: this._functionType, _signature: [{ types: [c] }] }, keys: { _func: this._functionKeys, _signature: [{ types: [l] }] }, values: { _func: this._functionValues, _signature: [{ types: [l] }] }, sort: { _func: this._functionSort, _signature: [{ types: [d, h] }] }, sort_by: { _func: this._functionSortBy, _signature: [{ types: [u] }, { types: [p] }] }, join: { _func: this._functionJoin, _signature: [{ types: [a] }, { types: [d] }] }, reverse: { _func: this._functionReverse, _signature: [{ types: [a, u] }] }, to_array: { _func: this._functionToArray, _signature: [{ types: [c] }] }, to_string: { _func: this._functionToString, _signature: [{ types: [c] }] }, to_number: { _func: this._functionToNumber, _signature: [{ types: [c] }] }, not_null: { _func: this._functionNotNull, _signature: [{ types: [c], variadic: !0 }] } } } Y[f] = 0, Y[g] = 0, Y[m] = 0, Y[v] = 0, Y[y] = 0, Y[E] = 0, Y[b] = 0, Y[C] = 0, Y[T] = 0, Y[I] = 0, Y[A] = 1, Y[_] = 2, Y[w] = 3, Y[R] = 5, Y[N] = 5, Y[k] = 5, Y[O] = 5, Y[L] = 5, Y[D] = 5, Y[P] = 9, Y[x] = 20, Y[M] = 21, Y[U] = 40, Y[q] = 45, Y[F] = 50, Y[j] = 55, Y[B] = 60, X.prototype = { parse: function (e) { this._loadTokens(e), this.index = 0; var t = this.expression(0); if (this._lookahead(0) !== f) { var n = this._lookaheadToken(0), o = new Error("Unexpected token type: " + n.type + ", value: " + n.value); throw o.name = "ParserError", o } return t }, _loadTokens: function (e) { var t = (new K).tokenize(e); t.push({ type: f, value: "", start: e.length }), this.tokens = t }, expression: function (e) { var t = this._lookaheadToken(0); this._advance(); for (var n = this.nud(t), o = this._lookahead(0); e < Y[o];)this._advance(), n = this.led(o, n), o = this._lookahead(0); return n }, _lookahead: function (e) { return this.tokens[this.index + e].type }, _lookaheadToken: function (e) { return this.tokens[this.index + e] }, _advance: function () { this.index++ }, nud: function (e) { var t, n; switch (e.type) { case V: return { type: "Literal", value: e.value }; case g: return { type: "Field", name: e.value }; case m: var o = { type: "Field", name: e.value }; if (this._lookahead(0) === B) throw new Error("Quoted identifier not allowed for function names."); return o; case q: return { type: "NotExpression", children: [t = this.expression(Y.Not)] }; case x: return t = null, { type: "ValueProjection", children: [{ type: "Identity" }, t = this._lookahead(0) === v ? { type: "Identity" } : this._parseProjectionRHS(Y.Star)] }; case M: return this.led(e.type, { type: "Identity" }); case F: return this._parseMultiselectHash(); case P: return { type: "Projection", children: [{ type: P, children: [{ type: "Identity" }] }, t = this._parseProjectionRHS(Y.Flatten)] }; case j: return this._lookahead(0) === C || this._lookahead(0) === S ? (t = this._parseIndexExpression(), this._projectIfSlice({ type: "Identity" }, t)) : this._lookahead(0) === x && this._lookahead(1) === v ? (this._advance(), this._advance(), { type: "Projection", children: [{ type: "Identity" }, t = this._parseProjectionRHS(Y.Star)] }) : this._parseMultiselectList(); case T: return { type: T }; case I: return { type: "ExpressionReference", children: [n = this.expression(Y.Expref)] }; case B: for (var r = []; this._lookahead(0) !== y;)this._lookahead(0) === T ? (n = { type: T }, this._advance()) : n = this.expression(0), r.push(n); return this._match(y), r[0]; default: this._errorToken(e) } }, led: function (e, t) { var n; switch (e) { case U: var o = Y.Dot; return this._lookahead(0) !== x ? { type: "Subexpression", children: [t, n = this._parseDotRHS(o)] } : (this._advance(), { type: "ValueProjection", children: [t, n = this._parseProjectionRHS(o)] }); case A: return n = this.expression(Y.Pipe), { type: A, children: [t, n] }; case _: return { type: "OrExpression", children: [t, n = this.expression(Y.Or)] }; case w: return { type: "AndExpression", children: [t, n = this.expression(Y.And)] }; case B: for (var r, i = t.name, s = []; this._lookahead(0) !== y;)this._lookahead(0) === T ? (r = { type: T }, this._advance()) : r = this.expression(0), this._lookahead(0) === E && this._match(E), s.push(r); return this._match(y), { type: "Function", name: i, children: s }; case M: var c = this.expression(0); return this._match(v), { type: "FilterProjection", children: [t, n = this._lookahead(0) === P ? { type: "Identity" } : this._parseProjectionRHS(Y.Filter), c] }; case P: return { type: "Projection", children: [{ type: P, children: [t] }, this._parseProjectionRHS(Y.Flatten)] }; case R: case D: case N: case O: case k: case L: return this._parseComparator(t, e); case j: var a = this._lookaheadToken(0); return a.type === C || a.type === S ? (n = this._parseIndexExpression(), this._projectIfSlice(t, n)) : (this._match(x), this._match(v), { type: "Projection", children: [t, n = this._parseProjectionRHS(Y.Star)] }); default: this._errorToken(this._lookaheadToken(0)) } }, _match: function (e) { if (this._lookahead(0) !== e) { var t = this._lookaheadToken(0), n = new Error("Expected " + e + ", got: " + t.type); throw n.name = "ParserError", n } this._advance() }, _errorToken: function (e) { var t = new Error("Invalid token (" + e.type + '): "' + e.value + '"'); throw t.name = "ParserError", t }, _parseIndexExpression: function () { if (this._lookahead(0) === S || this._lookahead(1) === S) return this._parseSliceExpression(); var e = { type: "Index", value: this._lookaheadToken(0).value }; return this._advance(), this._match(v), e }, _projectIfSlice: function (e, t) { var n = { type: "IndexExpression", children: [e, t] }; return "Slice" === t.type ? { type: "Projection", children: [n, this._parseProjectionRHS(Y.Star)] } : n }, _parseSliceExpression: function () { for (var e = [null, null, null], t = 0, n = this._lookahead(0); n !== v && t < 3;) { if (n === S) t++, this._advance(); else { if (n !== C) { var o = this._lookahead(0), r = new Error("Syntax error, unexpected token: " + o.value + "(" + o.type + ")"); throw r.name = "Parsererror", r } e[t] = this._lookaheadToken(0).value, this._advance() } n = this._lookahead(0) } return this._match(v), { type: "Slice", children: e } }, _parseComparator: function (e, t) { return { type: "Comparator", name: t, children: [e, this.expression(Y[t])] } }, _parseDotRHS: function (e) { var t = this._lookahead(0); return [g, m, x].indexOf(t) >= 0 ? this.expression(e) : t === j ? (this._match(j), this._parseMultiselectList()) : t === F ? (this._match(F), this._parseMultiselectHash()) : void 0 }, _parseProjectionRHS: function (e) { var t; if (Y[this._lookahead(0)] < 10) t = { type: "Identity" }; else if (this._lookahead(0) === j) t = this.expression(e); else if (this._lookahead(0) === M) t = this.expression(e); else { if (this._lookahead(0) !== U) { var n = this._lookaheadToken(0), o = new Error("Sytanx error, unexpected token: " + n.value + "(" + n.type + ")"); throw o.name = "ParserError", o } this._match(U), t = this._parseDotRHS(e) } return t }, _parseMultiselectList: function () { for (var e = []; this._lookahead(0) !== v;) { var t = this.expression(0); if (e.push(t), this._lookahead(0) === E && (this._match(E), this._lookahead(0) === v)) throw new Error("Unexpected token Rbracket") } return this._match(v), { type: "MultiSelectList", children: e } }, _parseMultiselectHash: function () { for (var e, t, n, o = [], r = [g, m]; ;) { if (e = this._lookaheadToken(0), r.indexOf(e.type) < 0) throw new Error("Expecting an identifier token, got: " + e.type); if (t = e.value, this._advance(), this._match(S), n = { type: "KeyValuePair", name: t, value: this.expression(0) }, o.push(n), this._lookahead(0) === E) this._match(E); else if (this._lookahead(0) === b) { this._match(b); break } } return { type: "MultiSelectHash", children: o } } }, J.prototype = { search: function (e, t) { return this.visit(e, t) }, visit: function (e, i) { var s, c, a, u, l, p, h, d, f; switch (e.type) { case "Field": return null === i ? null : n(i) ? void 0 === (p = i[e.name]) ? null : p : null; case "Subexpression": for (a = this.visit(e.children[0], i), f = 1; f < e.children.length; f++)if (null === (a = this.visit(e.children[1], a))) return null; return a; case "IndexExpression": return h = this.visit(e.children[0], i), this.visit(e.children[1], h); case "Index": if (!t(i)) return null; var g = e.value; return g < 0 && (g = i.length + g), void 0 === (a = i[g]) && (a = null), a; case "Slice": if (!t(i)) return null; var m = e.children.slice(0), v = this.computeSliceParams(i.length, m), y = v[0], E = v[1], S = v[2]; if (a = [], S > 0) for (f = y; f < E; f += S)a.push(i[f]); else for (f = y; f > E; f += S)a.push(i[f]); return a; case "Projection": var b = this.visit(e.children[0], i); if (!t(b)) return null; for (d = [], f = 0; f < b.length; f++)null !== (c = this.visit(e.children[1], b[f])) && d.push(c); return d; case "ValueProjection": if (!n(b = this.visit(e.children[0], i))) return null; d = []; var C = function (e) { for (var t = Object.keys(e), n = [], o = 0; o < t.length; o++)n.push(e[t[o]]); return n }(b); for (f = 0; f < C.length; f++)null !== (c = this.visit(e.children[1], C[f])) && d.push(c); return d; case "FilterProjection": if (!t(b = this.visit(e.children[0], i))) return null; var _ = [], w = []; for (f = 0; f < b.length; f++)r(s = this.visit(e.children[2], b[f])) || _.push(b[f]); for (var x = 0; x < _.length; x++)null !== (c = this.visit(e.children[1], _[x])) && w.push(c); return w; case "Comparator": switch (u = this.visit(e.children[0], i), l = this.visit(e.children[1], i), e.name) { case R: a = o(u, l); break; case D: a = !o(u, l); break; case N: a = u > l; break; case O: a = u >= l; break; case k: a = u < l; break; case L: a = u <= l; break; default: throw new Error("Unknown comparator: " + e.name) }return a; case P: var M = this.visit(e.children[0], i); if (!t(M)) return null; var U = []; for (f = 0; f < M.length; f++)t(c = M[f]) ? U.push.apply(U, c) : U.push(c); return U; case "Identity": return i; case "MultiSelectList": if (null === i) return null; for (d = [], f = 0; f < e.children.length; f++)d.push(this.visit(e.children[f], i)); return d; case "MultiSelectHash": if (null === i) return null; var q; for (d = {}, f = 0; f < e.children.length; f++)d[(q = e.children[f]).name] = this.visit(q.value, i); return d; case "OrExpression": return r(s = this.visit(e.children[0], i)) && (s = this.visit(e.children[1], i)), s; case "AndExpression": return !0 === r(u = this.visit(e.children[0], i)) ? u : this.visit(e.children[1], i); case "NotExpression": return r(u = this.visit(e.children[0], i)); case "Literal": return e.value; case A: return h = this.visit(e.children[0], i), this.visit(e.children[1], h); case T: return i; case "Function": var F = []; for (f = 0; f < e.children.length; f++)F.push(this.visit(e.children[f], i)); return this.runtime.callFunction(e.name, F); case "ExpressionReference": var j = e.children[0]; return j.jmespathType = I, j; default: throw new Error("Unknown node type: " + e.type) } }, computeSliceParams: function (e, t) { var n = t[0], o = t[1], r = t[2], i = [null, null, null]; if (null === r) r = 1; else if (0 === r) { var s = new Error("Invalid slice, step cannot be 0"); throw s.name = "RuntimeError", s } var c = r < 0; return n = null === n ? c ? e - 1 : 0 : this.capSliceRange(e, n, r), o = null === o ? c ? -1 : e : this.capSliceRange(e, o, r), i[0] = n, i[1] = o, i[2] = r, i }, capSliceRange: function (e, t, n) { return t < 0 ? (t += e) < 0 && (t = n < 0 ? -1 : 0) : t >= e && (t = n < 0 ? e - 1 : e), t } }, Q.prototype = { callFunction: function (e, t) { var n = this.functionTable[e]; if (void 0 === n) throw new Error("Unknown function: " + e + "()"); return this._validateArgs(e, t, n._signature), n._func.call(this, t) }, _validateArgs: function (e, t, n) { var o, r, i, s; if (n[n.length - 1].variadic) { if (t.length < n.length) throw o = 1 === n.length ? " argument" : " arguments", new Error("ArgumentError: " + e + "() takes at least" + n.length + o + " but received " + t.length) } else if (t.length !== n.length) throw o = 1 === n.length ? " argument" : " arguments", new Error("ArgumentError: " + e + "() takes " + n.length + o + " but received " + t.length); for (var c = 0; c < n.length; c++) { s = !1, r = n[c].types, i = this._getTypeName(t[c]); for (var a = 0; a < r.length; a++)if (this._typeMatches(i, r[a], t[c])) { s = !0; break } if (!s) throw new Error("TypeError: " + e + "() expected argument " + (c + 1) + " to be type " + r + " but received type " + i + " instead.") } }, _typeMatches: function (e, t, n) { if (t === c) return !0; if (t !== d && t !== h && t !== u) return e === t; if (t === u) return e === u; if (e === u) { var o; t === h ? o = s : t === d && (o = a); for (var r = 0; r < n.length; r++)if (!this._typeMatches(this._getTypeName(n[r]), o, n[r])) return !1; return !0 } }, _getTypeName: function (e) { switch (Object.prototype.toString.call(e)) { case "[object String]": return a; case "[object Number]": return s; case "[object Array]": return u; case "[object Boolean]": return 5; case "[object Null]": return 7; case "[object Object]": return e.jmespathType === I ? p : l } }, _functionStartsWith: function (e) { return 0 === e[0].lastIndexOf(e[1]) }, _functionEndsWith: function (e) { var t = e[0], n = e[1]; return -1 !== t.indexOf(n, t.length - n.length) }, _functionReverse: function (e) { if (this._getTypeName(e[0]) === a) { for (var t = e[0], n = "", o = t.length - 1; o >= 0; o--)n += t[o]; return n } var r = e[0].slice(0); return r.reverse(), r }, _functionAbs: function (e) { return Math.abs(e[0]) }, _functionCeil: function (e) { return Math.ceil(e[0]) }, _functionAvg: function (e) { for (var t = 0, n = e[0], o = 0; o < n.length; o++)t += n[o]; return t / n.length }, _functionContains: function (e) { return e[0].indexOf(e[1]) >= 0 }, _functionFloor: function (e) { return Math.floor(e[0]) }, _functionLength: function (e) { return n(e[0]) ? Object.keys(e[0]).length : e[0].length }, _functionMap: function (e) { for (var t = [], n = this._interpreter, o = e[0], r = e[1], i = 0; i < r.length; i++)t.push(n.visit(o, r[i])); return t }, _functionMerge: function (e) { for (var t = {}, n = 0; n < e.length; n++) { var o = e[n]; for (var r in o) t[r] = o[r] } return t }, _functionMax: function (e) { if (e[0].length > 0) { if (this._getTypeName(e[0][0]) === s) return Math.max.apply(Math, e[0]); for (var t = e[0], n = t[0], o = 1; o < t.length; o++)n.localeCompare(t[o]) < 0 && (n = t[o]); return n } return null }, _functionMin: function (e) { if (e[0].length > 0) { if (this._getTypeName(e[0][0]) === s) return Math.min.apply(Math, e[0]); for (var t = e[0], n = t[0], o = 1; o < t.length; o++)t[o].localeCompare(n) < 0 && (n = t[o]); return n } return null }, _functionSum: function (e) { for (var t = 0, n = e[0], o = 0; o < n.length; o++)t += n[o]; return t }, _functionType: function (e) { switch (this._getTypeName(e[0])) { case s: return "number"; case a: return "string"; case u: return "array"; case l: return "object"; case 5: return "boolean"; case p: return "expref"; case 7: return "null" } }, _functionKeys: function (e) { return Object.keys(e[0]) }, _functionValues: function (e) { for (var t = e[0], n = Object.keys(t), o = [], r = 0; r < n.length; r++)o.push(t[n[r]]); return o }, _functionJoin: function (e) { var t = e[0]; return e[1].join(t) }, _functionToArray: function (e) { return this._getTypeName(e[0]) === u ? e[0] : [e[0]] }, _functionToString: function (e) { return this._getTypeName(e[0]) === a ? e[0] : JSON.stringify(e[0]) }, _functionToNumber: function (e) { var t, n = this._getTypeName(e[0]); return n === s ? e[0] : n !== a || (t = +e[0], isNaN(t)) ? null : t }, _functionNotNull: function (e) { for (var t = 0; t < e.length; t++)if (7 !== this._getTypeName(e[t])) return e[t]; return null }, _functionSort: function (e) { var t = e[0].slice(0); return t.sort(), t }, _functionSortBy: function (e) { var t = e[0].slice(0); if (0 === t.length) return t; var n = this._interpreter, o = e[1], r = this._getTypeName(n.visit(o, t[0])); if ([s, a].indexOf(r) < 0) throw new Error("TypeError"); for (var i = this, c = [], u = 0; u < t.length; u++)c.push([u, t[u]]); c.sort((function (e, t) { var s = n.visit(o, e[1]), c = n.visit(o, t[1]); if (i._getTypeName(s) !== r) throw new Error("TypeError: expected " + r + ", received " + i._getTypeName(s)); if (i._getTypeName(c) !== r) throw new Error("TypeError: expected " + r + ", received " + i._getTypeName(c)); return s > c ? 1 : s < c ? -1 : e[0] - t[0] })); for (var l = 0; l < c.length; l++)t[l] = c[l][1]; return t }, _functionMaxBy: function (e) { for (var t, n, o = e[1], r = e[0], i = this.createKeyFunction(o, [s, a]), c = -1 / 0, u = 0; u < r.length; u++)(n = i(r[u])) > c && (c = n, t = r[u]); return t }, _functionMinBy: function (e) { for (var t, n, o = e[1], r = e[0], i = this.createKeyFunction(o, [s, a]), c = 1 / 0, u = 0; u < r.length; u++)(n = i(r[u])) < c && (c = n, t = r[u]); return t }, createKeyFunction: function (e, t) { var n = this, o = this._interpreter; return function (r) { var i = o.visit(e, r); if (t.indexOf(n._getTypeName(i)) < 0) { var s = "TypeError: expected one of " + t + ", received " + n._getTypeName(i); throw new Error(s) } return i } } }, e.tokenize = function (e) { return (new K).tokenize(e) }, e.compile = function (e) { return (new X).parse(e) }, e.search = function (e, t) { var n = new X, o = new Q, r = new J(o); o._interpreter = r; var i = n.parse(t); return r.search(i, e) }, e.strictDeepEqual = o }(void 0 === n ? this.jmespath = {} : n) }, {}], 86: [function (e, t, n) { var o, r, i = t.exports = {}; function s() { throw new Error("setTimeout has not been defined") } function c() { throw new Error("clearTimeout has not been defined") } function a(e) { if (o === setTimeout) return setTimeout(e, 0); if ((o === s || !o) && setTimeout) return o = setTimeout, setTimeout(e, 0); try { return o(e, 0) } catch (t) { try { return o.call(null, e, 0) } catch (t) { return o.call(this, e, 0) } } } !function () { try { o = "function" == typeof setTimeout ? setTimeout : s } catch (e) { o = s } try { r = "function" == typeof clearTimeout ? clearTimeout : c } catch (e) { r = c } }(); var u, l = [], p = !1, h = -1; function d() { p && u && (p = !1, u.length ? l = u.concat(l) : h = -1, l.length && f()) } function f() { if (!p) { var e = a(d); p = !0; for (var t = l.length; t;) { for (u = l, l = []; ++h < t;)u && u[h].run(); h = -1, t = l.length } u = null, p = !1, function (e) { if (r === clearTimeout) return clearTimeout(e); if ((r === c || !r) && clearTimeout) return r = clearTimeout, clearTimeout(e); try { return r(e) } catch (t) { try { return r.call(null, e) } catch (t) { return r.call(this, e) } } }(e) } } function g(e, t) { this.fun = e, this.array = t } function m() { } i.nextTick = function (e) { var t = new Array(arguments.length - 1); if (arguments.length > 1) for (var n = 1; n < arguments.length; n++)t[n - 1] = arguments[n]; l.push(new g(e, t)), 1 !== l.length || p || a(f) }, g.prototype.run = function () { this.fun.apply(null, this.array) }, i.title = "browser", i.browser = !0, i.env = {}, i.argv = [], i.version = "", i.versions = {}, i.on = m, i.addListener = m, i.once = m, i.off = m, i.removeListener = m, i.removeAllListeners = m, i.emit = m, i.prependListener = m, i.prependOnceListener = m, i.listeners = function (e) { return [] }, i.binding = function (e) { throw new Error("process.binding is not supported") }, i.cwd = function () { return "/" }, i.chdir = function (e) { throw new Error("process.chdir is not supported") }, i.umask = function () { return 0 } }, {}], 87: [function (e, t, n) { "use strict"; function o(e, t) { return Object.prototype.hasOwnProperty.call(e, t) } t.exports = function (e, t, n, i) { t = t || "&", n = n || "="; var s = {}; if ("string" != typeof e || 0 === e.length) return s; var c = /\+/g; e = e.split(t); var a = 1e3; i && "number" == typeof i.maxKeys && (a = i.maxKeys); var u = e.length; a > 0 && u > a && (u = a); for (var l = 0; l < u; ++l) { var p, h, d, f, g = e[l].replace(c, "%20"), m = g.indexOf(n); m >= 0 ? (p = g.substr(0, m), h = g.substr(m + 1)) : (p = g, h = ""), d = decodeURIComponent(p), f = decodeURIComponent(h), o(s, d) ? r(s[d]) ? s[d].push(f) : s[d] = [s[d], f] : s[d] = f } return s }; var r = Array.isArray || function (e) { return "[object Array]" === Object.prototype.toString.call(e) } }, {}], 88: [function (e, t, n) { "use strict"; var o = function (e) { switch (r(e)) { case "string": return e; case "boolean": return e ? "true" : "false"; case "number": return isFinite(e) ? e : ""; default: return "" } }; t.exports = function (e, t, n, a) { return t = t || "&", n = n || "=", null === e && (e = void 0), "object" === r(e) ? s(c(e), (function (r) { var c = encodeURIComponent(o(r)) + n; return i(e[r]) ? s(e[r], (function (e) { return c + encodeURIComponent(o(e)) })).join(t) : c + encodeURIComponent(o(e[r])) })).join(t) : a ? encodeURIComponent(o(a)) + n + encodeURIComponent(o(e)) : "" }; var i = Array.isArray || function (e) { return "[object Array]" === Object.prototype.toString.call(e) }; function s(e, t) { if (e.map) return e.map(t); for (var n = [], o = 0; o < e.length; o++)n.push(t(e[o], o)); return n } var c = Object.keys || function (e) { var t = []; for (var n in e) Object.prototype.hasOwnProperty.call(e, n) && t.push(n); return t } }, {}], 89: [function (e, t, n) { "use strict"; n.decode = n.parse = e("./decode"), n.encode = n.stringify = e("./encode") }, { "./decode": 87, "./encode": 88 }], 90: [function (e, t, n) { "use strict"; function o(e, t) { return Object.prototype.hasOwnProperty.call(e, t) } t.exports = function (e, t, n, r) { t = t || "&", n = n || "="; var i = {}; if ("string" != typeof e || 0 === e.length) return i; var s = /\+/g; e = e.split(t); var c = 1e3; r && "number" == typeof r.maxKeys && (c = r.maxKeys); var a = e.length; c > 0 && a > c && (a = c); for (var u = 0; u < a; ++u) { var l, p, h, d, f = e[u].replace(s, "%20"), g = f.indexOf(n); g >= 0 ? (l = f.substr(0, g), p = f.substr(g + 1)) : (l = f, p = ""), h = decodeURIComponent(l), d = decodeURIComponent(p), o(i, h) ? Array.isArray(i[h]) ? i[h].push(d) : i[h] = [i[h], d] : i[h] = d } return i } }, {}], 91: [function (e, t, n) { "use strict"; var o = function (e) { switch (r(e)) { case "string": return e; case "boolean": return e ? "true" : "false"; case "number": return isFinite(e) ? e : ""; default: return "" } }; t.exports = function (e, t, n, i) { return t = t || "&", n = n || "=", null === e && (e = void 0), "object" === r(e) ? Object.keys(e).map((function (r) { var i = encodeURIComponent(o(r)) + n; return Array.isArray(e[r]) ? e[r].map((function (e) { return i + encodeURIComponent(o(e)) })).join(t) : i + encodeURIComponent(o(e[r])) })).join(t) : i ? encodeURIComponent(o(i)) + n + encodeURIComponent(o(e)) : "" } }, {}], 92: [function (e, t, n) { arguments[4][89][0].apply(n, arguments) }, { "./decode": 90, "./encode": 91, dup: 89 }], 93: [function (e, t, n) { (function (t, o) { (function () { var r = e("process/browser.js").nextTick, i = Function.prototype.apply, s = Array.prototype.slice, c = {}, a = 0; function u(e, t) { this._id = e, this._clearFn = t } n.setTimeout = function () { return new u(i.call(setTimeout, window, arguments), clearTimeout) }, n.setInterval = function () { return new u(i.call(setInterval, window, arguments), clearInterval) }, n.clearTimeout = n.clearInterval = function (e) { e.close() }, u.prototype.unref = u.prototype.ref = function () { }, u.prototype.close = function () { this._clearFn.call(window, this._id) }, n.enroll = function (e, t) { clearTimeout(e._idleTimeoutId), e._idleTimeout = t }, n.unenroll = function (e) { clearTimeout(e._idleTimeoutId), e._idleTimeout = -1 }, n._unrefActive = n.active = function (e) { clearTimeout(e._idleTimeoutId); var t = e._idleTimeout; t >= 0 && (e._idleTimeoutId = setTimeout((function () { e._onTimeout && e._onTimeout() }), t)) }, n.setImmediate = "function" == typeof t ? t : function (e) { var t = a++, o = !(arguments.length < 2) && s.call(arguments, 1); return c[t] = !0, r((function () { c[t] && (o ? e.apply(null, o) : e.call(null), n.clearImmediate(t)) })), t }, n.clearImmediate = "function" == typeof o ? o : function (e) { delete c[e] } }).call(this) }).call(this, e("timers").setImmediate, e("timers").clearImmediate) }, { "process/browser.js": 86, timers: 93 }], 94: [function (e, t, n) { var o = e("punycode"); function i() { this.protocol = null, this.slashes = null, this.auth = null, this.host = null, this.port = null, this.hostname = null, this.hash = null, this.search = null, this.query = null, this.pathname = null, this.path = null, this.href = null } n.parse = y, n.resolve = function (e, t) { return y(e, !1, !0).resolve(t) }, n.resolveObject = function (e, t) { return e ? y(e, !1, !0).resolveObject(t) : t }, n.format = function (e) { return E(e) && (e = y(e)), e instanceof i ? e.format() : i.prototype.format.call(e) }, n.Url = i; var s = /^([a-z0-9.+-]+:)/i, c = /:[0-9]*$/, a = ["{", "}", "|", "\\", "^", "`"].concat(["<", ">", '"', "`", " ", "\r", "\n", "\t"]), u = ["'"].concat(a), l = ["%", "/", "?", ";", "#"].concat(u), p = ["/", "?", "#"], h = /^[a-z0-9A-Z_-]{0,63}$/, d = /^([a-z0-9A-Z_-]{0,63})(.*)$/, f = { javascript: !0, "javascript:": !0 }, g = { javascript: !0, "javascript:": !0 }, m = { http: !0, https: !0, ftp: !0, gopher: !0, file: !0, "http:": !0, "https:": !0, "ftp:": !0, "gopher:": !0, "file:": !0 }, v = e("querystring"); function y(e, t, n) { if (e && S(e) && e instanceof i) return e; var o = new i; return o.parse(e, t, n), o } function E(e) { return "string" == typeof e } function S(e) { return "object" === r(e) && null !== e } function b(e) { return null === e } i.prototype.parse = function (e, t, n) { if (!E(e)) throw new TypeError("Parameter 'url' must be a string, not " + r(e)); var i = e; i = i.trim(); var c = s.exec(i); if (c) { var a = (c = c[0]).toLowerCase(); this.protocol = a, i = i.substr(c.length) } if (n || c || i.match(/^\/\/[^@\/]+@[^@\/]+/)) { var y = "//" === i.substr(0, 2); !y || c && g[c] || (i = i.substr(2), this.slashes = !0) } if (!g[c] && (y || c && !m[c])) { for (var S, b, C = -1, T = 0; T < p.length; T++)-1 !== (I = i.indexOf(p[T])) && (-1 === C || I < C) && (C = I); for (-1 !== (b = -1 === C ? i.lastIndexOf("@") : i.lastIndexOf("@", C)) && (S = i.slice(0, b), i = i.slice(b + 1), this.auth = decodeURIComponent(S)), C = -1, T = 0; T < l.length; T++) { var I; -1 !== (I = i.indexOf(l[T])) && (-1 === C || I < C) && (C = I) } -1 === C && (C = i.length), this.host = i.slice(0, C), i = i.slice(C), this.parseHost(), this.hostname = this.hostname || ""; var A = "[" === this.hostname[0] && "]" === this.hostname[this.hostname.length - 1]; if (!A) for (var _ = this.hostname.split(/\./), w = (T = 0, _.length); T < w; T++) { var R = _[T]; if (R && !R.match(h)) { for (var N = "", k = 0, O = R.length; k < O; k++)R.charCodeAt(k) > 127 ? N += "x" : N += R[k]; if (!N.match(h)) { var L = _.slice(0, T), D = _.slice(T + 1), P = R.match(d); P && (L.push(P[1]), D.unshift(P[2])), D.length && (i = "/" + D.join(".") + i), this.hostname = L.join("."); break } } } if (this.hostname.length > 255 ? this.hostname = "" : this.hostname = this.hostname.toLowerCase(), !A) { var x = this.hostname.split("."), M = []; for (T = 0; T < x.length; ++T) { var U = x[T]; M.push(U.match(/[^A-Za-z0-9_-]/) ? "xn--" + o.encode(U) : U) } this.hostname = M.join(".") } var q = this.port ? ":" + this.port : "", F = this.hostname || ""; this.host = F + q, this.href += this.host, A && (this.hostname = this.hostname.substr(1, this.hostname.length - 2), "/" !== i[0] && (i = "/" + i)) } if (!f[a]) for (T = 0, w = u.length; T < w; T++) { var j = u[T], B = encodeURIComponent(j); B === j && (B = escape(j)), i = i.split(j).join(B) } var V = i.indexOf("#"); -1 !== V && (this.hash = i.substr(V), i = i.slice(0, V)); var H = i.indexOf("?"); return -1 !== H ? (this.search = i.substr(H), this.query = i.substr(H + 1), t && (this.query = v.parse(this.query)), i = i.slice(0, H)) : t && (this.search = "", this.query = {}), i && (this.pathname = i), m[a] && this.hostname && !this.pathname && (this.pathname = "/"), (this.pathname || this.search) && (q = this.pathname || "", U = this.search || "", this.path = q + U), this.href = this.format(), this }, i.prototype.format = function () { var e = this.auth || ""; e && (e = (e = encodeURIComponent(e)).replace(/%3A/i, ":"), e += "@"); var t = this.protocol || "", n = this.pathname || "", o = this.hash || "", r = !1, i = ""; this.host ? r = e + this.host : this.hostname && (r = e + (-1 === this.hostname.indexOf(":") ? this.hostname : "[" + this.hostname + "]"), this.port && (r += ":" + this.port)), this.query && S(this.query) && Object.keys(this.query).length && (i = v.stringify(this.query)); var s = this.search || i && "?" + i || ""; return t && ":" !== t.substr(-1) && (t += ":"), this.slashes || (!t || m[t]) && !1 !== r ? (r = "//" + (r || ""), n && "/" !== n.charAt(0) && (n = "/" + n)) : r || (r = ""), o && "#" !== o.charAt(0) && (o = "#" + o), s && "?" !== s.charAt(0) && (s = "?" + s), t + r + (n = n.replace(/[?#]/g, (function (e) { return encodeURIComponent(e) }))) + (s = s.replace("#", "%23")) + o }, i.prototype.resolve = function (e) { return this.resolveObject(y(e, !1, !0)).format() }, i.prototype.resolveObject = function (e) { if (E(e)) { var t = new i; t.parse(e, !1, !0), e = t } var n = new i; if (Object.keys(this).forEach((function (e) { n[e] = this[e] }), this), n.hash = e.hash, "" === e.href) return n.href = n.format(), n; if (e.slashes && !e.protocol) return Object.keys(e).forEach((function (t) { "protocol" !== t && (n[t] = e[t]) })), m[n.protocol] && n.hostname && !n.pathname && (n.path = n.pathname = "/"), n.href = n.format(), n; if (e.protocol && e.protocol !== n.protocol) { if (!m[e.protocol]) return Object.keys(e).forEach((function (t) { n[t] = e[t] })), n.href = n.format(), n; if (n.protocol = e.protocol, e.host || g[e.protocol]) n.pathname = e.pathname; else { for (var o = (e.pathname || "").split("/"); o.length && !(e.host = o.shift());); e.host || (e.host = ""), e.hostname || (e.hostname = ""), "" !== o[0] && o.unshift(""), o.length < 2 && o.unshift(""), n.pathname = o.join("/") } if (n.search = e.search, n.query = e.query, n.host = e.host || "", n.auth = e.auth, n.hostname = e.hostname || e.host, n.port = e.port, n.pathname || n.search) { var r = n.pathname || "", s = n.search || ""; n.path = r + s } return n.slashes = n.slashes || e.slashes, n.href = n.format(), n } var c = n.pathname && "/" === n.pathname.charAt(0), a = e.host || e.pathname && "/" === e.pathname.charAt(0), u = a || c || n.host && e.pathname, l = u, p = n.pathname && n.pathname.split("/") || [], h = (o = e.pathname && e.pathname.split("/") || [], n.protocol && !m[n.protocol]); if (h && (n.hostname = "", n.port = null, n.host && ("" === p[0] ? p[0] = n.host : p.unshift(n.host)), n.host = "", e.protocol && (e.hostname = null, e.port = null, e.host && ("" === o[0] ? o[0] = e.host : o.unshift(e.host)), e.host = null), u = u && ("" === o[0] || "" === p[0])), a) n.host = e.host || "" === e.host ? e.host : n.host, n.hostname = e.hostname || "" === e.hostname ? e.hostname : n.hostname, n.search = e.search, n.query = e.query, p = o; else if (o.length) p || (p = []), p.pop(), p = p.concat(o), n.search = e.search, n.query = e.query; else if (null != e.search) return h && (n.hostname = n.host = p.shift(), (S = !!(n.host && n.host.indexOf("@") > 0) && n.host.split("@")) && (n.auth = S.shift(), n.host = n.hostname = S.shift())), n.search = e.search, n.query = e.query, b(n.pathname) && b(n.search) || (n.path = (n.pathname ? n.pathname : "") + (n.search ? n.search : "")), n.href = n.format(), n; if (!p.length) return n.pathname = null, n.search ? n.path = "/" + n.search : n.path = null, n.href = n.format(), n; for (var d = p.slice(-1)[0], f = (n.host || e.host) && ("." === d || ".." === d) || "" === d, v = 0, y = p.length; y >= 0; y--)"." == (d = p[y]) ? p.splice(y, 1) : ".." === d ? (p.splice(y, 1), v++) : v && (p.splice(y, 1), v--); if (!u && !l) for (; v--; v)p.unshift(".."); !u || "" === p[0] || p[0] && "/" === p[0].charAt(0) || p.unshift(""), f && "/" !== p.join("/").substr(-1) && p.push(""); var S, C = "" === p[0] || p[0] && "/" === p[0].charAt(0); return h && (n.hostname = n.host = C ? "" : p.length ? p.shift() : "", (S = !!(n.host && n.host.indexOf("@") > 0) && n.host.split("@")) && (n.auth = S.shift(), n.host = n.hostname = S.shift())), (u = u || n.host && p.length) && !C && p.unshift(""), p.length ? n.pathname = p.join("/") : (n.pathname = null, n.path = null), b(n.pathname) && b(n.search) || (n.path = (n.pathname ? n.pathname : "") + (n.search ? n.search : "")), n.auth = e.auth || n.auth, n.slashes = n.slashes || e.slashes, n.href = n.format(), n }, i.prototype.parseHost = function () { var e = this.host, t = c.exec(e); t && (":" !== (t = t[0]) && (this.port = t.substr(1)), e = e.substr(0, e.length - t.length)), e && (this.hostname = e) } }, { punycode: 80, querystring: 89 }], 95: [function (e, t, n) { "function" == typeof Object.create ? t.exports = function (e, t) { e.super_ = t, e.prototype = Object.create(t.prototype, { constructor: { value: e, enumerable: !1, writable: !0, configurable: !0 } }) } : t.exports = function (e, t) { e.super_ = t; var n = function () { }; n.prototype = t.prototype, e.prototype = new n, e.prototype.constructor = e } }, {}], 96: [function (e, t, n) { t.exports = function (e) { return e && "object" === r(e) && "function" == typeof e.copy && "function" == typeof e.fill && "function" == typeof e.readUInt8 } }, {}], 97: [function (e, t, o) { (function (t, n) { (function () { var i = /%[sdj%]/g; o.format = function (e) { if (!y(e)) { for (var t = [], n = 0; n < arguments.length; n++)t.push(a(arguments[n])); return t.join(" ") } n = 1; for (var o = arguments, r = o.length, s = String(e).replace(i, (function (e) { if ("%%" === e) return "%"; if (n >= r) return e; switch (e) { case "%s": return String(o[n++]); case "%d": return Number(o[n++]); case "%j": try { return JSON.stringify(o[n++]) } catch (e) { return "[Circular]" } default: return e } })), c = o[n]; n < r; c = o[++n])m(c) || !b(c) ? s += " " + c : s += " " + a(c); return s }, o.deprecate = function (e, r) { if (E(n.process)) return function () { return o.deprecate(e, r).apply(this, arguments) }; if (!0 === t.noDeprecation) return e; var i = !1; return function () { if (!i) { if (t.throwDeprecation) throw new Error(r); t.traceDeprecation ? console.trace(r) : console.error(r), i = !0 } return e.apply(this, arguments) } }; var s, c = {}; function a(e, t) { var n = { seen: [], stylize: l }; return arguments.length >= 3 && (n.depth = arguments[2]), arguments.length >= 4 && (n.colors = arguments[3]), g(t) ? n.showHidden = t : t && o._extend(n, t), E(n.showHidden) && (n.showHidden = !1), E(n.depth) && (n.depth = 2), E(n.colors) && (n.colors = !1), E(n.customInspect) && (n.customInspect = !0), n.colors && (n.stylize = u), p(n, e, n.depth) } function u(e, t) { var n = a.styles[t]; return n ? "[" + a.colors[n][0] + "m" + e + "[" + a.colors[n][1] + "m" : e } function l(e, t) { return e } function p(e, t, n) { if (e.customInspect && t && I(t.inspect) && t.inspect !== o.inspect && (!t.constructor || t.constructor.prototype !== t)) { var r = t.inspect(n, e); return y(r) || (r = p(e, r, n)), r } var i = function (e, t) { if (E(t)) return e.stylize("undefined", "undefined"); if (y(t)) { var n = "'" + JSON.stringify(t).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; return e.stylize(n, "string") } return v(t) ? e.stylize("" + t, "number") : g(t) ? e.stylize("" + t, "boolean") : m(t) ? e.stylize("null", "null") : void 0 }(e, t); if (i) return i; var s = Object.keys(t), c = function (e) { var t = {}; return e.forEach((function (e, n) { t[e] = !0 })), t }(s); if (e.showHidden && (s = Object.getOwnPropertyNames(t)), T(t) && (s.indexOf("message") >= 0 || s.indexOf("description") >= 0)) return h(t); if (0 === s.length) { if (I(t)) { var a = t.name ? ": " + t.name : ""; return e.stylize("[Function" + a + "]", "special") } if (S(t)) return e.stylize(RegExp.prototype.toString.call(t), "regexp"); if (C(t)) return e.stylize(Date.prototype.toString.call(t), "date"); if (T(t)) return h(t) } var u, l = "", b = !1, A = ["{", "}"]; return f(t) && (b = !0, A = ["[", "]"]), I(t) && (l = " [Function" + (t.name ? ": " + t.name : "") + "]"), S(t) && (l = " " + RegExp.prototype.toString.call(t)), C(t) && (l = " " + Date.prototype.toUTCString.call(t)), T(t) && (l = " " + h(t)), 0 !== s.length || b && 0 != t.length ? n < 0 ? S(t) ? e.stylize(RegExp.prototype.toString.call(t), "regexp") : e.stylize("[Object]", "special") : (e.seen.push(t), u = b ? function (e, t, n, o, r) { for (var i = [], s = 0, c = t.length; s < c; ++s)R(t, String(s)) ? i.push(d(e, t, n, o, String(s), !0)) : i.push(""); return r.forEach((function (r) { r.match(/^\d+$/) || i.push(d(e, t, n, o, r, !0)) })), i }(e, t, n, c, s) : s.map((function (o) { return d(e, t, n, c, o, b) })), e.seen.pop(), function (e, t, n) { var o = e.reduce((function (e, t) { return t.indexOf("\n"), e + t.replace(/\u001b\[\d\d?m/g, "").length + 1 }), 0); return o > 60 ? n[0] + ("" === t ? "" : t + "\n ") + " " + e.join(",\n ") + " " + n[1] : n[0] + t + " " + e.join(", ") + " " + n[1] }(u, l, A)) : A[0] + l + A[1] } function h(e) { return "[" + Error.prototype.toString.call(e) + "]" } function d(e, t, n, o, r, i) { var s, c, a; if ((a = Object.getOwnPropertyDescriptor(t, r) || { value: t[r] }).get ? c = a.set ? e.stylize("[Getter/Setter]", "special") : e.stylize("[Getter]", "special") : a.set && (c = e.stylize("[Setter]", "special")), R(o, r) || (s = "[" + r + "]"), c || (e.seen.indexOf(a.value) < 0 ? (c = m(n) ? p(e, a.value, null) : p(e, a.value, n - 1)).indexOf("\n") > -1 && (c = i ? c.split("\n").map((function (e) { return " " + e })).join("\n").substr(2) : "\n" + c.split("\n").map((function (e) { return " " + e })).join("\n")) : c = e.stylize("[Circular]", "special")), E(s)) { if (i && r.match(/^\d+$/)) return c; (s = JSON.stringify("" + r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/) ? (s = s.substr(1, s.length - 2), s = e.stylize(s, "name")) : (s = s.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"), s = e.stylize(s, "string")) } return s + ": " + c } function f(e) { return Array.isArray(e) } function g(e) { return "boolean" == typeof e } function m(e) { return null === e } function v(e) { return "number" == typeof e } function y(e) { return "string" == typeof e } function E(e) { return void 0 === e } function S(e) { return b(e) && "[object RegExp]" === A(e) } function b(e) { return "object" === r(e) && null !== e } function C(e) { return b(e) && "[object Date]" === A(e) } function T(e) { return b(e) && ("[object Error]" === A(e) || e instanceof Error) } function I(e) { return "function" == typeof e } function A(e) { return Object.prototype.toString.call(e) } function _(e) { return e < 10 ? "0" + e.toString(10) : e.toString(10) } o.debuglog = function (e) { if (E(s) && (s = t.env.NODE_DEBUG || ""), e = e.toUpperCase(), !c[e]) if (new RegExp("\\b" + e + "\\b", "i").test(s)) { var n = t.pid; c[e] = function () { var t = o.format.apply(o, arguments); console.error("%s %d: %s", e, n, t) } } else c[e] = function () { }; return c[e] }, o.inspect = a, a.colors = { bold: [1, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], white: [37, 39], grey: [90, 39], black: [30, 39], blue: [34, 39], cyan: [36, 39], green: [32, 39], magenta: [35, 39], red: [31, 39], yellow: [33, 39] }, a.styles = { special: "cyan", number: "yellow", boolean: "yellow", undefined: "grey", null: "bold", string: "green", date: "magenta", regexp: "red" }, o.isArray = f, o.isBoolean = g, o.isNull = m, o.isNullOrUndefined = function (e) { return null == e }, o.isNumber = v, o.isString = y, o.isSymbol = function (e) { return "symbol" === r(e) }, o.isUndefined = E, o.isRegExp = S, o.isObject = b, o.isDate = C, o.isError = T, o.isFunction = I, o.isPrimitive = function (e) { return null === e || "boolean" == typeof e || "number" == typeof e || "string" == typeof e || "symbol" === r(e) || void 0 === e }, o.isBuffer = e("./support/isBuffer"); var w = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; function R(e, t) { return Object.prototype.hasOwnProperty.call(e, t) } o.log = function () { var e, t; console.log("%s - %s", (e = new Date, t = [_(e.getHours()), _(e.getMinutes()), _(e.getSeconds())].join(":"), [e.getDate(), w[e.getMonth()], t].join(" ")), o.format.apply(o, arguments)) }, o.inherits = e("inherits"), o._extend = function (e, t) { if (!t || !b(t)) return e; for (var n = Object.keys(t), o = n.length; o--;)e[n[o]] = t[n[o]]; return e } }).call(this) }).call(this, e("_process"), void 0 !== n.g ? n.g : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}) }, { "./support/isBuffer": 96, _process: 86, inherits: 95 }], 98: [function (e, t, n) { var o = e("./v1"), r = e("./v4"), i = r; i.v1 = o, i.v4 = r, t.exports = i }, { "./v1": 101, "./v4": 102 }], 99: [function (e, t, n) { for (var o = [], r = 0; r < 256; ++r)o[r] = (r + 256).toString(16).substr(1); t.exports = function (e, t) { var n = t || 0, r = o; return [r[e[n++]], r[e[n++]], r[e[n++]], r[e[n++]], "-", r[e[n++]], r[e[n++]], "-", r[e[n++]], r[e[n++]], "-", r[e[n++]], r[e[n++]], "-", r[e[n++]], r[e[n++]], r[e[n++]], r[e[n++]], r[e[n++]], r[e[n++]]].join("") } }, {}], 100: [function (e, t, n) { var o = "undefined" != typeof crypto && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || "undefined" != typeof msCrypto && "function" == typeof window.msCrypto.getRandomValues && msCrypto.getRandomValues.bind(msCrypto); if (o) { var r = new Uint8Array(16); t.exports = function () { return o(r), r } } else { var i = new Array(16); t.exports = function () { for (var e, t = 0; t < 16; t++)0 == (3 & t) && (e = 4294967296 * Math.random()), i[t] = e >>> ((3 & t) << 3) & 255; return i } } }, {}], 101: [function (e, t, n) { var o, r, i = e("./lib/rng"), s = e("./lib/bytesToUuid"), c = 0, a = 0; t.exports = function (e, t, n) { var u = t && n || 0, l = t || [], p = (e = e || {}).node || o, h = void 0 !== e.clockseq ? e.clockseq : r; if (null == p || null == h) { var d = i(); null == p && (p = o = [1 | d[0], d[1], d[2], d[3], d[4], d[5]]), null == h && (h = r = 16383 & (d[6] << 8 | d[7])) } var f = void 0 !== e.msecs ? e.msecs : (new Date).getTime(), g = void 0 !== e.nsecs ? e.nsecs : a + 1, m = f - c + (g - a) / 1e4; if (m < 0 && void 0 === e.clockseq && (h = h + 1 & 16383), (m < 0 || f > c) && void 0 === e.nsecs && (g = 0), g >= 1e4) throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); c = f, a = g, r = h; var v = (1e4 * (268435455 & (f += 122192928e5)) + g) % 4294967296; l[u++] = v >>> 24 & 255, l[u++] = v >>> 16 & 255, l[u++] = v >>> 8 & 255, l[u++] = 255 & v; var y = f / 4294967296 * 1e4 & 268435455; l[u++] = y >>> 8 & 255, l[u++] = 255 & y, l[u++] = y >>> 24 & 15 | 16, l[u++] = y >>> 16 & 255, l[u++] = h >>> 8 | 128, l[u++] = 255 & h; for (var E = 0; E < 6; ++E)l[u + E] = p[E]; return t || s(l) } }, { "./lib/bytesToUuid": 99, "./lib/rng": 100 }], 102: [function (e, t, n) { var o = e("./lib/rng"), r = e("./lib/bytesToUuid"); t.exports = function (e, t, n) { var i = t && n || 0; "string" == typeof e && (t = "binary" === e ? new Array(16) : null, e = null); var s = (e = e || {}).random || (e.rng || o)(); if (s[6] = 15 & s[6] | 64, s[8] = 63 & s[8] | 128, t) for (var c = 0; c < 16; ++c)t[i + c] = s[c]; return t || r(s) } }, { "./lib/bytesToUuid": 99, "./lib/rng": 100 }], 103: [function (e, t, n) { "use strict"; Object.defineProperty(n, "__esModule", { value: !0 }); var o = e("./utils/LRU"), r = function () { function e(e) { void 0 === e && (e = 1e3), this.maxSize = e, this.cache = new o.LRUCache(e) } return Object.defineProperty(e.prototype, "size", { get: function () { return this.cache.length }, enumerable: !0, configurable: !0 }), e.prototype.put = function (t, n) { var o = "string" != typeof t ? e.getKeyString(t) : t, r = this.populateValue(n); this.cache.put(o, r) }, e.prototype.get = function (t) { var n = "string" != typeof t ? e.getKeyString(t) : t, o = Date.now(), r = this.cache.get(n); if (r) for (var i = 0; i < r.length; i++)if (r[i].Expire < o) return void this.cache.remove(n); return r }, e.getKeyString = function (e) { for (var t = [], n = Object.keys(e).sort(), o = 0; o < n.length; o++) { var r = n[o]; void 0 !== e[r] && t.push(e[r]) } return t.join(" ") }, e.prototype.populateValue = function (e) { var t = Date.now(); return e.map((function (e) { return { Address: e.Address || "", Expire: t + 60 * (e.CachePeriodInMinutes || 1) * 1e3 } })) }, e.prototype.empty = function () { this.cache.empty() }, e.prototype.remove = function (t) { var n = "string" != typeof t ? e.getKeyString(t) : t; this.cache.remove(n) }, e }(); n.EndpointCache = r }, { "./utils/LRU": 104 }], 104: [function (e, t, n) { "use strict"; Object.defineProperty(n, "__esModule", { value: !0 }); var o = function (e, t) { this.key = e, this.value = t }, r = function () { function e(e) { if (this.nodeMap = {}, this.size = 0, "number" != typeof e || e < 1) throw new Error("Cache size can only be positive number"); this.sizeLimit = e } return Object.defineProperty(e.prototype, "length", { get: function () { return this.size }, enumerable: !0, configurable: !0 }), e.prototype.prependToList = function (e) { this.headerNode ? (this.headerNode.prev = e, e.next = this.headerNode) : this.tailNode = e, this.headerNode = e, this.size++ }, e.prototype.removeFromTail = function () { if (this.tailNode) { var e = this.tailNode, t = e.prev; return t && (t.next = void 0), e.prev = void 0, this.tailNode = t, this.size--, e } }, e.prototype.detachFromList = function (e) { this.headerNode === e && (this.headerNode = e.next), this.tailNode === e && (this.tailNode = e.prev), e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), e.next = void 0, e.prev = void 0, this.size-- }, e.prototype.get = function (e) { if (this.nodeMap[e]) { var t = this.nodeMap[e]; return this.detachFromList(t), this.prependToList(t), t.value } }, e.prototype.remove = function (e) { if (this.nodeMap[e]) { var t = this.nodeMap[e]; this.detachFromList(t), delete this.nodeMap[e] } }, e.prototype.put = function (e, t) { if (this.nodeMap[e]) this.remove(e); else if (this.size === this.sizeLimit) { var n = this.removeFromTail().key; delete this.nodeMap[n] } var r = new o(e, t); this.nodeMap[e] = r, this.prependToList(r) }, e.prototype.empty = function () { for (var e = Object.keys(this.nodeMap), t = 0; t < e.length; t++) { var n = e[t], o = this.nodeMap[n]; this.detachFromList(o), delete this.nodeMap[n] } }, e }(); n.LRUCache = r }, {}], 105: [function (e, t, n) { e("./browser_loader"); var o = e("./core"); "undefined" != typeof window && (window.AWS = o), void 0 !== t && (t.exports = o), "undefined" != typeof self && (self.AWS = o), Object.prototype.hasOwnProperty.call(o, "Connect") || (o.apiLoader.services.connect = {}, o.Connect = o.Service.defineService("connect", ["2017-02-15"])), o.apiLoader.services.connect["2017-02-15"] = e("../apis/connect-2017-02-15.min"), Object.prototype.hasOwnProperty.call(o, "STS") || (o.apiLoader.services.sts = {}, o.STS = o.Service.defineService("sts", ["2011-06-15"]), e("./services/sts")), o.apiLoader.services.sts["2011-06-15"] = e("../apis/sts-2011-06-15.min") }, { "../apis/connect-2017-02-15.min": 3, "../apis/sts-2011-06-15.min": 5, "./browser_loader": 16, "./core": 18, "./services/sts": 61 }] }, {}, [105]) }, 417: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect, e.lily = connect, connect.ClientMethods = connect.makeEnum(["getAgentSnapshot", "putAgentState", "getAgentStates", "getDialableCountryCodes", "getRoutingProfileQueues", "getAgentPermissions", "getAgentConfiguration", "updateAgentConfiguration", "acceptContact", "createOutboundContact", "createTaskContact", "clearContact", "completeContact", "destroyContact", "rejectContact", "notifyContactIssue", "updateContactAttributes", "createAdditionalConnection", "destroyConnection", "holdConnection", "resumeConnection", "toggleActiveConnections", "conferenceConnections", "sendClientLogs", "sendDigits", "sendSoftphoneCallReport", "sendSoftphoneCallMetrics", "getEndpoints", "getNewAuthToken", "createTransport", "muteParticipant", "unmuteParticipant"]), connect.AgentAppClientMethods = { GET_CONTACT: "AgentAppService.Lcms.getContact", DELETE_SPEAKER: "AgentAppService.VoiceId.deleteSpeaker", ENROLL_BY_SESSION: "AgentAppService.VoiceId.enrollBySession", EVALUATE_SESSION: "AgentAppService.VoiceId.evaluateSession", DESCRIBE_SPEAKER: "AgentAppService.VoiceId.describeSpeaker", OPT_OUT_SPEAKER: "AgentAppService.VoiceId.optOutSpeaker", UPDATE_VOICE_ID_DATA: "AgentAppService.Lcms.updateVoiceIdData", DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" }, connect.MasterMethods = connect.makeEnum(["becomeMaster", "checkMaster"]); var t = function () { }; t.EMPTY_CALLBACKS = { success: function () { }, failure: function () { } }, t.prototype.call = function (e, n, o) { connect.assertNotNull(e, "method"); var r = n || {}, i = o || t.EMPTY_CALLBACKS; this._callImpl(e, r, i) }, t.prototype._callImpl = function (e, t, n) { throw new connect.NotImplementedError }; var n = function () { t.call(this) }; (n.prototype = Object.create(t.prototype)).constructor = n, n.prototype._callImpl = function (e, t, n) { if (n && n.failure) { var o = connect.sprintf("No such method exists on NULL client: %s", e); n.failure(new connect.ValueError(o), { message: o }) } }; var o = function (e, n, o) { t.call(this), this.conduit = e, this.requestEvent = n, this.responseEvent = o, this._requestIdCallbacksMap = {}, this.conduit.onUpstream(o, connect.hitch(this, this._handleResponse)) }; (o.prototype = Object.create(t.prototype)).constructor = o, o.prototype._callImpl = function (e, t, n) { var o = connect.EventFactory.createRequest(this.requestEvent, e, t); this._requestIdCallbacksMap[o.requestId] = n, this.conduit.sendUpstream(o.event, o) }, o.prototype._getCallbacksForRequest = function (e) { var t = this._requestIdCallbacksMap[e] || null; return null != t && delete this._requestIdCallbacksMap[e], t }, o.prototype._handleResponse = function (e) { var t = this._getCallbacksForRequest(e.requestId); null != t && (e.err && t.failure ? t.failure(e.err, e.data) : t.success && t.success(e.data)) }; var r = function (e) { o.call(this, e, connect.EventType.API_REQUEST, connect.EventType.API_RESPONSE) }; (r.prototype = Object.create(o.prototype)).constructor = r; var i = function (e) { o.call(this, e, connect.EventType.MASTER_REQUEST, connect.EventType.MASTER_RESPONSE) }; (i.prototype = Object.create(o.prototype)).constructor = i; var s = function (e, n, o) { connect.assertNotNull(e, "authCookieName"), connect.assertNotNull(n, "authToken"), connect.assertNotNull(o, "endpoint"), t.call(this), this.endpointUrl = connect.getUrlWithProtocol(o), this.authToken = n, this.authCookieName = e }; (s.prototype = Object.create(t.prototype)).constructor = s, s.prototype._callImpl = function (e, t, n) { var o = this, r = {}; r[o.authCookieName] = o.authToken; var i = { method: "post", body: JSON.stringify(t || {}), headers: { Accept: "application/json", "Content-Type": "application/json", "X-Amz-target": e, "X-Amz-Bearer": JSON.stringify(r) } }; connect.fetch(o.endpointUrl, i).then((function (e) { n.success(e) })).catch((function (e) { var t = e.body.getReader(), o = "", r = new TextDecoder; t.read().then((function i(s) { var c = s.done, a = s.value; if (c) { var u = JSON.parse(o); return u.status = e.status, void n.failure(u) } return o += r.decode(a), t.read().then(i) })) })) }; var c = function (e, n, o) { connect.assertNotNull(e, "authToken"), connect.assertNotNull(n, "region"), t.call(this), AWS.config.credentials = new AWS.Credentials({}), AWS.config.region = n, this.authToken = e; var r = connect.getBaseUrl(), i = o || (r.includes(".awsapps.com") ? r + "/connect/api" : r + "/api"), s = new AWS.Endpoint(i); this.client = new AWS.Connect({ endpoint: s }) }; (c.prototype = Object.create(t.prototype)).constructor = c, c.prototype._callImpl = function (e, t, n) { var o = this, r = connect.getLog(); if (connect.contains(this.client, e)) t = this._translateParams(e, t), r.trace("AWSClient: --\x3e Calling operation '%s'", e).sendInternalLogToServer(), this.client[e](t).on("build", (function (e) { e.httpRequest.headers["X-Amz-Bearer"] = o.authToken })).send((function (t, o) { try { if (t) { if (t.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION) n.authFailure(); else if (!n.accessDenied || t.code !== connect.CTIExceptions.ACCESS_DENIED_EXCEPTION && 403 !== t.statusCode) { var i = {}; i.type = t.code, i.message = t.message, i.stack = t.stack ? t.stack.split("\n") : [], n.failure(i, o) } else n.accessDenied(); r.trace("AWSClient: <-- Operation '%s' failed: %s", e, JSON.stringify(t)).sendInternalLogToServer() } else r.trace("AWSClient: <-- Operation '%s' succeeded.", e).withObject(o).sendInternalLogToServer(), n.success(o) } catch (t) { connect.getLog().error("Failed to handle AWS API request for method %s", e).withException(t).sendInternalLogToServer() } })); else { var i = connect.sprintf("No such method exists on AWS client: %s", e); n.failure(new connect.ValueError(i), { message: i }) } }, c.prototype._requiresAuthenticationParam = function (e) { return e !== connect.ClientMethods.COMPLETE_CONTACT && e !== connect.ClientMethods.CLEAR_CONTACT && e !== connect.ClientMethods.REJECT_CONTACT && e !== connect.ClientMethods.CREATE_TASK_CONTACT }, c.prototype._translateParams = function (e, t) { switch (e) { case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: t.configuration = this._translateAgentConfiguration(t.configuration); break; case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: t.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(t.softphoneStreamStatistics); break; case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: t.report = this._translateSoftphoneCallReport(t.report) }return this._requiresAuthenticationParam(e) && (t.authentication = { authToken: this.authToken }), t }, c.prototype._translateAgentConfiguration = function (e) { return { name: e.name, softphoneEnabled: e.softphoneEnabled, softphoneAutoAccept: e.softphoneAutoAccept, extension: e.extension, routingProfile: this._translateRoutingProfile(e.routingProfile), agentPreferences: e.agentPreferences } }, c.prototype._translateRoutingProfile = function (e) { return { name: e.name, routingProfileARN: e.routingProfileARN, defaultOutboundQueue: this._translateQueue(e.defaultOutboundQueue) } }, c.prototype._translateQueue = function (e) { return { queueARN: e.queueARN, name: e.name } }, c.prototype._translateSoftphoneStreamStatistics = function (e) { return e.forEach((function (e) { "packetsCount" in e && (e.packetCount = e.packetsCount, delete e.packetsCount) })), e }, c.prototype._translateSoftphoneCallReport = function (e) { return "handshakingTimeMillis" in e && (e.handshakeTimeMillis = e.handshakingTimeMillis, delete e.handshakingTimeMillis), "preTalkingTimeMillis" in e && (e.preTalkTimeMillis = e.preTalkingTimeMillis, delete e.preTalkingTimeMillis), "handshakingFailure" in e && (e.handshakeFailure = e.handshakingFailure, delete e.handshakingFailure), "talkingTimeMillis" in e && (e.talkTimeMillis = e.talkingTimeMillis, delete e.talkingTimeMillis), e.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics), e }, connect.ClientBase = t, connect.NullClient = n, connect.UpstreamConduitClient = r, connect.UpstreamConduitMasterClient = i, connect.AWSClient = c, connect.AgentAppClient = s }() }, 531: () => { function e(e, n) { var o = "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"]; if (!o) { if (Array.isArray(e) || (o = function (e, n) { if (e) { if ("string" == typeof e) return t(e, n); var o = Object.prototype.toString.call(e).slice(8, -1); return "Object" === o && e.constructor && (o = e.constructor.name), "Map" === o || "Set" === o ? Array.from(e) : "Arguments" === o || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o) ? t(e, n) : void 0 } }(e)) || n && e && "number" == typeof e.length) { o && (e = o); var r = 0, i = function () { }; return { s: i, n: function () { return r >= e.length ? { done: !0 } : { done: !1, value: e[r++] } }, e: function (e) { throw e }, f: i } } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.") } var s, c = !0, a = !1; return { s: function () { o = o.call(e) }, n: function () { var e = o.next(); return c = e.done, e }, e: function (e) { a = !0, s = e }, f: function () { try { c || null == o.return || o.return() } finally { if (a) throw s } } } } function t(e, t) { (null == t || t > e.length) && (t = e.length); for (var n = 0, o = new Array(t); n < t; n++)o[n] = e[n]; return o } !function () { var t = this; connect = t.connect || {}, t.connect = connect, t.lily = connect, connect.core = {}, connect.core.initialized = !1, connect.version = "1.7.6", connect.DEFAULT_BATCH_SIZE = 500; var n = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}", o = "06919f4fd8ed324e", r = "/auth/authorize", i = "/connect/auth/authorize"; connect.numberOfConnectedCCPs = 0; var s = "Amazon Connect CCP"; function c(e) { var t = e.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/gi); return t.length ? t[0] : "" } connect.core.checkNotInitialized = function () { connect.core.initialized && connect.getLog().warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer() }, connect.core.init = function (e) { connect.core.eventBus = new connect.EventBus, connect.core.agentDataProvider = new h(connect.core.getEventBus()), connect.core.initClient(e), connect.core.initAgentAppClient(e), connect.core.initialized = !0 }, connect.core.initClient = function (e) { connect.assertNotNull(e, "params"); var t = connect.assertNotNull(e.authToken, "params.authToken"), n = connect.assertNotNull(e.region, "params.region"), o = e.endpoint || null; connect.core.client = new connect.AWSClient(t, n, o) }, connect.core.initAgentAppClient = function (e) { connect.assertNotNull(e, "params"); var t = connect.assertNotNull(e.authToken, "params.authToken"), n = connect.assertNotNull(e.authCookieName, "params.authCookieName"), o = connect.assertNotNull(e.agentAppEndpoint, "params.agentAppEndpoint"); connect.core.agentAppClient = new connect.AgentAppClient(n, t, o) }, connect.core.terminate = function () { connect.core.client = new connect.NullClient, connect.core.agentAppClient = new connect.NullClient, connect.core.masterClient = new connect.NullClient; var e = connect.core.getEventBus(); e && e.unsubscribeAll(), connect.core.bus = new connect.EventBus, connect.core.agentDataProvider = null, connect.core.softphoneManager = null, connect.core.upstream = null, connect.core.keepaliveManager = null, connect.agent.initialized = !1, connect.core.initialized = !1 }, connect.core.softphoneUserMediaStream = null, connect.core.getSoftphoneUserMediaStream = function () { return connect.core.softphoneUserMediaStream }, connect.core.setSoftphoneUserMediaStream = function (e) { connect.core.softphoneUserMediaStream = e }, connect.core.initRingtoneEngines = function (e) { connect.assertNotNull(e, "params"); var t = function (e) { connect.assertNotNull(e, "ringtoneSettings"), connect.assertNotNull(e.voice, "ringtoneSettings.voice"), connect.assertTrue(e.voice.ringtoneUrl || e.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"), connect.assertNotNull(e.queue_callback, "ringtoneSettings.queue_callback"), connect.assertTrue(e.queue_callback.ringtoneUrl || e.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"), connect.core.ringtoneEngines = {}, connect.agent((function (t) { t.onRefresh((function () { connect.ifMaster(connect.MasterTopics.RINGTONE, (function () { e.voice.disabled || connect.core.ringtoneEngines.voice || (connect.core.ringtoneEngines.voice = new connect.VoiceRingtoneEngine(e.voice), connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer()), e.chat.disabled || connect.core.ringtoneEngines.chat || (connect.core.ringtoneEngines.chat = new connect.ChatRingtoneEngine(e.chat), connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer()), e.task.disabled || connect.core.ringtoneEngines.task || (connect.core.ringtoneEngines.task = new connect.TaskRingtoneEngine(e.task), connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer()), e.queue_callback.disabled || connect.core.ringtoneEngines.queue_callback || (connect.core.ringtoneEngines.queue_callback = new connect.QueueCallbackRingtoneEngine(e.queue_callback), connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer()) })) })) })), a() }, n = function (e, t) { e.ringtone = e.ringtone || {}, e.ringtone.voice = e.ringtone.voice || {}, e.ringtone.queue_callback = e.ringtone.queue_callback || {}, e.ringtone.chat = e.ringtone.chat || { disabled: !0 }, e.ringtone.task = e.ringtone.task || { disabled: !0 }, t.softphone && (t.softphone.disableRingtone && (e.ringtone.voice.disabled = !0, e.ringtone.queue_callback.disabled = !0), t.softphone.ringtoneUrl && (e.ringtone.voice.ringtoneUrl = t.softphone.ringtoneUrl, e.ringtone.queue_callback.ringtoneUrl = t.softphone.ringtoneUrl)), t.chat && (t.chat.disableRingtone && (e.ringtone.chat.disabled = !0), t.chat.ringtoneUrl && (e.ringtone.chat.ringtoneUrl = t.chat.ringtoneUrl)), t.ringtone && (e.ringtone.voice = connect.merge(e.ringtone.voice, t.ringtone.voice || {}), e.ringtone.queue_callback = connect.merge(e.ringtone.queue_callback, t.ringtone.voice || {}), e.ringtone.chat = connect.merge(e.ringtone.chat, t.ringtone.chat || {})) }; n(e, e), connect.isFramed() ? connect.core.getEventBus().subscribe(connect.EventType.CONFIGURE, (function (o) { this.unsubscribe(), n(e, o), t(e.ringtone) })) : t(e.ringtone) }; var a = function () { connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, u) }, u = function (e) { if (0 !== connect.keys(connect.core.ringtoneEngines).length && e && e.deviceId) { var t = e.deviceId; for (var n in connect.core.ringtoneEngines) connect.core.ringtoneEngines[n].setOutputDevice(t); connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, data: { deviceId: t } }) } }; connect.core.initSoftphoneManager = function (e) { connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); var t = e || {}, n = function (e) { var n = connect.merge(t.softphone || {}, e); connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(), connect.agent((function (e) { e.getChannelConcurrency(connect.ChannelType.VOICE) && e.onRefresh((function () { var t = this; connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(), connect.ifMaster(connect.MasterTopics.SOFTPHONE, (function () { connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(), !connect.core.softphoneManager && e.isSoftphoneEnabled() && (connect.becomeMaster(connect.MasterTopics.SEND_LOGS), connect.core.softphoneManager = new connect.SoftphoneManager(n), t.unsubscribe()) })) })) })) }; function o(e) { var n = connect.merge(t.softphone || {}, e); connect.core.softphoneParams = n, connect.isFirefoxBrowser() && (connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, (function (e) { if (e.data && e.data.topic === connect.MasterTopics.SOFTPHONE && e.data.takeOver && e.data.masterId !== connect.core.portStreamId) { connect.core.softphoneManager && (connect.core.softphoneManager.onInitContactSub.unsubscribe(), delete connect.core.softphoneManager); var t = connect.core.getSoftphoneUserMediaStream(); t && (t.getTracks().forEach((function (e) { e.stop() })), connect.core.setSoftphoneUserMediaStream(null)) } })), connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, (function () { connect.ifMaster(connect.MasterTopics.SOFTPHONE, (function () { connect.core.softphoneManager && connect.core.softphoneManager.startSession() }), (function () { connect.becomeMaster(connect.MasterTopics.SOFTPHONE, (function () { connect.agent((function (e) { !connect.core.softphoneManager && e.isSoftphoneEnabled() && (connect.becomeMaster(connect.MasterTopics.SEND_LOGS), connect.core.softphoneManager = new connect.SoftphoneManager(n), connect.core.softphoneManager.startSession()) })) })) })) })), connect.contact((function (e) { connect.agent((function (t) { e.onRefresh((function (e) { if (connect.hasOtherConnectedCCPs() && "visible" === document.visibilityState && (e.getStatus().type === connect.ContactStatusType.CONNECTING || e.getStatus().type === connect.ContactStatusType.INCOMING)) { var n = e.isSoftphoneCall() && !e.isInbound(), o = e.isSoftphoneCall() && t.getConfiguration().softphoneAutoAccept, r = e.getType() === connect.ContactType.QUEUE_CALLBACK; (n || o || r) && connect.core.triggerReadyToStartSessionEvent() } })) })) }))) } connect.isFramed() && !t.allowFramedSoftphone ? connect.core.getEventBus().subscribe(connect.EventType.CONFIGURE, (function (e) { connect.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(), e.softphone && e.softphone.allowFramedSoftphone && (this.unsubscribe(), n(e.softphone)), o(e.softphone) })) : (n(t), o(t)), connect.agent((function (e) { e.isSoftphoneEnabled() && e.getChannelConcurrency(connect.ChannelType.VOICE) && connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.MUTE }) })) }, connect.core.triggerReadyToStartSessionEvent = function () { var e = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; connect.isCCP() ? e ? connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION) : connect.isFramed() ? connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION) : connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION) : e ? connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION) : connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION) }, connect.core.initPageOptions = function (e) { if (connect.assertNotNull(e, "params"), connect.isFramed()) { var t = connect.core.getEventBus(); t.subscribe(connect.EventType.CONFIGURE, (function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.CONFIGURE, data: e }) })), t.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, (function () { function e(e) { connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, e) } navigator && navigator.mediaDevices ? navigator.mediaDevices.enumerateDevices().then((function (t) { devices = t || [], devices = devices.map((function (e) { return e.toJSON() })), e(devices) })).catch((function (t) { e({ error: t.message }) })) : e({ error: "No navigator or navigator.mediaDevices object found" }) })) } }, connect.core.getFrameMediaDevices = function (e) { var t = null, n = e || 1e3, o = new Promise((function (e, t) { setTimeout((function () { t(new Error("Timeout exceeded")) }), n) })), r = new Promise((function (e, n) { if (connect.isFramed() || connect.isCCP()) navigator && navigator.mediaDevices ? navigator.mediaDevices.enumerateDevices().then((function (t) { devices = t || [], devices = devices.map((function (e) { return e.toJSON() })), e(devices) })) : n(new Error("No navigator or navigator.mediaDevices object found")); else { var o = connect.core.getEventBus(); t = o.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, (function (t) { t.error ? n(new Error(t.error)) : e(t) })), connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST) } })); return Promise.race([r, o]).finally((function () { t && t.unsubscribe() })) }, connect.core.authorize = function (e) { var t = e; return t || (t = connect.core.isLegacyDomain() ? i : r), connect.fetch(t, { credentials: "include" }, 2e3, 5) }, connect.core.verifyDomainAccess = function (e, t) { if (connect.getLog().warn("This API will be deprecated in the next major version release"), !connect.isFramed()) return Promise.resolve(); var n = { headers: { "X-Amz-Bearer": e } }, o = null; return o = t || (connect.core.isLegacyDomain() ? "/connect/whitelisted-origins" : "/whitelisted-origins"), connect.fetch(o, n, 2e3, 5).then((function (e) { var t = c(window.document.referrer); return e.whitelistedOrigins.some((function (e) { return t === c(e) })) ? Promise.resolve() : Promise.reject() })) }, connect.core.isLegacyDomain = function (e) { return (e = e || window.location.href).includes(".awsapps.com") }, connect.core.initSharedWorker = function (e) { if (connect.core.checkNotInitialized(), !connect.core.initialized) { connect.assertNotNull(e, "params"); var n = connect.assertNotNull(e.sharedWorkerUrl, "params.sharedWorkerUrl"), o = connect.assertNotNull(e.authToken, "params.authToken"), s = connect.assertNotNull(e.refreshToken, "params.refreshToken"), c = connect.assertNotNull(e.authTokenExpiration, "params.authTokenExpiration"), a = connect.assertNotNull(e.region, "params.region"), u = e.endpoint || null, l = e.authorizeEndpoint; l || (l = connect.core.isLegacyDomain() ? i : r); var d = e.agentAppEndpoint || null, f = e.authCookieName || null; try { connect.core.eventBus = new connect.EventBus({ logEvents: !0 }), connect.core.agentDataProvider = new h(connect.core.getEventBus()), connect.core.mediaFactory = new connect.MediaFactory(e); var g = new SharedWorker(n, "ConnectSharedWorker"), m = new connect.Conduit("ConnectSharedWorkerConduit", new connect.PortStream(g.port), new connect.WindowIOStream(window, parent)); connect.core.upstream = m, connect.core.webSocketProvider = new p, t.onunload = function () { m.sendUpstream(connect.EventType.CLOSE), g.port.close() }, connect.getLog().scheduleUpstreamLogPush(m), connect.getLog().scheduleDownstreamClientSideLogsPush(), m.onAllUpstream(connect.core.getEventBus().bridge()), m.onAllUpstream(m.passDownstream()), connect.isFramed() && (m.onAllDownstream(connect.core.getEventBus().bridge()), m.onAllDownstream(m.passUpstream())), m.sendUpstream(connect.EventType.CONFIGURE, { authToken: o, authTokenExpiration: c, endpoint: u, refreshToken: s, region: a, authorizeEndpoint: l, agentAppEndpoint: d, authCookieName: f }), m.onUpstream(connect.EventType.ACKNOWLEDGE, (function (e) { connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(), connect.core.initialized = !0, connect.core.portStreamId = e.id, this.unsubscribe() })), m.onUpstream(connect.EventType.LOG, (function (e) { e.loggerId !== connect.getLog().getLoggerId() && connect.getLog().addLogEntry(connect.LogEntry.fromObject(e)) })), m.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, (function (e) { connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(e)) })), m.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, (function (e) { connect.isFramed() && Array.isArray(e) && e.forEach((function (e) { connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(e)) })) })), m.onDownstream(connect.EventType.LOG, (function (e) { connect.isFramed() && e.loggerId !== connect.getLog().getLoggerId() && connect.getLog().addLogEntry(connect.LogEntry.fromObject(e)) })), m.onUpstream(connect.EventType.AUTH_FAIL, (function (e) { location.reload() })), connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(), connect.getLog().info("isCCPv2: " + !0).sendInternalLogToServer(), connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(), connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, (function (e) { var t = e.streamsVersion; connect.getLog().info("StreamsJS Version: " + t).sendInternalLogToServer() })), m.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, (function (e) { connect.getLog().info("Number of connected CCPs updated: " + e.length).sendInternalLogToServer(), connect.numberOfConnectedCCPs = e.length })), connect.core.client = new connect.UpstreamConduitClient(m), connect.core.masterClient = new connect.UpstreamConduitMasterClient(m), connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, m.passUpstream()), connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, (function () { window.location.reload(!0) })), g.port.start(), m.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, (function (e) { e && e.domainId && (connect.core.voiceIdDomainId = e.domainId) })), connect.agent((function () { (new connect.VoiceId).getDomainId().then((function (e) { connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + e).sendInternalLogToServer() })).catch((function (e) { connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ err: e }).sendInternalLogToServer() })) })), connect.core.getNotificationManager().requestPermission() } catch (e) { connect.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer() } } }, connect.core._getCCPIframe = function () { var t, n = e(window.document.getElementsByTagName("iframe")); try { for (n.s(); !(t = n.n()).done;) { var o = t.value; if (o.name === s) return o } } catch (e) { n.e(e) } finally { n.f() } return null }, connect.core.initCCP = function (e, r) { if (connect.core.checkNotInitialized(), !connect.core.initialized) { var i = {}; "string" == typeof r ? i.ccpUrl = r : i = r, connect.assertNotNull(e, "containerDiv"), connect.assertNotNull(i.ccpUrl, "params.ccpUrl"), connect.storageAccess.init(i.ccpUrl, e, i.storageAccess || {}); var c = document.createElement("iframe"); c.src = i.ccpUrl, c.allow = "microphone; autoplay", c.style = "width: 100%; height: 100%", c.title = "Amazon Connect CCP", c.name = s, connect.storageAccess.canRequest() && (c.src = connect.storageAccess.getRequestStorageAccessUrl(), c.addEventListener("load", connect.storageAccess.request)), e.appendChild(c); var a = new connect.IFrameConduit(i.ccpUrl, window, c); connect.core.upstream = a, connect.core.eventBus = new connect.EventBus({ logEvents: !1 }), connect.core.agentDataProvider = new h(connect.core.getEventBus()), connect.core.mediaFactory = new connect.MediaFactory(i), connect.storageAccess.canRequest() ? connect.storageAccess.setupRequestHandlers({ onGrant: u }) : u() } function u() { c.onload = setTimeout((function () { var e = { display: window.getComputedStyle(c, null).display, offsetWidth: c.offsetWidth, offsetHeight: c.offsetHeight, clientRectsLength: c.getClientRects().length }; a.sendUpstream(connect.EventType.IFRAME_STYLE, e) }), 1e4), connect.core.webSocketProvider = new p, a.onAllUpstream(connect.core.getEventBus().bridge()), connect.core.keepaliveManager = new l(a, connect.core.getEventBus(), i.ccpSynTimeout || 1e3, i.ccpAckTimeout || 3e3), connect.core.iframeRefreshInterval = null, connect.core.ccpLoadTimeoutInstance = t.setTimeout((function () { connect.core.ccpLoadTimeoutInstance = null, connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT) }), i.ccpLoadTimeout || 5e3), connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(a), connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(a), a.onUpstream(connect.EventType.ACKNOWLEDGE, (function (e) { connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(), connect.core.client = new connect.UpstreamConduitClient(a), connect.core.masterClient = new connect.UpstreamConduitMasterClient(a), connect.core.portStreamId = e.id, (i.softphone || i.chat || i.pageOptions) && a.sendUpstream(connect.EventType.CONFIGURE, { softphone: i.softphone, chat: i.chat, pageOptions: i.pageOptions }), connect.core.ccpLoadTimeoutInstance && (t.clearTimeout(connect.core.ccpLoadTimeoutInstance), connect.core.ccpLoadTimeoutInstance = null), a.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { streamsVersion: connect.version }), connect.core.keepaliveManager.start(), this.unsubscribe(), connect.core.initialized = !0, connect.core.getEventBus().trigger(connect.EventType.INIT) })), a.onUpstream(connect.EventType.LOG, (function (e) { e.loggerId !== connect.getLog().getLoggerId() && connect.getLog().addLogEntry(connect.LogEntry.fromObject(e)) })), connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, (function () { if (!1 !== i.loginPopup) try { var e = function (e) { var r = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; return connect.assertNotNull(r), e.loginUrl ? e.loginUrl : e.alias ? (log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."), n.replace("{alias}", e.alias).replace("{client_id}", o).replace("{redirect}", t.encodeURIComponent(r))) : e.ccpUrl }(i); connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(), i.loginUrl && connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP), connect.core.loginWindow = connect.core.getPopupManager().open(e, connect.MasterTopics.LOGIN_POPUP, i.loginOptions) } catch (e) { connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer() } null == connect.core.iframeRefreshInterval && (connect.core.iframeRefreshInterval = window.setInterval((function () { connect.storageAccess.canRequest() ? (c.removeEventListener("load", connect.storageAccess.request), c.addEventListener("load", connect.storageAccess.request), c.src = connect.storageAccess.getRequestStorageAccessUrl()) : c.src = i.ccpUrl }), 5e3), a.onUpstream(connect.EventType.ACKNOWLEDGE, (function () { this.unsubscribe(), t.clearInterval(connect.core.iframeRefreshInterval), connect.core.iframeRefreshInterval = null, connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP), (i.loginPopupAutoClose || i.loginOptions && i.loginOptions.autoClose) && connect.core.loginWindow && (connect.core.loginWindow.close(), connect.core.loginWindow = null) }))) })), i.onViewContact && connect.core.onViewContact(i.onViewContact), a.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, (function (e) { connect.numberOfConnectedCCPs = e.length })), a.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, (function (e) { e && e.domainId && (connect.core.voiceIdDomainId = e.domainId) })), connect.core.softphoneParams = i.softphone } }; var l = function (e, t, n, o) { this.conduit = e, this.eventBus = t, this.synTimeout = n, this.ackTimeout = o, this.ackTimer = null, this.synTimer = null, this.ackSub = null }; l.prototype.start = function () { var e = this; this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE), this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, (function () { this.unsubscribe(), t.clearTimeout(e.ackTimer), e._deferStart() })), this.ackTimer = t.setTimeout((function () { e.ackSub.unsubscribe(), e.eventBus.trigger(connect.EventType.ACK_TIMEOUT), e._deferStart() }), this.ackTimeout) }, l.prototype._deferStart = function () { this.synTimer = t.setTimeout(connect.hitch(this, this.start), this.synTimeout) }, l.prototype.deferStart = function () { null == this.synTimer && (this.synTimer = t.setTimeout(connect.hitch(this, this.start), this.synTimeout)) }; var p = function () { var e = { initFailure: new Set, subscriptionUpdate: new Set, subscriptionFailure: new Set, topic: new Map, allMessage: new Set, connectionGain: new Set, connectionLost: new Set, connectionOpen: new Set, connectionClose: new Set }, t = function (e, t) { e.forEach((function (e) { e(t) })) }; connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, (function () { t(e.initFailure) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, (function (n) { t(e.connectionOpen, n) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, (function (n) { t(e.connectionClose, n) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, (function () { t(e.connectionGain) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, (function (n) { t(e.connectionLost, n) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, (function (n) { t(e.subscriptionUpdate, n) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, (function (n) { t(e.subscriptionFailure, n) })), connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, (function (n) { t(e.allMessage, n), e.topic.has(n.topic) && t(e.topic.get(n.topic), n) })), this.sendMessage = function (e) { connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, e) }, this.onInitFailure = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.initFailure.add(t), function () { return e.initFailure.delete(t) } }, this.onConnectionOpen = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.connectionOpen.add(t), function () { return e.connectionOpen.delete(t) } }, this.onConnectionClose = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.connectionClose.add(t), function () { return e.connectionClose.delete(t) } }, this.onConnectionGain = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.connectionGain.add(t), function () { return e.connectionGain.delete(t) } }, this.onConnectionLost = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.connectionLost.add(t), function () { return e.connectionLost.delete(t) } }, this.onSubscriptionUpdate = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.subscriptionUpdate.add(t), function () { return e.subscriptionUpdate.delete(t) } }, this.onSubscriptionFailure = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.subscriptionFailure.add(t), function () { return e.subscriptionFailure.delete(t) } }, this.subscribeTopics = function (e) { connect.assertNotNull(e, "topics"), connect.assertTrue(connect.isArray(e), "topics must be a array"), connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, e) }, this.onMessage = function (t, n) { return connect.assertNotNull(t, "topicName"), connect.assertTrue(connect.isFunction(n), "method must be a function"), e.topic.has(t) ? e.topic.get(t).add(n) : e.topic.set(t, new Set([n])), function () { return e.topic.get(t).delete(n) } }, this.onAllMessage = function (t) { return connect.assertTrue(connect.isFunction(t), "method must be a function"), e.allMessage.add(t), function () { return e.allMessage.delete(t) } } }, h = function (e) { this.bus = e, this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)) }; h.prototype.updateAgentData = function (e) { var t = this.agentData; this.agentData = e, null == t && (connect.agent.initialized = !0, this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent)), this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent), this._fireAgentUpdateEvents(t) }, h.prototype.getAgentData = function () { if (null == this.agentData) throw new connect.StateError("No agent data is available yet!"); return this.agentData }, h.prototype.getContactData = function (e) { var t = this.getAgentData(), n = connect.find(t.snapshot.contacts, (function (t) { return t.contactId === e })); if (null == n) throw new connect.StateError("Contact %s no longer exists.", e); return n }, h.prototype.getConnectionData = function (e, t) { var n = this.getContactData(e), o = connect.find(n.connections, (function (e) { return e.connectionId === t })); if (null == o) throw new connect.StateError("Connection %s for contact %s no longer exists.", t, e); return o }, h.prototype.getInstanceId = function () { return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1] }, h.prototype.getAWSAccountId = function () { return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1] }, h.prototype._diffContacts = function (e) { var t = { added: {}, removed: {}, common: {}, oldMap: connect.index(null == e ? [] : e.snapshot.contacts, (function (e) { return e.contactId })), newMap: connect.index(this.agentData.snapshot.contacts, (function (e) { return e.contactId })) }; return connect.keys(t.oldMap).forEach((function (e) { connect.contains(t.newMap, e) ? t.common[e] = t.newMap[e] : t.removed[e] = t.oldMap[e] })), connect.keys(t.newMap).forEach((function (e) { connect.contains(t.oldMap, e) || (t.added[e] = t.newMap[e]) })), t }, h.prototype._fireAgentUpdateEvents = function (e) { var t = this, n = null, o = null == e ? connect.AgentAvailStates.INIT : e.snapshot.state.name, r = this.agentData.snapshot.state.name, i = null == e ? connect.AgentStateType.INIT : e.snapshot.state.type, s = this.agentData.snapshot.state.type; i !== s && connect.core.getAgentRoutingEventGraph().getAssociations(this, i, s).forEach((function (e) { t.bus.trigger(e, new connect.Agent) })), o !== r && (this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { agent: new connect.Agent, oldState: o, newState: r }), connect.core.getAgentStateEventGraph().getAssociations(this, o, r).forEach((function (e) { t.bus.trigger(e, new connect.Agent) }))); var c = e && e.snapshot.nextState ? e.snapshot.nextState.name : null, a = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; c !== a && a && t.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent), n = null !== e ? this._diffContacts(e) : { added: connect.index(this.agentData.snapshot.contacts, (function (e) { return e.contactId })), removed: {}, common: {}, oldMap: {}, newMap: connect.index(this.agentData.snapshot.contacts, (function (e) { return e.contactId })) }, connect.values(n.added).forEach((function (e) { t.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(e.contactId)), t._fireContactUpdateEvents(e.contactId, connect.ContactStateType.INIT, e.state.type) })), connect.values(n.removed).forEach((function (e) { t.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(e)), t.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, e.contactId), new connect.ContactSnapshot(e)), t._unsubAllContactEventsForContact(e.contactId) })), connect.keys(n.common).forEach((function (e) { t._fireContactUpdateEvents(e, n.oldMap[e].state.type, n.newMap[e].state.type) })) }, h.prototype._fireContactUpdateEvents = function (e, t, n) { var o = this; t !== n && connect.core.getContactEventGraph().getAssociations(this, t, n).forEach((function (t) { o.bus.trigger(t, new connect.Contact(e)), o.bus.trigger(connect.core.getContactEventName(t, e), new connect.Contact(e)) })), o.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(e)), o.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, e), new connect.Contact(e)) }, h.prototype._unsubAllContactEventsForContact = function (e) { var t = this; connect.values(connect.ContactEvents).forEach((function (n) { t.bus.getSubscriptions(connect.core.getContactEventName(n, e)).map((function (e) { e.unsubscribe() })) })) }, connect.core.onViewContact = function (e) { connect.core.getUpstream().onUpstream(connect.ContactEvents.VIEW, e) }, connect.core.viewContact = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.VIEW, data: { contactId: e } }) }, connect.core.onActivateChannelWithViewType = function (e) { connect.core.getUpstream().onUpstream(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, e) }, connect.core.activateChannelWithViewType = function (e, t, n) { var o = { viewType: e, mediaType: t }; n && (o.source = n), connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, data: o }) }, connect.core.triggerTaskCreated = function (e) { connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, e) }, connect.core.onAccessDenied = function (e) { connect.core.getUpstream().onUpstream(connect.EventType.ACCESS_DENIED, e) }, connect.core.onAuthFail = function (e) { connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, e) }, connect.core.onSoftphoneSessionInit = function (e) { connect.core.getUpstream().onUpstream(connect.ConnectionEvents.SESSION_INIT, e) }, connect.core.onConfigure = function (e) { connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.CONFIGURE, e) }, connect.core.onInitialized = function (e) { connect.core.getEventBus().subscribe(connect.EventType.INIT, e) }, connect.core.getContactEventName = function (e, t) { if (connect.assertNotNull(e, "eventName"), connect.assertNotNull(t, "contactId"), !connect.contains(connect.values(connect.ContactEvents), e)) throw new connect.ValueError("%s is not a valid contact event.", e); return connect.sprintf("%s::%s", e, t) }, connect.core.getEventBus = function () { return connect.core.eventBus }, connect.core.getWebSocketManager = function () { return connect.core.webSocketProvider }, connect.core.getAgentDataProvider = function () { return connect.core.agentDataProvider }, connect.core.getLocalTimestamp = function () { return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp }, connect.core.getSkew = function () { return connect.core.getAgentDataProvider().getAgentData().snapshot.skew }, connect.core.getAgentRoutingEventGraph = function () { return connect.core.agentRoutingEventGraph }, connect.core.agentRoutingEventGraph = (new connect.EventGraph).assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, connect.AgentEvents.ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, connect.AgentEvents.NOT_ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, connect.AgentEvents.OFFLINE), connect.core.getAgentStateEventGraph = function () { return connect.core.agentStateEventGraph }, connect.core.agentStateEventGraph = (new connect.EventGraph).assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.AgentEvents.ERROR).assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, connect.AgentEvents.ACW), connect.core.getContactEventGraph = function () { return connect.core.contactEventGraph }, connect.core.contactEventGraph = (new connect.EventGraph).assoc(connect.EventGraph.ANY, connect.ContactStateType.INCOMING, connect.ContactEvents.INCOMING).assoc(connect.EventGraph.ANY, connect.ContactStateType.PENDING, connect.ContactEvents.PENDING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTING, connect.ContactEvents.CONNECTING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTED, connect.ContactEvents.CONNECTED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ENDED, connect.ContactEvents.ACW).assoc(connect.values(connect.CONTACT_ACTIVE_STATES), connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), connect.ContactEvents.ENDED).assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.ContactEvents.ERROR).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED), connect.core.getClient = function () { if (!connect.core.client) throw new connect.StateError("The connect core has not been initialized!"); return connect.core.client }, connect.core.client = null, connect.core.getAgentAppClient = function () { if (!connect.core.agentAppClient) throw new connect.StateError("The connect AgentApp Client has not been initialized!"); return connect.core.agentAppClient }, connect.core.agentAppClient = null, connect.core.getMasterClient = function () { if (!connect.core.masterClient) throw new connect.StateError("The connect master client has not been initialized!"); return connect.core.masterClient }, connect.core.masterClient = null, connect.core.getSoftphoneManager = function () { return connect.core.softphoneManager }, connect.core.softphoneManager = null, connect.core.getNotificationManager = function () { return connect.core.notificationManager || (connect.core.notificationManager = new connect.NotificationManager), connect.core.notificationManager }, connect.core.notificationManager = null, connect.core.getPopupManager = function () { return connect.core.popupManager }, connect.core.popupManager = new connect.PopupManager, connect.core.getUpstream = function () { if (!connect.core.upstream) throw new connect.StateError("There is no upstream conduit!"); return connect.core.upstream }, connect.core.upstream = null, connect.core.AgentDataProvider = h }() }, 547: () => { !function () { connect = this.connect || {}, this.connect = connect; var e = "<>", t = connect.makeEnum(["acknowledge", "ack_timeout", "init", "api_request", "api_response", "auth_fail", "access_denied", "close", "configure", "log", "master_request", "master_response", "synchronize", "terminate", "terminated", "send_logs", "reload_agent_configuration", "broadcast", "api_metric", "client_metric", "softphone_stats", "softphone_report", "client_side_logs", "server_bound_internal_log", "mute", "iframe_style", "update_connected_ccps", "outer_context_info", "media_device_request", "media_device_response"]), n = connect.makeNamespacedEnum("connect", ["loginPopup", "sendLogs", "softphone", "ringtone", "metrics"]), o = connect.makeNamespacedEnum("agent", ["init", "update", "refresh", "routable", "not_routable", "pending", "contact_pending", "offline", "error", "softphone_error", "websocket_connection_lost", "websocket_connection_gained", "state_change", "acw", "mute_toggle", "local_media_stream_created", "enqueued_next_state"]), r = connect.makeNamespacedEnum("webSocket", ["init_failure", "connection_open", "connection_close", "connection_error", "connection_gain", "connection_lost", "subscription_update", "subscription_failure", "all_message", "send", "subscribe"]), i = connect.makeNamespacedEnum("contact", ["init", "refresh", "destroyed", "incoming", "pending", "connecting", "connected", "missed", "acw", "view", "ended", "error", "accepted"]), s = connect.makeNamespacedEnum("taskList", ["activate_channel_with_view_type"]), c = connect.makeNamespacedEnum("task", ["created"]), a = connect.makeNamespacedEnum("connection", ["session_init", "ready_to_start_session"]), u = connect.makeNamespacedEnum("configuration", ["configure", "set_speaker_device", "set_microphone_device", "set_ringer_device", "speaker_device_changed", "microphone_device_changed", "ringer_device_changed"]), l = connect.makeNamespacedEnum("voiceId", ["update_domain_id"]), p = function () { }; p.createRequest = function (e, t, n) { return { event: e, requestId: connect.randomId(), method: t, params: n } }, p.createResponse = function (e, t, n, o) { return { event: e, requestId: t.requestId, data: n, err: o || null } }; var h = function (e, t, n) { this.subMap = e, this.id = connect.randomId(), this.eventName = t, this.f = n }; h.prototype.unsubscribe = function () { this.subMap.unsubscribe(this.eventName, this.id) }; var d = function () { this.subIdMap = {}, this.subEventNameMap = {} }; d.prototype.subscribe = function (e, t) { var n = new h(this, e, t); this.subIdMap[n.id] = n; var o = this.subEventNameMap[e] || []; return o.push(n), this.subEventNameMap[e] = o, n }, d.prototype.unsubscribe = function (e, t) { connect.contains(this.subEventNameMap, e) && (this.subEventNameMap[e] = this.subEventNameMap[e].filter((function (e) { return e.id !== t })), this.subEventNameMap[e].length < 1 && delete this.subEventNameMap[e]), connect.contains(this.subIdMap, t) && delete this.subIdMap[t] }, d.prototype.getAllSubscriptions = function () { return connect.values(this.subEventNameMap).reduce((function (e, t) { return e.concat(t) }), []) }, d.prototype.getSubscriptions = function (e) { return this.subEventNameMap[e] || [] }; var f = function (e) { var t = e || {}; this.subMap = new d, this.logEvents = t.logEvents || !1 }; f.prototype.subscribe = function (e, t) { return connect.assertNotNull(e, "eventName"), connect.assertNotNull(t, "f"), connect.assertTrue(connect.isFunction(t), "f must be a function"), this.subMap.subscribe(e, t) }, f.prototype.subscribeAll = function (t) { return connect.assertNotNull(t, "f"), connect.assertTrue(connect.isFunction(t), "f must be a function"), this.subMap.subscribe(e, t) }, f.prototype.getSubscriptions = function (e) { return this.subMap.getSubscriptions(e) }, f.prototype.trigger = function (t, n) { connect.assertNotNull(t, "eventName"); var o = this, r = this.subMap.getSubscriptions(e), i = this.subMap.getSubscriptions(t); this.logEvents && t !== connect.EventType.LOG && t !== connect.EventType.MASTER_RESPONSE && t !== connect.EventType.API_METRIC && t !== connect.EventType.SERVER_BOUND_INTERNAL_LOG && connect.getLog().trace("Publishing event: %s", t).sendInternalLogToServer(), t.startsWith(connect.ContactEvents.ACCEPTED) && n && n.contactId && !(n instanceof connect.Contact) && (n = new connect.Contact(n.contactId)), r.concat(i).forEach((function (e) { try { e.f(n || null, t, o) } catch (e) { connect.getLog().error("'%s' event handler failed.", t).withException(e).sendInternalLogToServer() } })) }, f.prototype.bridge = function () { var e = this; return function (t, n) { e.trigger(n, t) } }, f.prototype.unsubscribeAll = function () { this.subMap.getAllSubscriptions().forEach((function (e) { e.unsubscribe() })) }, connect.EventBus = f, connect.EventFactory = p, connect.EventType = t, connect.AgentEvents = o, connect.ConfigurationEvents = u, connect.ConnectionEvents = a, connect.ConnnectionEvents = a, connect.ContactEvents = i, connect.ChannelViewEvents = s, connect.TaskEvents = c, connect.VoiceIdEvents = l, connect.WebSocketEvents = r, connect.MasterTopics = n }() }, 42: () => { function e(t) { return e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, e(t) } !function (t) { var n = {}; function o(e) { if (n[e]) return n[e].exports; var r = n[e] = { i: e, l: !1, exports: {} }; return t[e].call(r.exports, r, r.exports, o), r.l = !0, r.exports } o.m = t, o.c = n, o.d = function (e, t, n) { o.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: n }) }, o.r = function (e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }) }, o.t = function (t, n) { if (1 & n && (t = o(t)), 8 & n) return t; if (4 & n && "object" == e(t) && t && t.__esModule) return t; var r = Object.create(null); if (o.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: t }), 2 & n && "string" != typeof t) for (var i in t) o.d(r, i, function (e) { return t[e] }.bind(null, i)); return r }, o.n = function (e) { var t = e && e.__esModule ? function () { return e.default } : function () { return e }; return o.d(t, "a", t), t }, o.o = function (e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, o.p = "", o(o.s = 2) }([function (t, n, o) { "use strict"; var r = o(1), i = "DEBUG", s = "aws/subscribe", c = "aws/heartbeat", a = "disconnected"; function u(t) { return (u = "function" == typeof Symbol && "symbol" == e(Symbol.iterator) ? function (t) { return e(t) } : function (t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : e(t) })(t) } var l = { assertTrue: function (e, t) { if (!e) throw new Error(t) }, assertNotNull: function (e, t) { return l.assertTrue(null !== e && void 0 !== u(e), Object(r.sprintf)("%s must be provided", t || "A value")), e }, isNonEmptyString: function (e) { return "string" == typeof e && e.length > 0 }, assertIsList: function (e, t) { if (!Array.isArray(e)) throw new Error(t + " is not an array") }, isFunction: function (e) { return !!(e && e.constructor && e.call && e.apply) }, isObject: function (e) { return !("object" !== u(e) || null === e) }, isString: function (e) { return "string" == typeof e }, isNumber: function (e) { return "number" == typeof e } }, p = new RegExp("^(wss://)\\w*"); l.validWSUrl = function (e) { return p.test(e) }, l.getSubscriptionResponse = function (e, t, n) { return { topic: e, content: { status: t ? "success" : "failure", topics: n } } }, l.assertIsObject = function (e, t) { if (!l.isObject(e)) throw new Error(t + " is not an object!") }, l.addJitter = function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1; t = Math.min(t, 1); var n = Math.random() > .5 ? 1 : -1; return Math.floor(e + n * e * Math.random() * t) }, l.isNetworkOnline = function () { return navigator.onLine }, l.isNetworkFailure = function (e) { return !(!e._debug || !e._debug.type) && "NetworkingError" === e._debug.type }; var h = l; function d(t) { return (d = "function" == typeof Symbol && "symbol" == e(Symbol.iterator) ? function (t) { return e(t) } : function (t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : e(t) })(t) } function f(e) { return (f = Object.setPrototypeOf ? Object.getPrototypeOf : function (e) { return e.__proto__ || Object.getPrototypeOf(e) })(e) } function g(e, t) { return (g = Object.setPrototypeOf || function (e, t) { return e.__proto__ = t, e })(e, t) } function m(e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") } function v(e, t) { for (var n = 0; n < t.length; n++) { var o = t[n]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o) } } function y(e, t, n) { return t && v(e.prototype, t), n && v(e, n), e } var E = function () { function e() { m(this, e) } return y(e, [{ key: "debug", value: function (e) { } }, { key: "info", value: function (e) { } }, { key: "warn", value: function (e) { } }, { key: "error", value: function (e) { } }]), e }(), S = { DEBUG: 10, INFO: 20, WARN: 30, ERROR: 40 }, b = function () { function e() { m(this, e), this.updateLoggerConfig(), this.consoleLoggerWrapper = I() } return y(e, [{ key: "writeToClientLogger", value: function (e, t) { if (this.hasClientLogger()) switch (e) { case S.DEBUG: return this._clientLogger.debug(t); case S.INFO: return this._clientLogger.info(t); case S.WARN: return this._clientLogger.warn(t); case S.ERROR: return this._clientLogger.error(t) } } }, { key: "isLevelEnabled", value: function (e) { return e >= this._level } }, { key: "hasClientLogger", value: function () { return null !== this._clientLogger } }, { key: "getLogger", value: function (e) { var t = e.prefix || ""; return this._logsDestination === i ? this.consoleLoggerWrapper : new T(t) } }, { key: "updateLoggerConfig", value: function (e) { var t = e || {}; this._level = t.level || S.DEBUG, this._clientLogger = t.logger || null, this._logsDestination = "NULL", t.debug && (this._logsDestination = i), t.logger && (this._logsDestination = "CLIENT_LOGGER") } }]), e }(), C = function () { function e() { m(this, e) } return y(e, [{ key: "debug", value: function () { } }, { key: "info", value: function () { } }, { key: "warn", value: function () { } }, { key: "error", value: function () { } }]), e }(), T = function (e) { function t(e) { var n; return m(this, t), (n = function (e, t) { return !t || "object" !== d(t) && "function" != typeof t ? function (e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e }(e) : t }(this, f(t).call(this))).prefix = e || "", n } return function (e, t) { if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function"); e.prototype = Object.create(t && t.prototype, { constructor: { value: e, writable: !0, configurable: !0 } }), t && g(e, t) }(t, C), y(t, [{ key: "debug", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this._log(S.DEBUG, t) } }, { key: "info", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this._log(S.INFO, t) } }, { key: "warn", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this._log(S.WARN, t) } }, { key: "error", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this._log(S.ERROR, t) } }, { key: "_shouldLog", value: function (e) { return A.hasClientLogger() && A.isLevelEnabled(e) } }, { key: "_writeToClientLogger", value: function (e, t) { return A.writeToClientLogger(e, t) } }, { key: "_log", value: function (e, t) { if (this._shouldLog(e)) { var n = this._convertToSingleStatement(t); return this._writeToClientLogger(e, n) } } }, { key: "_convertToSingleStatement", value: function (e) { var t = ""; this.prefix && (t += this.prefix + " "); for (var n = 0; n < e.length; n++) { var o = e[n]; t += this._convertToString(o) + " " } return t } }, { key: "_convertToString", value: function (e) { try { if (!e) return ""; if (h.isString(e)) return e; if (h.isObject(e) && h.isFunction(e.toString)) { var t = e.toString(); if ("[object Object]" !== t) return t } return JSON.stringify(e) } catch (t) { return console.error("Error while converting argument to string", e, t), "" } } }]), t }(), I = function () { var e = new C; return e.debug = console.debug, e.info = console.info, e.warn = console.warn, e.error = console.error, e }, A = new b; function _(e, t) { for (var n = 0; n < t.length; n++) { var o = t[n]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o) } } var w = function () { function e(t) { var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 2e3; !function (e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") }(this, e), this.numAttempts = 0, this.executor = t, this.hasActiveReconnection = !1, this.defaultRetry = n } var t, n; return t = e, (n = [{ key: "retry", value: function () { var e = this; this.hasActiveReconnection || (this.hasActiveReconnection = !0, setTimeout((function () { e._execute() }), this._getDelay())) } }, { key: "_execute", value: function () { this.hasActiveReconnection = !1, this.executor(), this.numAttempts++ } }, { key: "connected", value: function () { this.numAttempts = 0 } }, { key: "_getDelay", value: function () { var e = Math.pow(2, this.numAttempts) * this.defaultRetry; return e <= 3e4 ? e : 3e4 } }]) && _(t.prototype, n), e }(); o.d(n, "a", (function () { return N })); var R = function () { var e = A.getLogger({}), t = h.isNetworkOnline(), n = { primary: null, secondary: null }, o = { reconnectWebSocket: !0, websocketInitFailed: !1, exponentialBackOffTime: 1e3, exponentialTimeoutHandle: null, lifeTimeTimeoutHandle: null, webSocketInitCheckerTimeoutId: null, connState: null }, r = { connectWebSocketRetryCount: 0, connectionAttemptStartTime: null, noOpenConnectionsTimestamp: null }, i = { pendingResponse: !1, intervalHandle: null }, u = { initFailure: new Set, getWebSocketTransport: null, subscriptionUpdate: new Set, subscriptionFailure: new Set, topic: new Map, allMessage: new Set, connectionGain: new Set, connectionLost: new Set, connectionOpen: new Set, connectionClose: new Set }, l = { connConfig: null, promiseHandle: null, promiseCompleted: !0 }, p = { subscribed: new Set, pending: new Set, subscriptionHistory: new Set }, d = { responseCheckIntervalId: null, requestCompleted: !0, reSubscribeIntervalId: null, consecutiveFailedSubscribeAttempts: 0, consecutiveNoResponseRequest: 0 }, f = new w((function () { B() })), g = new Set([s, "aws/unsubscribe", c]), m = setInterval((function () { if (t !== h.isNetworkOnline()) { if (!(t = h.isNetworkOnline())) return void W(e.info("Network offline")); var n = T(); t && (!n || S(n, WebSocket.CLOSING) || S(n, WebSocket.CLOSED)) && (W(e.info("Network online, connecting to WebSocket server")), B()) } }), 250), v = function (t, n) { t.forEach((function (t) { try { t(n) } catch (t) { W(e.error("Error executing callback", t)) } })) }, y = function (e) { if (null === e) return "NULL"; switch (e.readyState) { case WebSocket.CONNECTING: return "CONNECTING"; case WebSocket.OPEN: return "OPEN"; case WebSocket.CLOSING: return "CLOSING"; case WebSocket.CLOSED: return "CLOSED"; default: return "UNDEFINED" } }, E = function () { var t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ""; W(e.debug("[" + t + "] Primary WebSocket: " + y(n.primary) + " | Secondary WebSocket: " + y(n.secondary))) }, S = function (e, t) { return e && e.readyState === t }, b = function (e) { return S(e, WebSocket.OPEN) }, C = function (e) { return null === e || void 0 === e.readyState || S(e, WebSocket.CLOSED) }, T = function () { return null !== n.secondary ? n.secondary : n.primary }, I = function () { return b(T()) }, _ = function () { if (i.pendingResponse) return W(e.warn("Heartbeat response not received")), clearInterval(i.intervalHandle), i.pendingResponse = !1, void B(); I() ? (W(e.debug("Sending heartbeat")), T().send(F(c)), i.pendingResponse = !0) : (W(e.warn("Failed to send heartbeat since WebSocket is not open")), E("sendHeartBeat"), B()) }, R = function () { o.exponentialBackOffTime = 1e3, i.pendingResponse = !1, o.reconnectWebSocket = !0, clearTimeout(o.lifeTimeTimeoutHandle), clearInterval(i.intervalHandle), clearTimeout(o.exponentialTimeoutHandle), clearTimeout(o.webSocketInitCheckerTimeoutId) }, N = function () { d.consecutiveFailedSubscribeAttempts = 0, d.consecutiveNoResponseRequest = 0, clearInterval(d.responseCheckIntervalId), clearInterval(d.reSubscribeIntervalId) }, k = function () { r.connectWebSocketRetryCount = 0, r.connectionAttemptStartTime = null, r.noOpenConnectionsTimestamp = null }, O = function () { try { W(e.info("WebSocket connection established!")), E("webSocketOnOpen"), null !== o.connState && o.connState !== a || v(u.connectionGain), o.connState = "connected"; var t = Date.now(); v(u.connectionOpen, { connectWebSocketRetryCount: r.connectWebSocketRetryCount, connectionAttemptStartTime: r.connectionAttemptStartTime, noOpenConnectionsTimestamp: r.noOpenConnectionsTimestamp, connectionEstablishedTime: t, timeToConnect: t - r.connectionAttemptStartTime, timeWithoutConnection: r.noOpenConnectionsTimestamp ? t - r.noOpenConnectionsTimestamp : null }), k(), R(), T().openTimestamp = Date.now(), 0 === p.subscribed.size && b(n.secondary) && x(n.primary, "[Primary WebSocket] Closing WebSocket"), (p.subscribed.size > 0 || p.pending.size > 0) && (b(n.secondary) && W(e.info("Subscribing secondary websocket to topics of primary websocket")), p.subscribed.forEach((function (e) { p.subscriptionHistory.add(e), p.pending.add(e) })), p.subscribed.clear(), P()), _(), i.intervalHandle = setInterval(_, 1e4); var s = 1e3 * l.connConfig.webSocketTransport.transportLifeTimeInSeconds; W(e.debug("Scheduling WebSocket manager reconnection, after delay " + s + " ms")), o.lifeTimeTimeoutHandle = setTimeout((function () { W(e.debug("Starting scheduled WebSocket manager reconnection")), B() }), s) } catch (t) { W(e.error("Error after establishing WebSocket connection", t)) } }, L = function (t) { E("webSocketOnError"), W(e.error("WebSocketManager Error, error_event: ", JSON.stringify(t))), B() }, D = function (t) { var o = JSON.parse(t.data); switch (o.topic) { case s: if (W(e.debug("Subscription Message received from webSocket server", t.data)), d.requestCompleted = !0, d.consecutiveNoResponseRequest = 0, "success" === o.content.status) d.consecutiveFailedSubscribeAttempts = 0, o.content.topics.forEach((function (e) { p.subscriptionHistory.delete(e), p.pending.delete(e), p.subscribed.add(e) })), 0 === p.subscriptionHistory.size ? b(n.secondary) && (W(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")), x(n.primary, "[Primary WebSocket] Closing WebSocket")) : P(), v(u.subscriptionUpdate, o); else { if (clearInterval(d.reSubscribeIntervalId), ++d.consecutiveFailedSubscribeAttempts, 5 === d.consecutiveFailedSubscribeAttempts) return v(u.subscriptionFailure, o), void (d.consecutiveFailedSubscribeAttempts = 0); d.reSubscribeIntervalId = setInterval((function () { P() }), 500) } break; case c: W(e.debug("Heartbeat response received")), i.pendingResponse = !1; break; default: if (o.topic) { if (W(e.debug("Message received for topic " + o.topic)), b(n.primary) && b(n.secondary) && 0 === p.subscriptionHistory.size && this === n.primary) return void W(e.warn("Ignoring Message for Topic " + o.topic + ", to avoid duplicates")); if (0 === u.allMessage.size && 0 === u.topic.size) return void W(e.warn("No registered callback listener for Topic", o.topic)); v(u.allMessage, o), u.topic.has(o.topic) && v(u.topic.get(o.topic), o) } else o.message ? W(e.warn("WebSocketManager Message Error", o)) : W(e.warn("Invalid incoming message", o)) } }, P = function t() { if (d.consecutiveNoResponseRequest > 3) return W(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")), void v(u.subscriptionFailure, h.getSubscriptionResponse(s, !1, Array.from(p.pending))); I() ? (clearInterval(d.responseCheckIntervalId), T().send(F(s, { topics: Array.from(p.pending) })), d.requestCompleted = !1, d.responseCheckIntervalId = setInterval((function () { d.requestCompleted || (++d.consecutiveNoResponseRequest, t()) }), 1e3)) : W(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open")) }, x = function (t, n) { S(t, WebSocket.CONNECTING) || S(t, WebSocket.OPEN) ? t.close(1e3, n) : W(e.warn("Ignoring WebSocket Close request, WebSocket State: " + y(t))) }, M = function (e) { x(n.primary, "[Primary] WebSocket " + e), x(n.secondary, "[Secondary] WebSocket " + e) }, U = function () { r.connectWebSocketRetryCount++; var t = h.addJitter(o.exponentialBackOffTime, .3); Date.now() + t <= l.connConfig.urlConnValidTime ? (W(e.debug("Scheduling WebSocket reinitialization, after delay " + t + " ms")), o.exponentialTimeoutHandle = setTimeout((function () { return V() }), t), o.exponentialBackOffTime *= 2) : (W(e.warn("WebSocket URL cannot be used to establish connection")), B()) }, q = function (t) { R(), N(), W(e.error("WebSocket Initialization failed")), o.websocketInitFailed = !0, M("Terminating WebSocket Manager"), clearInterval(m), v(u.initFailure, { connectWebSocketRetryCount: r.connectWebSocketRetryCount, connectionAttemptStartTime: r.connectionAttemptStartTime, reason: t }), k() }, F = function (e, t) { return JSON.stringify({ topic: e, content: t }) }, j = function (t) { return !!(h.isObject(t) && h.isObject(t.webSocketTransport) && h.isNonEmptyString(t.webSocketTransport.url) && h.validWSUrl(t.webSocketTransport.url) && 1e3 * t.webSocketTransport.transportLifeTimeInSeconds >= 3e5) || (W(e.error("Invalid WebSocket Connection Configuration", t)), !1) }, B = function () { if (h.isNetworkOnline()) if (o.websocketInitFailed) W(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request")); else { if (l.promiseCompleted) return R(), W(e.info("Fetching new WebSocket connection configuration")), r.connectionAttemptStartTime = r.connectionAttemptStartTime || Date.now(), l.promiseCompleted = !1, l.promiseHandle = u.getWebSocketTransport(), l.promiseHandle.then((function (t) { return l.promiseCompleted = !0, W(e.debug("Successfully fetched webSocket connection configuration", t)), j(t) ? (l.connConfig = t, l.connConfig.urlConnValidTime = Date.now() + 85e3, f.connected(), V()) : (q("Invalid WebSocket connection configuration: " + t), { webSocketConnectionFailed: !0 }) }), (function (t) { return l.promiseCompleted = !0, W(e.error("Failed to fetch webSocket connection configuration", t)), h.isNetworkFailure(t) ? (W(e.info("Retrying fetching new WebSocket connection configuration")), f.retry()) : q("Failed to fetch webSocket connection configuration: " + JSON.stringify(t)), { webSocketConnectionFailed: !0 } })); W(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")) } else W(e.info("Network offline, ignoring this getWebSocketConnConfig request")) }, V = function () { if (o.websocketInitFailed) return W(e.info("web-socket initializing had failed, aborting re-init")), { webSocketConnectionFailed: !0 }; if (!h.isNetworkOnline()) return W(e.warn("System is offline aborting web-socket init")), { webSocketConnectionFailed: !0 }; W(e.info("Initializing Websocket Manager")), E("initWebSocket"); try { if (j(l.connConfig)) { var t = null; return b(n.primary) ? (W(e.debug("Primary Socket connection is already open")), S(n.secondary, WebSocket.CONNECTING) || (W(e.debug("Establishing a secondary web-socket connection")), n.secondary = H()), t = n.secondary) : (S(n.primary, WebSocket.CONNECTING) || (W(e.debug("Establishing a primary web-socket connection")), n.primary = H()), t = n.primary), o.webSocketInitCheckerTimeoutId = setTimeout((function () { b(t) || U() }), 1e3), { webSocketConnectionFailed: !1 } } } catch (t) { return W(e.error("Error Initializing web-socket-manager", t)), q("Failed to initialize new WebSocket: " + t.message), { webSocketConnectionFailed: !0 } } }, H = function () { var t = new WebSocket(l.connConfig.webSocketTransport.url); return t.addEventListener("open", O), t.addEventListener("message", D), t.addEventListener("error", L), t.addEventListener("close", (function (i) { return function (t, i) { W(e.info("Socket connection is closed", t)), E("webSocketOnClose before-cleanup"), v(u.connectionClose, { openTimestamp: i.openTimestamp, closeTimestamp: Date.now(), connectionDuration: Date.now() - i.openTimestamp, code: t.code, reason: t.reason }), C(n.primary) && (n.primary = null), C(n.secondary) && (n.secondary = null), o.reconnectWebSocket && (b(n.primary) || b(n.secondary) ? C(n.primary) && b(n.secondary) && (W(e.info("[Primary] WebSocket Cleanly Closed")), n.primary = n.secondary, n.secondary = null) : (W(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")), o.connState === a ? W(e.info("Ignoring connectionLost callback invocation")) : (v(u.connectionLost, { openTimestamp: i.openTimestamp, closeTimestamp: Date.now(), connectionDuration: Date.now() - i.openTimestamp, code: t.code, reason: t.reason }), r.noOpenConnectionsTimestamp = Date.now()), o.connState = a, B()), E("webSocketOnClose after-cleanup")) }(i, t) })), t }, W = function (e) { return e && "function" == typeof e.sendInternalLogToServer && e.sendInternalLogToServer(), e }; this.init = function (t) { if (h.assertTrue(h.isFunction(t), "transportHandle must be a function"), null === u.getWebSocketTransport) return u.getWebSocketTransport = t, B(); W(e.warn("Web Socket Manager was already initialized")) }, this.onInitFailure = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.initFailure.add(e), o.websocketInitFailed && e(), function () { return u.initFailure.delete(e) } }, this.onConnectionOpen = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.connectionOpen.add(e), function () { return u.connectionOpen.delete(e) } }, this.onConnectionClose = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.connectionClose.add(e), function () { return u.connectionClose.delete(e) } }, this.onConnectionGain = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.connectionGain.add(e), I() && e(), function () { return u.connectionGain.delete(e) } }, this.onConnectionLost = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.connectionLost.add(e), o.connState === a && e(), function () { return u.connectionLost.delete(e) } }, this.onSubscriptionUpdate = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.subscriptionUpdate.add(e), function () { return u.subscriptionUpdate.delete(e) } }, this.onSubscriptionFailure = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.subscriptionFailure.add(e), function () { return u.subscriptionFailure.delete(e) } }, this.onMessage = function (e, t) { return h.assertNotNull(e, "topicName"), h.assertTrue(h.isFunction(t), "cb must be a function"), u.topic.has(e) ? u.topic.get(e).add(t) : u.topic.set(e, new Set([t])), function () { return u.topic.get(e).delete(t) } }, this.onAllMessage = function (e) { return h.assertTrue(h.isFunction(e), "cb must be a function"), u.allMessage.add(e), function () { return u.allMessage.delete(e) } }, this.subscribeTopics = function (e) { h.assertNotNull(e, "topics"), h.assertIsList(e), e.forEach((function (e) { p.subscribed.has(e) || p.pending.add(e) })), d.consecutiveNoResponseRequest = 0, P() }, this.sendMessage = function (t) { if (h.assertIsObject(t, "payload"), void 0 === t.topic || g.has(t.topic)) W(e.warn("Cannot send message, Invalid topic", t)); else { try { t = JSON.stringify(t) } catch (n) { return void W(e.warn("Error stringify message", t)) } I() ? T().send(t) : W(e.warn("Cannot send message, web socket connection is not open")) } }, this.closeWebSocket = function () { R(), N(), o.reconnectWebSocket = !1, clearInterval(m), M("User request to close WebSocket") }, this.terminateWebSocketManager = q }, N = { create: function () { return new R }, setGlobalConfig: function (e) { var t = e.loggerConfig; A.updateLoggerConfig(t) }, LogLevel: S, Logger: E } }, function (t, n, o) { var r; !function () { "use strict"; var i = { not_string: /[^s]/, not_bool: /[^t]/, not_type: /[^T]/, not_primitive: /[^v]/, number: /[diefg]/, numeric_arg: /[bcdiefguxX]/, json: /[j]/, not_json: /[^j]/, text: /^[^\x25]+/, modulo: /^\x25{2}/, placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, key: /^([a-z_][a-z_\d]*)/i, key_access: /^\.([a-z_][a-z_\d]*)/i, index_access: /^\[(\d+)\]/, sign: /^[+-]/ }; function s(t) { return function (t, n) { var o, r, c, a, u, l, p, h, d, f = 1, g = t.length, m = ""; for (r = 0; r < g; r++)if ("string" == typeof t[r]) m += t[r]; else if ("object" == e(t[r])) { if ((a = t[r]).keys) for (o = n[f], c = 0; c < a.keys.length; c++) { if (null == o) throw new Error(s('[sprintf] Cannot access property "%s" of undefined value "%s"', a.keys[c], a.keys[c - 1])); o = o[a.keys[c]] } else o = a.param_no ? n[a.param_no] : n[f++]; if (i.not_type.test(a.type) && i.not_primitive.test(a.type) && o instanceof Function && (o = o()), i.numeric_arg.test(a.type) && "number" != typeof o && isNaN(o)) throw new TypeError(s("[sprintf] expecting number but found %T", o)); switch (i.number.test(a.type) && (h = o >= 0), a.type) { case "b": o = parseInt(o, 10).toString(2); break; case "c": o = String.fromCharCode(parseInt(o, 10)); break; case "d": case "i": o = parseInt(o, 10); break; case "j": o = JSON.stringify(o, null, a.width ? parseInt(a.width) : 0); break; case "e": o = a.precision ? parseFloat(o).toExponential(a.precision) : parseFloat(o).toExponential(); break; case "f": o = a.precision ? parseFloat(o).toFixed(a.precision) : parseFloat(o); break; case "g": o = a.precision ? String(Number(o.toPrecision(a.precision))) : parseFloat(o); break; case "o": o = (parseInt(o, 10) >>> 0).toString(8); break; case "s": o = String(o), o = a.precision ? o.substring(0, a.precision) : o; break; case "t": o = String(!!o), o = a.precision ? o.substring(0, a.precision) : o; break; case "T": o = Object.prototype.toString.call(o).slice(8, -1).toLowerCase(), o = a.precision ? o.substring(0, a.precision) : o; break; case "u": o = parseInt(o, 10) >>> 0; break; case "v": o = o.valueOf(), o = a.precision ? o.substring(0, a.precision) : o; break; case "x": o = (parseInt(o, 10) >>> 0).toString(16); break; case "X": o = (parseInt(o, 10) >>> 0).toString(16).toUpperCase() }i.json.test(a.type) ? m += o : (!i.number.test(a.type) || h && !a.sign ? d = "" : (d = h ? "+" : "-", o = o.toString().replace(i.sign, "")), l = a.pad_char ? "0" === a.pad_char ? "0" : a.pad_char.charAt(1) : " ", p = a.width - (d + o).length, u = a.width && p > 0 ? l.repeat(p) : "", m += a.align ? d + o + u : "0" === l ? d + u + o : u + d + o) } return m }(function (e) { if (a[e]) return a[e]; for (var t, n = e, o = [], r = 0; n;) { if (null !== (t = i.text.exec(n))) o.push(t[0]); else if (null !== (t = i.modulo.exec(n))) o.push("%"); else { if (null === (t = i.placeholder.exec(n))) throw new SyntaxError("[sprintf] unexpected placeholder"); if (t[2]) { r |= 1; var s = [], c = t[2], u = []; if (null === (u = i.key.exec(c))) throw new SyntaxError("[sprintf] failed to parse named argument key"); for (s.push(u[1]); "" !== (c = c.substring(u[0].length));)if (null !== (u = i.key_access.exec(c))) s.push(u[1]); else { if (null === (u = i.index_access.exec(c))) throw new SyntaxError("[sprintf] failed to parse named argument key"); s.push(u[1]) } t[2] = s } else r |= 2; if (3 === r) throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported"); o.push({ placeholder: t[0], param_no: t[1], keys: t[2], sign: t[3], pad_char: t[4], align: t[5], width: t[6], precision: t[7], type: t[8] }) } n = n.substring(t[0].length) } return a[e] = o }(t), arguments) } function c(e, t) { return s.apply(null, [e].concat(t || [])) } var a = Object.create(null); n.sprintf = s, n.vsprintf = c, "undefined" != typeof window && (window.sprintf = s, window.vsprintf = c, void 0 === (r = function () { return { sprintf: s, vsprintf: c } }.call(n, o, n, t)) || (t.exports = r)) }() }, function (e, t, n) { "use strict"; n.r(t), function (e) { n.d(t, "WebSocketManager", (function () { return r })); var o = n(0); e.connect = e.connect || {}, connect.WebSocketManager = o.a; var r = o.a }.call(this, n(3)) }, function (t, n) { var o; o = function () { return this }(); try { o = o || new Function("return this")() } catch (t) { "object" == ("undefined" == typeof window ? "undefined" : e(window)) && (o = window) } t.exports = o }]) }, 312: () => { function e(t) { return e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, e(t) } !function () { var t = this; connect = t.connect || {}, t.connect = connect, t.lily = connect; var n = { TEST: "TEST", TRACE: "TRACE", DEBUG: "DEBUG", INFO: "INFO", LOG: "LOG", WARN: "WARN", ERROR: "ERROR", CRITICAL: "CRITICAL" }, o = { CCP: "ccp", SOFTPHONE: "softphone", CHAT: "chat", TASK: "task" }, r = { TEST: 0, TRACE: 10, DEBUG: 20, INFO: 30, LOG: 40, WARN: 50, ERROR: 100, CRITICAL: 200 }, i = { TRACE: function (e) { console.info(e) }, DEBUG: function (e) { console.info(e) }, INFO: function (e) { console.info(e) }, LOG: function (e) { console.log(e) }, TEST: function (e) { console.log(e) }, WARN: function (e) { console.warn(e) }, ERROR: function (e) { console.error(e) }, CRITICAL: function (e) { console.error(e) } }, s = function (e) { var t, n, r = Array.prototype.slice.call(e, 0), i = r.shift(); return function (e) { return -1 !== Object.values(o).indexOf(e) }(i) ? (n = i, t = r.shift()) : (t = i, n = o.CCP), { format: t, component: n, args: r } }, c = function (e, t, n, o) { this.component = e, this.level = t, this.text = n, this.time = new Date, this.exception = null, this.objects = [], this.line = 0, this.agentResourceId = null; try { connect.agent.initialized && (this.agentResourceId = (new connect.Agent)._getResourceId()) } catch (e) { console.log("Issue finding agentResourceId: ", e) } this.loggerId = o }; c.fromObject = function (e) { var t = new c(o.CCP, e.level, e.text, e.loggerId); return "[object Date]" === Object.prototype.toString.call(e.time) ? t.time = new Date(e.time.getTime()) : "number" == typeof e.time ? t.time = new Date(e.time) : "string" == typeof e.time ? t.time = Date.parse(e.time) : t.time = new Date, t.exception = e.exception, t.objects = e.objects, t }; var a = function t(n) { var o = /AuthToken.*\=/g; n && "object" === e(n) && Object.keys(n).forEach((function (r) { "object" === e(n[r]) ? t(n[r]) : "string" == typeof n[r] && ("url" === r || "text" === r ? n[r] = n[r].replace(o, "[redacted]") : "quickConnectName" === r && (n[r] = "[redacted]")) })) }, u = function (e) { this.type = e instanceof Error ? e.name : e.code || Object.prototype.toString.call(e), this.message = e.message, this.stack = e.stack ? e.stack.split("\n") : [] }; c.prototype.toString = function () { return connect.sprintf("[%s] [%s] [%s]: %s", this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", this.getLevel(), this.getAgentResourceId(), this.getText()) }, c.prototype.getTime = function () { return this.time }, c.prototype.getAgentResourceId = function () { return this.agentResourceId }, c.prototype.getLevel = function () { return this.level }, c.prototype.getText = function () { return this.text }, c.prototype.getComponent = function () { return this.component }, c.prototype.withException = function (e) { return this.exception = new u(e), this }, c.prototype.withObject = function (e) { var t = connect.deepcopy(e); return a(t), this.objects.push(t), this }, c.prototype.withCrossOriginEventObject = function (e) { var t = connect.deepcopyCrossOriginEvent(e); return a(t), this.objects.push(t), this }, c.prototype.sendInternalLogToServer = function () { return connect.getLog()._serverBoundInternalLogs.push(this), this }; var l = function () { this._logs = [], this._rolledLogs = [], this._logsToPush = [], this._serverBoundInternalLogs = [], this._echoLevel = r.INFO, this._logLevel = r.INFO, this._lineCount = 0, this._logRollInterval = 0, this._logRollTimer = null, this._loggerId = (new Date).getTime() + "-" + Math.random().toString(36).slice(2), this.setLogRollInterval(18e5), this._startLogIndexToPush = 0 }; l.prototype.setLogRollInterval = function (e) { var n = this; this._logRollTimer && e === this._logRollInterval ? this.warn("Logger is already set to the given interval: %d", this._logRollInterval) : (this._logRollTimer && t.clearInterval(this._logRollTimer), this._logRollInterval = e, this._logRollTimer = t.setInterval((function () { this._rolledLogs = this._logs, this._logs = [], this._startLogIndexToPush = 0, n.info("Log roll interval occurred.") }), this._logRollInterval)) }, l.prototype.setLogLevel = function (e) { if (!(e in r)) throw new Error("Unknown logging level: " + e); this._logLevel = r[e] }, l.prototype.setEchoLevel = function (e) { if (!(e in r)) throw new Error("Unknown logging level: " + e); this._echoLevel = r[e] }, l.prototype.write = function (e, t, n) { var o = new c(e, t, n, this.getLoggerId()); return a(o), this.addLogEntry(o), o }, l.prototype.addLogEntry = function (e) { a(e), this._logs.push(e), o.SOFTPHONE === e.component && this._logsToPush.push(e), e.level in r && r[e.level] >= this._logLevel && (r[e.level] >= this._echoLevel && i[e.getLevel()](e.toString()), e.line = this._lineCount++) }, l.prototype.sendInternalLogEntryToServer = function (e) { this._serverBoundInternalLogs.push(e), e.level in r && r[e.level] >= this._logLevel && (r[e.level] >= this._echoLevel && i[e.getLevel()](e.toString()), e.line = this._lineCount++) }, l.prototype.clearObjects = function () { for (var e = 0; e < this._logs.length; e++)this._logs[e].objects && delete this._logs[e].objects }, l.prototype.clearExceptions = function () { for (var e = 0; e < this._logs.length; e++)this._logs[e].exception && delete this._logs[e].exception }, l.prototype.trace = function () { var e = s(arguments); return this.write(e.component, n.TRACE, connect.vsprintf(e.format, e.args)) }, l.prototype.debug = function () { var e = s(arguments); return this.write(e.component, n.DEBUG, connect.vsprintf(e.format, e.args)) }, l.prototype.info = function () { var e = s(arguments); return this.write(e.component, n.INFO, connect.vsprintf(e.format, e.args)) }, l.prototype.log = function () { var e = s(arguments); return this.write(e.component, n.LOG, connect.vsprintf(e.format, e.args)) }, l.prototype.test = function () { var e = s(arguments); return this.write(e.component, n.TEST, connect.vsprintf(e.format, e.args)) }, l.prototype.warn = function () { var e = s(arguments); return this.write(e.component, n.WARN, connect.vsprintf(e.format, e.args)) }, l.prototype.error = function () { var e = s(arguments); return this.write(e.component, n.ERROR, connect.vsprintf(e.format, e.args)) }, l.prototype.critical = function () { var e = s(arguments); return this.write(e.component, n.ERROR, connect.vsprintf(e.format, e.args)) }, l.prototype.toString = function () { for (var e = [], t = 0; t < this._logs.length; t++)e.push(this._logs[t].toString()); return e.join("\n") }, l.prototype.download = function (n) { var o = "agent-log", i = !1; "object" === e(n) ? (o = n.logName || o, i = n.filterByLogLevel || i) : "string" == typeof n && (o = n || o); var s = this, c = this._rolledLogs.concat(this._logs); i && (c = c.filter((function (e) { return r[e.level] >= s._logLevel }))); var a = new t.Blob([JSON.stringify(c, void 0, 4)], ["text/plain"]), u = document.createElement("a"); o = o || "agent-log", u.href = t.URL.createObjectURL(a), u.download = o + ".txt", document.body.appendChild(u), u.click(), document.body.removeChild(u) }, l.prototype.scheduleUpstreamLogPush = function (e) { connect.upstreamLogPushScheduled || (connect.upstreamLogPushScheduled = !0, t.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, e), 5e3)) }, l.prototype.reportMasterLogsUpStream = function (e) { var t = this._logsToPush.slice(); this._logsToPush = [], connect.ifMaster(connect.MasterTopics.SEND_LOGS, (function () { t.length > 0 && e.sendUpstream(connect.EventType.SEND_LOGS, t) })) }, l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function (e) { t.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, e), 1e3) }, l.prototype.scheduleUpstreamOuterContextCCPLogsPush = function (e) { t.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, e), 1e3) }, l.prototype.pushOuterContextCCPserverBoundLogsUpstream = function (e) { if (this._serverBoundInternalLogs.length > 0) { for (var t = 0; t < this._serverBoundInternalLogs.length; t++)this._serverBoundInternalLogs[t].text = this._serverBoundInternalLogs[t].text; e.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs), this._serverBoundInternalLogs = [] } }, l.prototype.pushOuterContextCCPLogsUpstream = function (e) { for (var t = this._startLogIndexToPush; t < this._logs.length; t++)this._logs[t].loggerId === this._loggerId && e.sendUpstream(connect.EventType.LOG, this._logs[t]); this._startLogIndexToPush = this._logs.length }, l.prototype.getLoggerId = function () { return this._loggerId }, l.prototype.scheduleDownstreamClientSideLogsPush = function () { t.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), 5e3) }, l.prototype.pushClientSideLogsDownstream = function () { var e = []; this._serverBoundInternalLogs.length < 50 || (this._serverBoundInternalLogs.length > 500 ? e = this._serverBoundInternalLogs.splice(0, 500) : (e = this._serverBoundInternalLogs, this._serverBoundInternalLogs = []), connect.publishClientSideLogs(e)) }; var p = function e(n) { l.call(this), this.conduit = n, t.setInterval(connect.hitch(this, this._pushLogsDownstream), e.LOG_PUSH_INTERVAL), t.clearInterval(this._logRollTimer), this._logRollTimer = null }; p.LOG_PUSH_INTERVAL = 1e3, (p.prototype = Object.create(l.prototype)).constructor = p, p.prototype.pushLogsDownstream = function (e) { var t = this; e.forEach((function (e) { t.conduit.sendDownstream(connect.EventType.LOG, e) })) }, p.prototype._pushLogsDownstream = function () { var e = this; this._logs.forEach((function (t) { e.conduit.sendDownstream(connect.EventType.LOG, t) })), this._logs = []; for (var t = 0; t < this._serverBoundInternalLogs.length; t++)this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[t]); this._serverBoundInternalLogs = [] }; var h = function (e) { return function () { try { return e.apply(this, arguments) } catch (e) { i.ERROR(e) } } }; connect.rootLogger = new l, function (e) { for (var t in e) "function" == typeof e[t] && (e[t] = h(e[t])) }(connect.rootLogger), connect = connect || {}, connect.getLog = function () { return connect.rootLogger }, connect.LogEntry = c, connect.Logger = l, connect.LogLevel = n, connect.LogComponent = o, connect.DownstreamConduitLogger = p }() }, 158: () => { !function () { connect = this.connect || {}, this.connect = connect, connect.ChatMediaController = function (e, t) { var n = connect.getLog(), o = connect.LogComponent.CHAT, r = function (t, n) { connect.publishMetric({ name: t, contactId: e.contactId, data: n || e }) }, i = function (e) { e.onConnectionBroken((function (e) { n.error(o, "Chat Session connection broken").withException(e).sendInternalLogToServer(), r("Chat Session connection broken", e) })), e.onConnectionEstablished((function (e) { n.info(o, "Chat Session connection established").withObject(e).sendInternalLogToServer(), r("Chat Session connection established", e) })) }; return { get: function () { return function () { r("Chat media controller init", e.contactId), n.info(o, "Chat media controller init").withObject(e).sendInternalLogToServer(), connect.ChatSession.setGlobalConfig({ loggerConfig: { logger: n }, region: t.region }); var s = connect.ChatSession.create({ chatDetails: e, type: "AGENT", websocketManager: connect.core.getWebSocketManager() }); return i(s), s.connect().then((function (t) { return n.info(o, "Chat Session Successfully established for contactId %s", e.contactId).sendInternalLogToServer(), r("Chat Session Successfully established", e.contactId), s })).catch((function (t) { throw n.error(o, "Chat Session establishement failed for contact %s", e.contactId).withException(t).sendInternalLogToServer(), r("Chat Session establishement failed", e.contactId, t), t })) }() } } } }() }, 7: () => { !function () { connect = this.connect || {}, this.connect = connect, connect.MediaFactory = function (e) { var t = {}, n = new Set, o = connect.getLog(), r = connect.LogComponent.CHAT, i = connect.merge({}, e) || {}; i.region = i.region || "us-west-2"; var s = function (e) { t[e] && !n.has(e) && (o.info(r, "Destroying mediaController for %s", e), n.add(e), t[e].then((function () { "function" == typeof controller.cleanUp && controller.cleanUp(), delete t[e], n.delete(e) })).catch((function () { delete t[e], n.delete(e) }))) }; return { get: function (e) { return function (e) { return e.isActive() }(e) ? function (e) { var n = e.getConnectionId(); if (!e.getMediaInfo()) return o.error(r, "Media info does not exist for a media type %s", e.getMediaType()).withObject(e).sendInternalLogToServer(), Promise.reject("Media info does not exist for this connection"); if (t[n]) return t[n]; switch (o.info(r, "media controller of type %s init", e.getMediaType()).withObject(e).sendInternalLogToServer(), e.getMediaType()) { case connect.MediaType.CHAT: return t[n] = new connect.ChatMediaController(e.getMediaInfo(), i).get(); case connect.MediaType.SOFTPHONE: return t[n] = new connect.SoftphoneMediaController(e.getMediaInfo()).get(); case connect.MediaType.TASK: return t[n] = new connect.TaskMediaController(e.getMediaInfo()).get(); default: return o.error(r, "Unrecognized media type %s ", e.getMediaType()).sendInternalLogToServer(), Promise.reject() } }(e) : (s(e.getConnectionId()), Promise.reject("Media Controller is no longer available for this connection")) }, destroy: s } } }() }, 6: () => { !function () { connect = this.connect || {}, this.connect = connect, connect.SoftphoneMediaController = function (e) { return { get: function () { return Promise.resolve(e) } } } }() }, 487: () => { !function () { connect = this.connect || {}, this.connect = connect, connect.TaskMediaController = function (e) { var t = connect.getLog(), n = connect.LogComponent.TASK, o = function (t, n) { connect.publishMetric({ name: t, contactId: e.contactId, data: n || e }) }, r = function (e) { e.onConnectionBroken((function (e) { t.error(n, "Task Session connection broken").withException(e), o("Task Session connection broken", e) })), e.onConnectionEstablished((function (e) { t.info(n, "Task Session connection established").withObject(e), o("Task Session connection established", e) })) }; return { get: function () { return function () { o("Task media controller init", e.contactId), t.info(n, "Task media controller init").withObject(e); var i = connect.TaskSession.create({ contactId: e.contactId, initialContactId: e.initialContactId, websocketManager: connect.core.getWebSocketManager() }); return r(i), i.connect().then((function () { return t.info(n, "Task Session Successfully established for contactId %s", e.contactId), o("Task Session Successfully established", e.contactId), i })).catch((function (r) { throw t.error(n, "Task Session establishement failed for contact %s", e.contactId).withException(r), o("Chat Session establishement failed", e.contactId, r), r })) }() } } } }() }, 743: () => { function e(t) { return e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, e(t) } function t(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); t && (o = o.filter((function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable }))), n.push.apply(n, o) } return n } function n(e) { for (var n = 1; n < arguments.length; n++) { var r = null != arguments[n] ? arguments[n] : {}; n % 2 ? t(Object(r), !0).forEach((function (t) { o(e, t, r[t]) })) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(r)) : t(Object(r)).forEach((function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(r, t)) })) } return e } function o(t, n, o) { return (n = function (t) { var n = function (t, n) { if ("object" !== e(t) || null === t) return t; var o = t[Symbol.toPrimitive]; if (void 0 !== o) { var r = o.call(t, n || "default"); if ("object" !== e(r)) return r; throw new TypeError("@@toPrimitive must return a primitive value.") } return ("string" === n ? String : Number)(t) }(t, "string"); return "symbol" === e(n) ? n : String(n) }(n)) in t ? Object.defineProperty(t, n, { value: o, enumerable: !0, configurable: !0, writable: !0 }) : t[n] = o, t } !function () { var e = this || globalThis, t = e.connect || {}; e.connect = t, e.lily = t; var o, r = "/request-storage-access", i = { canRequest: !0, mode: "default", custom: {} }, s = {}, c = "", a = null, u = !1, l = { INIT: "storageAccess::init", GRANTED: "storageAccess::granted", DENIED: "storageAccess::denied", REQUEST: "storageAccess::request" }, p = function () { return { show: function () { a.style.display = "block" }, hide: function () { a.style.display = "none" } } }, h = function () { return s && "default" !== s.mode }, d = function (e) { return e.match(/.connect.aws.a2z.com|.my.connect.aws|.awsapps.com/) }, f = function (e) { var t = new URL(e), n = t.origin, o = t.pathname; if (n.match(/.awsapps.com/)) { var i = "connect"; return o.startsWith("/connect-gamma") && (i = "connect-gamma"), "".concat(n, "/").concat(i).concat(r) } return "".concat(n).concat(r) }, g = function (e) { return e.match(/^https?:\/\/localhost/) }, m = function () { if (!c) throw new Error("[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first"); return d(c) || g(c) ? new URL(c).pathname : "/connect/ccp-v2" }, v = function (e) { var n = e.onInit, o = e.onDeny, r = e.onGrant; function i(e) { var s = e.data, c = e.source; if (t.core._getCCPIframe().contentWindow !== c) return !1; switch (t.core.initialized && window.removeEventListener("message", i), s.event) { case l.INIT: t.getLog().info("[StorageAccess][INIT] message recieved").withObject(s), n && n(s); break; case l.GRANTED: t.getLog().info("[StorageAccess][GRANTED] message recieved").withObject(s), r && r(s); break; case l.DENIED: t.getLog().info("[StorageAccess][DENIED] message recieved").withObject(s), o && o(s); break; default: t.core.initialized && window.removeEventListener("message", i) } } return s.canRequest && window.addEventListener("message", i), { unsubscribe: function () { window.removeEventListener("message", i) } } }; t.storageAccess = Object.freeze({ canRequest: function () { return s.canRequest }, optOutFromRequestAccess: function () { i.canRequest = !1 }, optInForRequestAccess: function () { i.canRequest = !0 }, init: function (e, o) { var r = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}; t.assertNotNull(e, "ccpUrl"), t.assertNotNull(o, "container"), a = o, c = e, function () { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; e.custom = e.custom || {}, (s = n(n(n({}, i), e), {}, { custom: n(n({}, i.custom), e.custom) })).canRequest = !("false" === s.canRequest || !1 === s.canRequest) }(r), t.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(e, " - ").concat(s.canRequest ? "Proceeding with requesting storage access" : "user has opted out, skipping request storage access")).withObject(s) }, setupRequestHandlers: function (e) { var n = e.onGrant; o && o.unsubscribe(), o = v({ onInit: function (e) { console.log("%c[INIT]", "background:lime; color: black; font-size:large"), t.getLog().info("[StorageAccess][onInit] callback executed").withObject(null == e ? void 0 : e.data), null != e && e.data.hasAccess || !h() || p().show() }, onDeny: function () { console.log("%c[DENIED]", "background:lime; color: black; font-size:large"), t.getLog().info("[StorageAccess][onDeny] callback executed"), h() && p().show() }, onGrant: function () { console.log("%c[Granted]", "background:lime; color: black; font-size:large"), t.getLog().info("[StorageAccess][onGrant] callback executed"), h() && p().hide(), u || (n(), u = !0) } }) }, getRequestStorageAccessUrl: function () { if (!c) throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first"); if (d(c)) return f(c); if (g(c)) return t.getLog().info("[StorageAccess] [CCP] Local testing"), "".concat(c).concat(r); if (s.instanceUrl && d(s.instanceUrl)) return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(s.instanceUrl)), f(s.instanceUrl); if (s.instanceUrl && g(s.instanceUrl)) return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"), "".concat(s.instanceUrl).concat(r); throw t.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"), new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL") }, storageAccessEvents: l, resetStorageAccessState: function () { s = {}, c = "", a = null }, getStorageAccessParams: function () { return s }, onRequest: v, request: function () { t.core._getCCPIframe().contentWindow.postMessage({ event: l.REQUEST, data: n(n({}, s), {}, { landat: m() }) }, "*") } }) }() }, 555: () => { !function () { var e = this, t = e.connect || {}; e.connect = t, e.lily = t; var n = function (n) { var o = this; if (this._prevContactId = null, t.assertNotNull(n, "ringtoneConfig"), !n.ringtoneUrl) throw new Error("ringtoneUrl is required!"); e.Audio && void 0 !== e.Promise ? this._playableAudioPromise = new Promise((function (e, t) { o._audio = new Audio(n.ringtoneUrl), o._audio.loop = !0, o._audio.addEventListener("canplay", (function () { o._audioPlayable = !0, e(o._audio) })) })) : (this._audio = null, t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()), o._driveRingtone() }; n.prototype._driveRingtone = function () { throw new Error("Not implemented.") }, n.prototype._startRingtone = function (e) { this._audio && (this._audio.play().catch((function (n) { this._publishTelemetryEvent("Ringtone Playback Failure", e), t.getLog().error("Ringtone Playback Failure").sendInternalLogToServer() })), this._publishTelemetryEvent("Ringtone Start", e), t.getLog().info("Ringtone Start").sendInternalLogToServer()) }, n.prototype._stopRingtone = function (e) { this._audio && (this._audio.pause(), this._audio.currentTime = 0, this._publishTelemetryEvent("Ringtone Stop", e), t.getLog().info("Ringtone Stop").sendInternalLogToServer()) }, n.prototype.stopRingtone = function () { this._stopRingtone() }, n.prototype._ringtoneSetup = function (e) { var n = this; t.ifMaster(t.MasterTopics.RINGTONE, (function () { n._startRingtone(e), n._prevContactId = e.getContactId(), e.onConnected(lily.hitch(n, n._stopRingtone)), e.onAccepted(lily.hitch(n, n._stopRingtone)), e.onEnded(lily.hitch(n, n._stopRingtone)), e.onRefresh((function (e) { e.getStatus().type !== t.ContactStatusType.CONNECTING && e.getStatus().type !== t.ContactStatusType.INCOMING && n._stopRingtone() })) })) }, n.prototype._publishTelemetryEvent = function (e, n) { n && n.getContactId() && t.publishMetric({ name: e, contactId: n.getContactId() }) }, n.prototype.setOutputDevice = function (t) { return this._playableAudioPromise ? Promise.race([this._playableAudioPromise, new Promise((function (t, n) { e.setTimeout((function () { n("Timed out waiting for playable audio") }), 3e3) }))]).then((function (e) { return e ? e.setSinkId ? Promise.resolve(e.setSinkId(t)) : Promise.reject("Not supported") : Promise.reject("No audio found") })) : e.Promise ? Promise.reject("Not eligible ringtone owner") : void 0 }; var o = function (e) { n.call(this, e) }; (o.prototype = Object.create(n.prototype)).constructor = o, o.prototype._driveRingtone = function () { var e = this, n = function (n) { n.getType() === lily.ContactType.VOICE && n.isSoftphoneCall() && n.isInbound() && (e._ringtoneSetup(n), e._publishTelemetryEvent("Ringtone Connecting", n), t.getLog().info("Ringtone Connecting").sendInternalLogToServer()) }; t.contact((function (e) { e.onConnecting(n) })), (new t.Agent).getContacts().forEach((function (e) { e.getStatus().type === t.ContactStatusType.CONNECTING && n(e) })) }; var r = function (e) { n.call(this, e) }; (r.prototype = Object.create(n.prototype)).constructor = r, r.prototype._driveRingtone = function () { var e = this, n = function (n) { n.getType() === lily.ContactType.CHAT && n.isInbound() && (e._ringtoneSetup(n), e._publishTelemetryEvent("Chat Ringtone Connecting", n), t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer()) }; t.contact((function (e) { e.onConnecting(n) })) }; var i = function (e) { n.call(this, e) }; (i.prototype = Object.create(n.prototype)).constructor = i, i.prototype._driveRingtone = function () { var e = this, n = function (n) { n.getType() === lily.ContactType.TASK && n.isInbound() && (e._ringtoneSetup(n), e._publishTelemetryEvent("Task Ringtone Connecting", n), t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer()) }; t.contact((function (e) { e.onConnecting(n) })) }; var s = function (e) { n.call(this, e) }; (s.prototype = Object.create(n.prototype)).constructor = s, s.prototype._driveRingtone = function () { var e = this; t.contact((function (n) { n.onIncoming((function () { n.getType() === lily.ContactType.QUEUE_CALLBACK && (e._ringtoneSetup(n), e._publishTelemetryEvent("Callback Ringtone Connecting", n), t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer()) })) })) }, t.VoiceRingtoneEngine = o, t.ChatRingtoneEngine = r, t.TaskRingtoneEngine = i, t.QueueCallbackRingtoneEngine = s }() }, 960: () => { function e(t) { return e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, e(t) } !function () { var t = this; connect = t.connect || {}, t.connect = connect, t.lily = connect, t.ccpVersion = "V2"; var n = {}; n[connect.SoftphoneCallType.AUDIO_ONLY] = "Audio", n[connect.SoftphoneCallType.VIDEO_ONLY] = "Video", n[connect.SoftphoneCallType.AUDIO_VIDEO] = "AudioVideo", n[connect.SoftphoneCallType.NONE] = "None"; var o = "audio_input", r = "audio_output"; ({})[connect.ContactType.VOICE] = "Voice"; var i = [], s = {}, c = {}, a = null, u = null, l = null, p = connect.SoftphoneErrorTypes, h = {}, d = connect.randomId(), f = function (e) { return new Promise((function (t, n) { connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, e, { success: function (e) { t(e.softphoneTransport.softphoneMediaConnections) }, failure: function (e) { e.message && e.message.includes("SoftphoneConnectionLimitBreachedException") && _("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""), n(Error("requestIceAccess failed")) }, authFailure: function () { n(Error("Authentication failed while requestIceAccess")) }, accessDenied: function () { n(Error("Access Denied while requestIceAccess")) } }) })) }, g = function (e) { var t = connect.core.getUpstream(), n = e.getAgentConnection(); if (n) { var o = n.getSoftphoneMediaInfo(); o ? !0 === o.autoAccept ? (l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(), t.sendUpstream(connect.EventType.BROADCAST, { event: connect.ContactEvents.ACCEPTED, data: new connect.Contact(e.contactId) }), t.sendUpstream(connect.EventType.BROADCAST, { event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, e.contactId), data: new connect.Contact(e.contactId) })) : l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer() : l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer() } else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer() }, m = function () { connect.core.getEventBus().subscribe(connect.EventType.MUTE, S) }, v = function () { connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, b) }, y = function () { connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, C) }, E = function (e) { delete h[e], connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.MUTE_TOGGLE, data: { muted: !1 } }) }, S = function (e) { var t; if (0 !== connect.keys(h).length) { for (var n in e && void 0 !== e.mute && (t = e.mute), h) if (h.hasOwnProperty(n)) { var o = h[n].stream; if (o) { var r = o.getAudioTracks()[0]; void 0 !== t ? (r.enabled = !t, h[n].muted = t, t ? l.info("Agent has muted the contact, connectionId - " + n).sendInternalLogToServer() : l.info("Agent has unmuted the contact, connectionId - " + n).sendInternalLogToServer()) : t = h[n].muted || !1 } } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.MUTE_TOGGLE, data: { muted: t } }) } }, b = function (e) { if (0 !== connect.keys(h).length && e && e.deviceId) { var t = e.deviceId, n = document.getElementById("remote-audio"); try { l.info("Trying to set speaker to device " + t), n && "function" == typeof n.setSinkId && n.setSinkId(t) } catch (e) { l.error("Failed to set speaker to device " + t) } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, data: { deviceId: t } }) } }, C = function (e) { if (0 !== connect.keys(h).length && e && e.deviceId) { var t = e.deviceId, n = connect.core.getSoftphoneManager(); try { navigator.mediaDevices.getUserMedia({ audio: { deviceId: { exact: t } } }).then((function (e) { var t = e.getAudioTracks()[0]; for (var o in h) h.hasOwnProperty(o) && (h[o].stream, n.getSession(o)._pc.getSenders()[0].replaceTrack(t).then((function () { n.replaceLocalMediaTrack(o, t) }))) })) } catch (e) { l.error("Failed to set microphone device " + t) } connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, data: { deviceId: t } }) } }, T = function (e, t) { if (t === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { for (var n = "\n", o = 0; o < e._iceServers.length; o++)for (var r = 0; r < e._iceServers[o].urls.length; r++)n = n + e._iceServers[o].urls[r] + "\n"; _(p.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", n) } else t === connect.RTCErrors.USER_BUSY ? _(p.USER_BUSY_ERROR, "Softphone call UserBusy error. ", "") : t === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE ? _(p.SIGNALLING_HANDSHAKE_FAILURE, "Handshaking with Signalling Server " + e._signalingUri + " failed. ", e._signalingUri) : t === connect.RTCErrors.GUM_TIMEOUT_FAILURE || t === connect.RTCErrors.GUM_OTHER_FAILURE ? _(p.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", "") : t === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE ? _(p.SIGNALLING_CONNECTION_FAILURE, "URL " + e._signalingUri + " cannot be reached. ", e._signalingUri) : t === connect.RTCErrors.CALL_NOT_FOUND ? l.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer() : _(p.WEBRTC_ERROR, "webrtc system error. ", "") }, I = function (e) { var t = e.replace(/"/g, '"'); return JSON.parse(t) }, A = function (t) { var n = t || {}; n.success = n.success || function () { }, n.failure = n.failure || function () { }; var o = { audio: !0 }, r = null; if ("function" == typeof Promise) { if ("object" === e(navigator.mediaDevices) && "function" == typeof navigator.mediaDevices.getUserMedia) r = navigator.mediaDevices.getUserMedia(o); else { if ("function" != typeof navigator.webkitGetUserMedia) return void n.failure(p.UNSUPPORTED_BROWSER); r = new Promise((function (e, t) { navigator.webkitGetUserMedia(o, e, t) })) } return r.then((function (e) { var t = e.getAudioTracks(); t && t.length > 0 ? n.success(e) : n.failure(p.MICROPHONE_NOT_SHARED) }), (function (e) { n.failure(p.MICROPHONE_NOT_SHARED) })), r } n.failure(p.UNSUPPORTED_BROWSER) }, _ = function (e, t, n) { l.error("Softphone error occurred : ", e, t || "").sendInternalLogToServer(), connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.SOFTPHONE_ERROR, data: new connect.SoftphoneError(e, t, n) }) }, w = function (e, t) { R("Softphone Session Failed", e, { failedReason: t }) }, R = function (e, t, n) { t && connect.publishMetric({ name: e, contactId: t, data: n }) }, N = function (e, t, n) { R(e, t, [{ name: "AgentConnectionId", value: n }]), l.info("Publish multiple session error metrics", e, "contactId " + t, "agent connectionId " + n).sendInternalLogToServer() }, k = function () { return !!(connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) || !!(connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) || !!(connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) }, O = function (e) { var t = i.slice(); i = [], t.length > 0 && e.sendSoftphoneMetrics(t, { success: function () { l.info("sendSoftphoneMetrics success" + JSON.stringify(t)).sendInternalLogToServer() }, failure: function (e) { l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer() } }) }, L = function (e) { a = window.setInterval((function () { e.getUserAudioStats().then((function (e) { var t = s; s = e, i.push(x(s, t, o)) }), (function (e) { l.debug("Failed to get user audio stats.", e).sendInternalLogToServer() })), e.getRemoteAudioStats().then((function (e) { var t = c; c = e, i.push(x(c, t, r)) }), (function (e) { l.debug("Failed to get remote audio stats.", e).sendInternalLogToServer() })) }), 1e3) }, D = function (e) { u = window.setInterval((function () { O(e) }), 3e4) }, P = function () { s = null, c = null, i = [], a = null, u = null }, x = function (e, t, n) { if (t && e) { var o = e.packetsLost > t.packetsLost ? e.packetsLost - t.packetsLost : 0, r = e.packetsCount > t.packetsCount ? e.packetsCount - t.packetsCount : 0; return new q(e.timestamp, o, r, n, e.audioLevel, e.jbMilliseconds, e.rttMilliseconds) } return new q(e.timestamp, e.packetsLost, e.packetsCount, n, e.audioLevel, e.jbMilliseconds, e.rttMilliseconds) }, M = function (e) { return null !== e && window.clearInterval(e), null }, U = function (e, t) { a = M(a), u = M(u), function (e, t, n, i) { t.streamStats = [F(n, o), F(i, r)]; var s = { callStartTime: t.sessionStartTime, callEndTime: t.sessionEndTime, gumTimeMillis: t.gumTimeMillis, initializationTimeMillis: t.initializationTimeMillis, iceCollectionTimeMillis: t.iceCollectionTimeMillis, signallingConnectTimeMillis: t.signallingConnectTimeMillis, handshakingTimeMillis: t.handshakingTimeMillis, preTalkingTimeMillis: t.preTalkingTimeMillis, talkingTimeMillis: t.talkingTimeMillis, cleanupTimeMillis: t.cleanupTimeMillis, iceCollectionFailure: t.iceCollectionFailure, signallingConnectionFailure: t.signallingConnectionFailure, handshakingFailure: t.handshakingFailure, gumOtherFailure: t.gumOtherFailure, gumTimeoutFailure: t.gumTimeoutFailure, createOfferFailure: t.createOfferFailure, setLocalDescriptionFailure: t.setLocalDescriptionFailure, userBusyFailure: t.userBusyFailure, invalidRemoteSDPFailure: t.invalidRemoteSDPFailure, noRemoteIceCandidateFailure: t.noRemoteIceCandidateFailure, setRemoteDescriptionFailure: t.setRemoteDescriptionFailure, softphoneStreamStatistics: t.streamStats }; e.sendSoftphoneReport(s, { success: function () { l.info("sendSoftphoneReport success" + JSON.stringify(s)).sendInternalLogToServer() }, failure: function (e) { l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer() } }) }(e, t, F(s, o), F(c, r)), O(e) }, q = function (e, t, n, o, r, i, s) { this.softphoneStreamType = o, this.timestamp = e, this.packetsLost = t, this.packetsCount = n, this.audioLevel = r, this.jitterBufferMillis = i, this.roundTripTimeMillis = s }, F = function (e, t) { return new q((e = e || {}).timestamp, e.packetsLost, e.packetsCount, t, e.audioLevel) }, j = function (e) { this._originalLogger = e; var t = this; this._tee = function (e, n) { return function () { var e = Array.prototype.slice.call(arguments[0]), o = ""; return e.forEach((function () { o += " %s" })), n.apply(t._originalLogger, [connect.LogComponent.SOFTPHONE, o].concat(e)) } } }; j.prototype.debug = function () { return this._tee(1, this._originalLogger.debug)(arguments) }, j.prototype.info = function () { return this._tee(2, this._originalLogger.info)(arguments) }, j.prototype.log = function () { return this._tee(3, this._originalLogger.log)(arguments) }, j.prototype.warn = function () { return this._tee(4, this._originalLogger.warn)(arguments) }, j.prototype.error = function () { return this._tee(5, this._originalLogger.error)(arguments) }, connect.SoftphoneManager = function (e) { var t, n = this; (l = new j(connect.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(), connect.RtcPeerConnectionFactory && (t = new connect.RtcPeerConnectionFactory(l, connect.core.getWebSocketManager(), d, connect.hitch(n, f, { transportType: "softphone", softphoneClientId: d }), connect.hitch(n, _))), k() || _(p.UNSUPPORTED_BROWSER, "Connect does not support this browser. Some functionality may not work. ", ""), A({ success: function (e) { connect.core.setSoftphoneUserMediaStream(e) }, failure: function (e) { _(e, "Your microphone is not enabled in your browser. ", "") } }), m(), v(), y(), this.ringtoneEngine = null; var o = {}, r = {}; this.onInitContactSub = {}, this.onInitContactSub.unsubscribe = function () { }; var i = !1, s = null, c = null, a = function () { i = !1, s = null, c = null }; this.getSession = function (e) { return o[e] }, this.replaceLocalMediaTrack = function (e, t) { var n = h[e].stream; if (n) { var o = n.getAudioTracks()[0]; t.enabled = o.enabled, o.enabled = !1, n.removeTrack(o), n.addTrack(t) } }; var u = function (e) { if (o.hasOwnProperty(e)) { var t = o[e]; new Promise((function (n, i) { delete o[e], delete r[e], t.hangup() })).catch((function (t) { lily.getLog().warn("Clean up the session locally " + e, t.message).sendInternalLogToServer() })) } }; this.startSession = function (e, n) { var p = i ? s : e, d = i ? c : n; if (p && d) { a(), r[d] = !0, l.info("Softphone call detected:", "contactId " + p.getContactId(), "agent connectionId " + d).sendInternalLogToServer(), function (e) { if (Object.keys(e).length > 0) { for (var t in e) e.hasOwnProperty(t) && (N("MultiSessionHangUp", e[t].callId, t), u(t)); throw new Error("duplicate session detected, refusing to setup new connection") } }(o), p.getStatus().type === connect.ContactStatusType.CONNECTING && R("Softphone Connecting", p.getContactId()), P(); var f, m = p.getAgentConnection().getSoftphoneMediaInfo(), v = I(m.callConfigJson); v.useWebSocketProvider && (f = connect.core.getWebSocketManager()); var y = new connect.RTCSession(v.signalingEndpoint, v.iceServers, m.callContextToken, l, p.getContactId(), d, f); o[d] = y, connect.core.getSoftphoneUserMediaStream() && (y.mediaStream = connect.core.getSoftphoneUserMediaStream()), connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.ConnectionEvents.SESSION_INIT, data: { connectionId: d } }), y.onSessionFailed = function (e, t) { delete o[d], delete r[d], T(e, t), w(p.getContactId(), t), U(p, e.sessionReport) }, y.onSessionConnected = function (e) { R("Softphone Session Connected", p.getContactId()), connect.becomeMaster(connect.MasterTopics.SEND_LOGS), L(e), D(p), g(p) }, y.onSessionCompleted = function (e) { R("Softphone Session Completed", p.getContactId()), delete o[d], delete r[d], U(p, e.sessionReport), E(d) }, y.onLocalStreamAdded = function (e, t) { h[d] = { stream: t }, connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, data: { connectionId: d } }) }, y.remoteAudioElement = document.getElementById("remote-audio"), t ? y.connect(t.get(v.iceServers)) : y.connect() } }; var S = function (e, t) { o[t] && function (e) { return e.getStatus().type === connect.ContactStatusType.ENDED || e.getStatus().type === connect.ContactStatusType.ERROR || e.getStatus().type === connect.ContactStatusType.MISSED }(e) && (u(t), a()), !e.isSoftphoneCall() || r[t] || e.getStatus().type !== connect.ContactStatusType.CONNECTING && e.getStatus().type !== connect.ContactStatusType.INCOMING || (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs() ? function (e, t) { i = !0, s = e, c = t }(e, t) : n.startSession(e, t)) }, b = function (e) { var t = e.getAgentConnection().connectionId; l.info("Contact detected:", "contactId " + e.getContactId(), "agent connectionId " + t).sendInternalLogToServer(), r[t] || e.onRefresh((function () { S(e, t) })) }; n.onInitContactSub = connect.contact(b), (new connect.Agent).getContacts().forEach((function (e) { var t = e.getAgentConnection().connectionId; l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + e.getContactId(), "agent connectionId " + t).sendInternalLogToServer(), b(e), S(e, t) })) } }() }, 778: () => { !function () { var e = function e() { return e.cache.hasOwnProperty(arguments[0]) || (e.cache[arguments[0]] = e.parse(arguments[0])), e.format.call(null, e.cache[arguments[0]], arguments) }; function t(e) { return Object.prototype.toString.call(e).slice(8, -1).toLowerCase() } function n(e, t) { for (var n = []; t > 0; n[--t] = e); return n.join("") } e.format = function (o, r) { var i, s, c, a, u, l, p, h = 1, d = o.length, f = "", g = []; for (s = 0; s < d; s++)if ("string" === (f = t(o[s]))) g.push(o[s]); else if ("array" === f) { if ((a = o[s])[2]) for (i = r[h], c = 0; c < a[2].length; c++) { if (!i.hasOwnProperty(a[2][c])) throw e('[sprintf] property "%s" does not exist', a[2][c]); i = i[a[2][c]] } else i = a[1] ? r[a[1]] : r[h++]; if (/[^s]/.test(a[8]) && "number" != t(i)) throw e("[sprintf] expecting number but found %s", t(i)); switch (a[8]) { case "b": i = i.toString(2); break; case "c": i = String.fromCharCode(i); break; case "d": i = parseInt(i, 10); break; case "e": i = a[7] ? i.toExponential(a[7]) : i.toExponential(); break; case "f": i = a[7] ? parseFloat(i).toFixed(a[7]) : parseFloat(i); break; case "o": i = i.toString(8); break; case "s": i = (i = String(i)) && a[7] ? i.substring(0, a[7]) : i; break; case "u": i >>>= 0; break; case "x": i = i.toString(16); break; case "X": i = i.toString(16).toUpperCase() }i = /[def]/.test(a[8]) && a[3] && i >= 0 ? "+" + i : i, l = a[4] ? "0" == a[4] ? "0" : a[4].charAt(1) : " ", p = a[6] - String(i).length, u = a[6] ? n(l, p) : "", g.push(a[5] ? i + u : u + i) } return g.join("") }, e.cache = {}, e.parse = function (e) { for (var t = e, n = [], o = [], r = 0; t;) { if (null !== (n = /^[^\x25]+/.exec(t))) o.push(n[0]); else if (null !== (n = /^\x25{2}/.exec(t))) o.push("%"); else { if (null === (n = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t))) throw "[sprintf] huh?"; if (n[2]) { r |= 1; var i = [], s = n[2], c = []; if (null === (c = /^([a-z_][a-z_\d]*)/i.exec(s))) throw "[sprintf] huh?"; for (i.push(c[1]); "" !== (s = s.substring(c[0].length));)if (null !== (c = /^\.([a-z_][a-z_\d]*)/i.exec(s))) i.push(c[1]); else { if (null === (c = /^\[(\d+)\]/.exec(s))) throw "[sprintf] huh?"; i.push(c[1]) } n[2] = i } else r |= 2; if (3 === r) throw "[sprintf] mixing positional and named placeholders is not (yet) supported"; o.push(n) } t = t.substring(n[0].length) } return o }, this.sprintf = e, this.vsprintf = function (t, n, o) { return (o = n.slice(0)).splice(0, 0, t), e.apply(null, o) } }() }, 768: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect, e.lily = connect; var t = function () { }; t.prototype.send = function (e) { throw new connect.NotImplementedError }, t.prototype.onMessage = function (e) { throw new connect.NotImplementedError }; var n = function () { t.call(this) }; (n.prototype = Object.create(t.prototype)).constructor = n, n.prototype.onMessage = function (e) { }, n.prototype.send = function (e) { }; var o = function (e, n) { t.call(this), this.window = e, this.domain = n || "*" }; (o.prototype = Object.create(t.prototype)).constructor = o, o.prototype.send = function (e) { this.window.postMessage(e, this.domain) }, o.prototype.onMessage = function (e) { this.window.addEventListener("message", e) }; var r = function (e, n, o) { t.call(this), this.input = e, this.output = n, this.domain = o || "*" }; (r.prototype = Object.create(t.prototype)).constructor = r, r.prototype.send = function (e) { this.output.postMessage(e, this.domain) }, r.prototype.onMessage = function (e) { var t = this; this.input.addEventListener("message", (function (n) { n.source === t.output && e(n) })) }; var i = function (e) { t.call(this), this.port = e, this.id = connect.randomId() }; (i.prototype = Object.create(t.prototype)).constructor = i, i.prototype.send = function (e) { this.port.postMessage(e) }, i.prototype.onMessage = function (e) { this.port.addEventListener("message", e) }, i.prototype.getId = function () { return this.id }; var s = function (e) { t.call(this), this.streamMap = e ? connect.index(e, (function (e) { return e.getId() })) : {}, this.messageListeners = [] }; (s.prototype = Object.create(t.prototype)).constructor = s, s.prototype.send = function (e) { this.getStreams().forEach((function (t) { try { t.send(e) } catch (e) { } })) }, s.prototype.onMessage = function (e) { this.messageListeners.push(e), this.getStreams().forEach((function (t) { t.onMessage(e) })) }, s.prototype.addStream = function (e) { this.streamMap[e.getId()] = e, this.messageListeners.forEach((function (t) { e.onMessage(t) })) }, s.prototype.removeStream = function (e) { delete this.streamMap[e.getId()] }, s.prototype.getStreams = function (e) { return connect.values(this.streamMap) }, s.prototype.getStreamForPort = function (e) { return connect.find(this.getStreams(), (function (t) { return t.port === e })) }; var c = function (e, t, o) { this.name = e, this.upstream = t || new n, this.downstream = o || new n, this.downstreamBus = new connect.EventBus, this.upstreamBus = new connect.EventBus, this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)), this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)) }; c.prototype.onUpstream = function (e, t) { return connect.assertNotNull(e, "eventName"), connect.assertNotNull(t, "f"), connect.assertTrue(connect.isFunction(t), "f must be a function"), this.upstreamBus.subscribe(e, t) }, c.prototype.onAllUpstream = function (e) { return connect.assertNotNull(e, "f"), connect.assertTrue(connect.isFunction(e), "f must be a function"), this.upstreamBus.subscribeAll(e) }, c.prototype.onDownstream = function (e, t) { return connect.assertNotNull(e, "eventName"), connect.assertNotNull(t, "f"), connect.assertTrue(connect.isFunction(t), "f must be a function"), this.downstreamBus.subscribe(e, t) }, c.prototype.onAllDownstream = function (e) { return connect.assertNotNull(e, "f"), connect.assertTrue(connect.isFunction(e), "f must be a function"), this.downstreamBus.subscribeAll(e) }, c.prototype.sendUpstream = function (e, t) { connect.assertNotNull(e, "eventName"), this.upstream.send({ event: e, data: t }) }, c.prototype.sendDownstream = function (e, t) { connect.assertNotNull(e, "eventName"), this.downstream.send({ event: e, data: t }) }, c.prototype._dispatchEvent = function (e, t) { var n = t.data; n.event && e.trigger(n.event, n.data) }, c.prototype.passUpstream = function () { var e = this; return function (t, n) { e.upstream.send({ event: n, data: t }) } }, c.prototype.passDownstream = function () { var e = this; return function (t, n) { e.downstream.send({ event: n, data: t }) } }, c.prototype.shutdown = function () { this.upstreamBus.unsubscribeAll(), this.downstreamBus.unsubscribeAll() }; var a = function (e, t, n, o) { c.call(this, e, new r(t, n.contentWindow, o || "*"), null) }; (a.prototype = Object.create(c.prototype)).constructor = a, connect.Stream = t, connect.NullStream = n, connect.WindowStream = o, connect.WindowIOStream = r, connect.PortStream = i, connect.StreamMultiplexer = s, connect.Conduit = c, connect.IFrameConduit = a }() }, 738: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect, e.lily = connect; var t = function (e, t) { connect.assertNotNull(e, "fromState"), connect.assertNotNull(t, "toState"), this.fromState = e, this.toState = t }; t.prototype.getAssociations = function (e) { throw connect.NotImplementedError() }, t.prototype.getFromState = function () { return this.fromState }, t.prototype.getToState = function () { return this.toState }; var n = function (e, n, o) { connect.assertNotNull(e, "fromState"), connect.assertNotNull(n, "toState"), connect.assertNotNull(o, "associations"), t.call(this, e, n), this.associations = o }; (n.prototype = Object.create(t.prototype)).constructor = n, n.prototype.getAssociations = function (e) { return this.associations }; var o = function (e, n, o) { connect.assertNotNull(e, "fromState"), connect.assertNotNull(n, "toState"), connect.assertNotNull(o, "closure"), connect.assertTrue(connect.isFunction(o), "closure must be a function"), t.call(this, e, n), this.closure = o }; (o.prototype = Object.create(t.prototype)).constructor = o, o.prototype.getAssociations = function (e) { return this.closure(e, this.getFromState(), this.getToState()) }; var r = function () { this.fromMap = {} }; r.ANY = "<>", r.prototype.assoc = function (e, t, r) { var i = this; if (!e) throw new Error("fromStateObj is not defined."); if (!t) throw new Error("toStateObj is not defined."); if (!r) throw new Error("assocObj is not defined."); return e instanceof Array ? e.forEach((function (e) { i.assoc(e, t, r) })) : t instanceof Array ? t.forEach((function (t) { i.assoc(e, t, r) })) : "function" == typeof r ? this._addAssociation(new o(e, t, r)) : r instanceof Array ? this._addAssociation(new n(e, t, r)) : this._addAssociation(new n(e, t, [r])), this }, r.prototype.getAssociations = function (e, t, n) { connect.assertNotNull(t, "fromState"), connect.assertNotNull(n, "toState"); var o = [], i = this.fromMap[r.ANY] || {}, s = this.fromMap[t] || {}; return o = (o = o.concat(this._getAssociationsFromMap(i, e, t, n))).concat(this._getAssociationsFromMap(s, e, t, n)) }, r.prototype._addAssociation = function (e) { var t = this.fromMap[e.getFromState()]; t || (t = this.fromMap[e.getFromState()] = {}); var n = t[e.getToState()]; n || (n = t[e.getToState()] = []), n.push(e) }, r.prototype._getAssociationsFromMap = function (e, t, n, o) { return (e[r.ANY] || []).concat(e[o] || []).reduce((function (e, n) { return e.concat(n.getAssociations(t)) }), []) }, connect.EventGraph = r }() }, 420: () => { function e(t) { return e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, e(t) } !function () { var t = this; connect = t.connect || {}, t.connect = connect, t.lily = connect; var n = navigator.userAgent, o = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; connect.sprintf = t.sprintf, connect.vsprintf = t.vsprintf, delete t.sprintf, delete t.vsprintf, connect.HTTP_STATUS_CODES = { SUCCESS: 200, TOO_MANY_REQUESTS: 429, INTERNAL_SERVER_ERROR: 500 }, connect.TRANSPORT_TYPES = { CHAT_TOKEN: "chat_token", WEB_SOCKET: "web_socket" }, connect.hitch = function () { var e = Array.prototype.slice.call(arguments), t = e.shift(), n = e.shift(); return connect.assertNotNull(t, "scope"), connect.assertNotNull(n, "method"), connect.assertTrue(connect.isFunction(n), "method must be a function"), function () { var o = Array.prototype.slice.call(arguments); return n.apply(t, e.concat(o)) } }, connect.isFunction = function (e) { return !!(e && e.constructor && e.call && e.apply) }, connect.isArray = function (e) { return "[object Array]" === Object.prototype.toString.call(e) }, connect.keys = function (e) { var t = []; for (var n in connect.assertNotNull(e, "map"), e) t.push(n); return t }, connect.values = function (e) { var t = []; for (var n in connect.assertNotNull(e, "map"), e) t.push(e[n]); return t }, connect.entries = function (e) { var t = []; for (var n in e) t.push({ key: n, value: e[n] }); return t }, connect.merge = function () { var e = Array.prototype.slice.call(arguments, 0), t = {}; return e.forEach((function (e) { connect.entries(e).forEach((function (e) { t[e.key] = e.value })) })), t }, connect.now = function () { return (new Date).getTime() }, connect.find = function (e, t) { for (var n = 0; n < e.length; n++)if (t(e[n])) return e[n]; return null }, connect.contains = function (e, t) { return e instanceof Array ? null != connect.find(e, (function (e) { return e === t })) : t in e }, connect.containsValue = function (e, t) { return e instanceof Array ? null != connect.find(e, (function (e) { return e === t })) : null != connect.find(connect.values(e), (function (e) { return e === t })) }, connect.randomId = function () { return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)) }, connect.makeEnum = function (e) { var t = {}; return e.forEach((function (e) { var n = e.replace(/\.?([a-z]+)_?/g, (function (e, t) { return t.toUpperCase() + "_" })).replace(/_$/, ""); t[n] = e })), t }, connect.makeNamespacedEnum = function (e, t) { var n = connect.makeEnum(t); return connect.keys(n).forEach((function (t) { n[t] = connect.sprintf("%s::%s", e, n[t]) })), n }, connect.makeGenericNamespacedEnum = function (e, t, n) { var o = connect.makeEnum(t); return connect.keys(o).forEach((function (t) { o[t] = connect.sprintf("%s" + n + "%s", e, o[t]) })), o }, connect.isChromeBrowser = function () { return -1 !== n.indexOf("Chrome") }, connect.isFirefoxBrowser = function () { return -1 !== n.indexOf("Firefox") }, connect.isOperaBrowser = function () { return -1 !== n.indexOf("Opera") }, connect.getChromeBrowserVersion = function () { var e = n.substring(n.indexOf("Chrome") + 7); return e ? parseFloat(e) : -1 }, connect.getFirefoxBrowserVersion = function () { var e = n.substring(n.indexOf("Firefox") + 8); return e ? parseFloat(e) : -1 }, connect.isValidLocale = function (e) { return [{ id: "en_US", label: "English" }, { id: "de_DE", label: "Deutsch" }, { id: "es_ES", label: "Español" }, { id: "fr_FR", label: "Français" }, { id: "ja_JP", label: "日本語" }, { id: "it_IT", label: "Italiano" }, { id: "ko_KR", label: "한국어" }, { id: "pt_BR", label: "Português" }, { id: "zh_CN", label: "中文(简体)" }, { id: "zh_TW", label: "中文(繁體)" }].map((function (e) { return e.id })).includes(e) }, connect.getOperaBrowserVersion = function () { var e = n.indexOf("Opera"), t = -1 !== n.indexOf("Version") ? n.substring(e + 8) : n.substring(e + 6); return t ? parseFloat(t) : -1 }, connect.index = function (e, t) { var n = {}; return e.forEach((function (e) { n[t(e)] = e })), n }, connect.set = function (e) { var t = {}; return e.forEach((function (e) { t[e] = 1 })), t }, connect.relativeComplement = function (e, t) { var n = {}; return connect.keys(t).forEach((function (o) { o in e || (n[o] = t[o]) })), n }, connect.assertTrue = function (e, t) { if (!e) throw new connect.ValueError(t) }, connect.assertNotNull = function (t, n) { return connect.assertTrue(null != t && void 0 !== e(t), connect.sprintf("%s must be provided", n || "A value")), t }, connect.deepcopy = function (e) { return JSON.parse(JSON.stringify(e)) }, connect.deepcopyCrossOriginEvent = function (e) { var t = {}; return o.forEach((function (n) { try { t[n] = e[n] } catch (e) { connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", n).sendInternalLogToServer() } })), connect.deepcopy(t) }, connect.getBaseUrl = function () { var e = t.location; return connect.sprintf("%s//%s:%s", e.protocol, e.hostname, e.port) }, connect.getUrlWithProtocol = function (e) { var n = t.location.protocol; return e.substr(0, n.length) !== n ? connect.sprintf("%s//%s", n, e) : e }, connect.isFramed = function () { try { return window.self !== window.top } catch (e) { return !0 } }, connect.hasOtherConnectedCCPs = function () { return connect.numberOfConnectedCCPs > 1 }, connect.fetch = function (e, t, n, o) { return o = o || 5, n = n || 1e3, t = t || {}, new Promise((function (r, i) { !function o(s) { fetch(e, t).then((function (e) { e.status === connect.HTTP_STATUS_CODES.SUCCESS ? e.json().then((function (e) { return r(e) })).catch((function () { return r({}) })) : 1 !== s && (e.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || e.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS) ? setTimeout((function () { o(--s) }), n) : i(e) })).catch((function (e) { i(e) })) }(o) })) }, connect.backoff = function (e, n, o, r) { connect.assertTrue(connect.isFunction(e), "func must be a Function"); var i = this; e({ success: function (e) { r && r.success && r.success(e) }, failure: function (s, c) { if (o > 0) { var a = 2 * n * Math.random(); t.setTimeout((function () { i.backoff(e, 2 * a, --o, r) }), a) } else r && r.failure && r.failure(s, c) } }) }, connect.publishMetric = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.CLIENT_METRIC, data: e }) }, connect.publishSoftphoneStats = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.SOFTPHONE_STATS, data: e }) }, connect.publishSoftphoneReport = function (e) { connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { event: connect.EventType.SOFTPHONE_REPORT, data: e }) }, connect.publishClientSideLogs = function (e) { connect.core.getEventBus().trigger(connect.EventType.CLIENT_SIDE_LOGS, e) }, connect.PopupManager = function () { }, connect.PopupManager.prototype.open = function (e, t, n) { var o = this._getLastOpenedTimestamp(t), r = (new Date).getTime(), i = null; if (r - o > 864e5) { if (n) { var s = n.height || 578, c = n.width || 433, a = n.top || 0, u = n.left || 0; (i = window.open("", t, "width=" + c + ", height=" + s + ", top=" + a + ", left=" + u)).location !== e && (i = window.open(e, t, "width=" + c + ", height=" + s + ", top=" + a + ", left=" + u)) } else (i = window.open("", t)).location !== e && (i = window.open(e, t)); this._setLastOpenedTimestamp(t, r) } return i }, connect.PopupManager.prototype.clear = function (e) { var n = this._getLocalStorageKey(e); t.localStorage.removeItem(n) }, connect.PopupManager.prototype._getLastOpenedTimestamp = function (e) { var n = this._getLocalStorageKey(e), o = t.localStorage.getItem(n); return o ? parseInt(o, 10) : 0 }, connect.PopupManager.prototype._setLastOpenedTimestamp = function (e, n) { var o = this._getLocalStorageKey(e); t.localStorage.setItem(o, "" + n) }, connect.PopupManager.prototype._getLocalStorageKey = function (e) { return "connectPopupManager::" + e }; var r = connect.makeEnum(["granted", "denied", "default"]); connect.NotificationManager = function () { this.queue = [], this.permission = r.DEFAULT }, connect.NotificationManager.prototype.requestPermission = function () { var e = this; "Notification" in t ? t.Notification.permission === r.DENIED ? (connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(), this.permission = r.DENIED) : this.permission !== r.GRANTED && t.Notification.requestPermission().then((function (t) { e.permission = t, t === r.GRANTED ? e._showQueued() : e.queue = [] })) : (connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(), this.permission = r.DENIED) }, connect.NotificationManager.prototype.show = function (e, t) { if (this.permission === r.GRANTED) return this._showImpl({ title: e, options: t }); if (this.permission === r.DENIED) connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({ title: e, options: t }); else { var n = { title: e, options: t }; connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(n).sendInternalLogToServer(), this.queue.push(n) } }, connect.NotificationManager.prototype._showQueued = function () { var e = this, t = this.queue.map((function (t) { return e._showImpl(t) })); return this.queue = [], t }, connect.NotificationManager.prototype._showImpl = function (e) { var n = new t.Notification(e.title, e.options); return e.options.clicked && (n.onclick = function () { e.options.clicked.call(n) }), n }, connect.BaseError = function (e, n) { t.Error.call(this, connect.vsprintf(e, n)) }, connect.BaseError.prototype = Object.create(Error.prototype), connect.BaseError.prototype.constructor = connect.BaseError, connect.ValueError = function () { var e = Array.prototype.slice.call(arguments, 0), t = e.shift(); connect.BaseError.call(this, t, e) }, connect.ValueError.prototype = Object.create(connect.BaseError.prototype), connect.ValueError.prototype.constructor = connect.ValueError, connect.NotImplementedError = function () { var e = Array.prototype.slice.call(arguments, 0), t = e.shift(); connect.BaseError.call(this, t, e) }, connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype), connect.NotImplementedError.prototype.constructor = connect.NotImplementedError, connect.StateError = function () { var e = Array.prototype.slice.call(arguments, 0), t = e.shift(); connect.BaseError.call(this, t, e) }, connect.StateError.prototype = Object.create(connect.BaseError.prototype), connect.StateError.prototype.constructor = connect.StateError, connect.VoiceIdError = function (e, t, n) { var o = {}; return o.type = e, o.message = t, o.stack = Error(t).stack, o.err = n, o }, connect.isCCP = function () { return "ConnectSharedWorkerConduit" === connect.core.getUpstream().name } }() }, 744: () => { !function () { var e = this; connect = e.connect || {}, e.connect = connect, e.lily = connect, connect.worker = {}; var t = function () { this.topicMasterMap = {} }; t.prototype.getMaster = function (e) { return connect.assertNotNull(e, "topic"), this.topicMasterMap[e] || null }, t.prototype.setMaster = function (e, t) { connect.assertNotNull(e, "topic"), connect.assertNotNull(t, "id"), this.topicMasterMap[e] = t }, t.prototype.removeMaster = function (e) { connect.assertNotNull(e, "id"); var t = this; connect.entries(this.topicMasterMap).filter((function (t) { return t.value === e })).forEach((function (e) { delete t.topicMasterMap[e.key] })) }; var n = function (e) { connect.ClientBase.call(this), this.conduit = e }; (n.prototype = Object.create(connect.ClientBase.prototype)).constructor = n, n.prototype._callImpl = function (e, t, n) { var o = this, r = (new Date).getTime(); connect.containsValue(connect.AgentAppClientMethods, e) ? connect.core.getAgentAppClient()._callImpl(e, t, { success: function (t) { o._recordAPILatency(e, r), n.success(t) }, failure: function (t) { o._recordAPILatency(e, r, t), n.failure(t) } }) : connect.core.getClient()._callImpl(e, t, { success: function (t) { o._recordAPILatency(e, r), n.success(t) }, failure: function (t, i) { o._recordAPILatency(e, r, t), n.failure(t, i) }, authFailure: function () { o._recordAPILatency(e, r), n.authFailure() }, accessDenied: function () { n.accessDenied && n.accessDenied() } }) }, n.prototype._recordAPILatency = function (e, t, n) { var o = (new Date).getTime() - t; this._sendAPIMetrics(e, o, n) }, n.prototype._sendAPIMetrics = function (e, t, n) { this.conduit.sendDownstream(connect.EventType.API_METRIC, { name: e, time: t, dimensions: [{ name: "Category", value: "API" }], error: n }) }; var o = function () { var o = this; this.multiplexer = new connect.StreamMultiplexer, this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer), this.client = new n(this.conduit), this.timeout = null, this.agent = null, this.nextToken = null, this.initData = {}, this.portConduitMap = {}, this.masterCoord = new t, this.logsBuffer = [], this.suppress = !1, this.forceOffline = !1; var r = null; connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit), this.conduit.onDownstream(connect.EventType.SEND_LOGS, (function (e) { connect.getLog().pushLogsDownstream(e), o.logsBuffer = o.logsBuffer.concat(e), o.logsBuffer.length > 400 && o.handleSendLogsRequest(o.logsBuffer) })), this.conduit.onDownstream(connect.EventType.CONFIGURE, (function (t) { t.authToken && t.authToken !== o.initData.authToken && (o.initData = t, connect.core.init(t), r ? connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer() : (connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(), connect.WebSocketManager.setGlobalConfig({ loggerConfig: { logger: connect.getLog() } }), (r = connect.WebSocketManager.create()).onInitFailure((function () { o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE) })), r.onConnectionOpen((function (e) { o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, e) })), r.onConnectionClose((function (e) { o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, e) })), r.onConnectionGain((function () { o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED), o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN) })), r.onConnectionLost((function (e) { o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, e), o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, e) })), r.onSubscriptionUpdate((function (e) { o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, e) })), r.onSubscriptionFailure((function (e) { o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, e) })), r.onAllMessage((function (e) { o.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, e) })), o.conduit.onDownstream(connect.WebSocketEvents.SEND, (function (e) { r.sendMessage(e) })), o.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, (function (e) { r.subscribeTopics(e) })), r.init(connect.hitch(o, o.getWebSocketUrl)).then((function (t) { t && !t.webSocketConnectionFailed ? (connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(), o.pollForAgent(), connect.getLog().info("Kicking off config polling").sendInternalLogToServer(), o.pollForAgentConfiguration({ repeatForever: !0 }), connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(), e.setInterval(connect.hitch(o, o.checkAuthToken), 3e5)) : connect.webSocketInitFailed || (o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE), connect.webSocketInitFailed = !0) })))) })), this.conduit.onDownstream(connect.EventType.TERMINATE, (function () { o.handleSendLogsRequest(o.logsBuffer), connect.core.terminate(), o.conduit.sendDownstream(connect.EventType.TERMINATED) })), this.conduit.onDownstream(connect.EventType.SYNCHRONIZE, (function () { o.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE) })), this.conduit.onDownstream(connect.EventType.BROADCAST, (function (e) { o.conduit.sendDownstream(e.event, e.data) })), e.onconnect = function (e) { var t = e.ports[0], n = new connect.PortStream(t); o.multiplexer.addStream(n), t.start(); var r = new connect.Conduit(n.getId(), null, n); r.sendDownstream(connect.EventType.ACKNOWLEDGE, { id: n.getId() }), o.portConduitMap[n.getId()] = r, o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(o.portConduitMap).length }), null !== o.agent && o.updateAgent(), r.onDownstream(connect.EventType.API_REQUEST, connect.hitch(o, o.handleAPIRequest, r)), r.onDownstream(connect.EventType.MASTER_REQUEST, connect.hitch(o, o.handleMasterRequest, r, n.getId())), r.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(o, o.pollForAgentConfiguration)), r.onDownstream(connect.EventType.CLOSE, (function () { o.multiplexer.removeStream(n), delete o.portConduitMap[n.getId()], o.masterCoord.removeMaster(n.getId()), o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { length: Object.keys(o.portConduitMap).length }) })) } }; o.prototype.pollForAgent = function () { var t = this, n = connect.hitch(t, t.handleAuthFail); this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT, { nextToken: t.nextToken, timeout: 3e4 }, { success: function (n) { try { t.agent = t.agent || {}, t.agent.snapshot = n.snapshot, t.agent.snapshot.localTimestamp = connect.now(), t.agent.snapshot.skew = t.agent.snapshot.snapshotTimestamp - t.agent.snapshot.localTimestamp, t.nextToken = n.nextToken, connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(n).sendInternalLogToServer(), t.updateAgent() } catch (e) { connect.getLog().error("Long poll failed to update agent.").withObject(n).withException(e).sendInternalLogToServer() } finally { e.setTimeout(connect.hitch(t, t.pollForAgent), 100) } }, failure: function (n, o) { try { connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({ err: n, data: o }) } finally { e.setTimeout(connect.hitch(t, t.pollForAgent), 5e3) } }, authFailure: function () { n() }, accessDenied: connect.hitch(t, t.handleAccessDenied) }) }, o.prototype.pollForAgentConfiguration = function (t) { var n = this, o = t || {}, r = connect.hitch(n, n.handleAuthFail); this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION, {}, { success: function (t) { var r = t.configuration; n.pollForAgentPermissions(r), n.pollForAgentStates(r), n.pollForDialableCountryCodes(r), n.pollForRoutingProfileQueues(r), o.repeatForever && e.setTimeout(connect.hitch(n, n.pollForAgentConfiguration, o), 3e4) }, failure: function (t, r) { try { connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({ err: t, data: r }) } finally { o.repeatForever && e.setTimeout(connect.hitch(n, n.pollForAgentConfiguration), 3e4, o) } }, authFailure: function () { r() }, accessDenied: connect.hitch(n, n.handleAccessDenied) }) }, o.prototype.pollForAgentStates = function (e, t) { var n = this, o = t || {}; o.maxResults = o.maxResults || connect.DEFAULT_BATCH_SIZE, this.client.call(connect.ClientMethods.GET_AGENT_STATES, { nextToken: o.nextToken || null, maxResults: o.maxResults }, { success: function (t) { t.nextToken ? n.pollForAgentStates(e, { states: (o.states || []).concat(t.states), nextToken: t.nextToken, maxResults: o.maxResults }) : (e.agentStates = (o.states || []).concat(t.states), n.updateAgentConfiguration(e)) }, failure: function (e, t) { connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({ err: e, data: t }) }, authFailure: connect.hitch(n, n.handleAuthFail), accessDenied: connect.hitch(n, n.handleAccessDenied) }) }, o.prototype.pollForAgentPermissions = function (e, t) { var n = this, o = t || {}; o.maxResults = o.maxResults || connect.DEFAULT_BATCH_SIZE, this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS, { nextToken: o.nextToken || null, maxResults: o.maxResults }, { success: function (t) { t.nextToken ? n.pollForAgentPermissions(e, { permissions: (o.permissions || []).concat(t.permissions), nextToken: t.nextToken, maxResults: o.maxResults }) : (e.permissions = (o.permissions || []).concat(t.permissions), n.updateAgentConfiguration(e)) }, failure: function (e, t) { connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({ err: e, data: t }) }, authFailure: connect.hitch(n, n.handleAuthFail), accessDenied: connect.hitch(n, n.handleAccessDenied) }) }, o.prototype.pollForDialableCountryCodes = function (e, t) { var n = this, o = t || {}; o.maxResults = o.maxResults || connect.DEFAULT_BATCH_SIZE, this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, { nextToken: o.nextToken || null, maxResults: o.maxResults }, { success: function (t) { t.nextToken ? n.pollForDialableCountryCodes(e, { countryCodes: (o.countryCodes || []).concat(t.countryCodes), nextToken: t.nextToken, maxResults: o.maxResults }) : (e.dialableCountries = (o.countryCodes || []).concat(t.countryCodes), n.updateAgentConfiguration(e)) }, failure: function (e, t) { connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({ err: e, data: t }) }, authFailure: connect.hitch(n, n.handleAuthFail), accessDenied: connect.hitch(n, n.handleAccessDenied) }) }, o.prototype.pollForRoutingProfileQueues = function (e, t) { var n = this, o = t || {}; o.maxResults = o.maxResults || connect.DEFAULT_BATCH_SIZE, this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES, { routingProfileARN: e.routingProfile.routingProfileARN, nextToken: o.nextToken || null, maxResults: o.maxResults }, { success: function (t) { t.nextToken ? n.pollForRoutingProfileQueues(e, { countryCodes: (o.queues || []).concat(t.queues), nextToken: t.nextToken, maxResults: o.maxResults }) : (e.routingProfile.queues = (o.queues || []).concat(t.queues), n.updateAgentConfiguration(e)) }, failure: function (e, t) { connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({ err: e, data: t }) }, authFailure: connect.hitch(n, n.handleAuthFail), accessDenied: connect.hitch(n, n.handleAccessDenied) }) }, o.prototype.handleAPIRequest = function (e, t) { var n = this; this.client.call(t.method, t.params, { success: function (n) { var o = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, t, n); e.sendDownstream(o.event, o) }, failure: function (o, r) { var i = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, t, r, JSON.stringify(o)); e.sendDownstream(i.event, i), connect.getLog().error("'%s' API request failed", t.method).withObject({ request: n.filterAuthToken(t), response: i }).withException(o).sendInternalLogToServer() }, authFailure: connect.hitch(n, n.handleAuthFail) }) }, o.prototype.handleMasterRequest = function (e, t, n) { var o = this.conduit, r = null; switch (n.method) { case connect.MasterMethods.BECOME_MASTER: var i = this.masterCoord.getMaster(n.params.topic), s = Boolean(i) && i !== t; this.masterCoord.setMaster(n.params.topic, t), r = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, n, { masterId: t, takeOver: s, topic: n.params.topic }), s && o.sendDownstream(r.event, r); break; case connect.MasterMethods.CHECK_MASTER: (i = this.masterCoord.getMaster(n.params.topic)) || n.params.shouldNotBecomeMasterIfNone || (this.masterCoord.setMaster(n.params.topic, t), i = t), r = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, n, { masterId: i, isMaster: t === i, topic: n.params.topic }); break; default: throw new Error("Unknown master method: " + n.method) }e.sendDownstream(r.event, r) }, o.prototype.updateAgentConfiguration = function (e) { e.permissions && e.dialableCountries && e.agentStates && e.routingProfile.queues ? (this.agent = this.agent || {}, this.agent.configuration = e, this.updateAgent()) : connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer() }, o.prototype.updateAgent = function () { this.agent ? this.agent.snapshot ? this.agent.configuration ? (this.agent.snapshot.status = this.agent.state, this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1 && this.agent.snapshot.contacts.sort((function (e, t) { return e.state.timestamp.getTime() - t.state.timestamp.getTime() })), this.agent.snapshot.contacts.forEach((function (e) { e.status = e.state, e.connections.forEach((function (e) { e.address = e.endpoint })) })), this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN, this.agent.configuration.routingProfile.queues.forEach((function (e) { e.queueId = e.queueARN })), this.agent.snapshot.contacts.forEach((function (e) { void 0 !== e.queue && (e.queue.queueId = e.queue.queueARN) })), this.agent.configuration.routingProfile.routingProfileId = this.agent.configuration.routingProfile.routingProfileARN, this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent)) : connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer() : connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer() : connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer() }, o.prototype.getWebSocketUrl = function () { var e = this, t = connect.core.getClient(), n = connect.hitch(e, e.handleAuthFail), o = connect.hitch(e, e.handleAccessDenied); return new Promise((function (e, r) { t.call(connect.ClientMethods.CREATE_TRANSPORT, { transportType: connect.TRANSPORT_TYPES.WEB_SOCKET }, { success: function (t) { connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(), e(t) }, failure: function (e, t) { connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({ err: e, data: t }), r({ reason: "getWebSocketUrl failed", _debug: e }) }, authFailure: function () { connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(), r(Error("Authentication failed while getting getWebSocketUrl")), n() }, accessDenied: function () { connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(), r(Error("Access Denied Failure while getting getWebSocketUrl")), o() } }) })) }, o.prototype.handleSendLogsRequest = function () { var e = this, t = [], n = e.logsBuffer.slice(); e.logsBuffer = [], n.forEach((function (e) { t.push({ timestamp: e.time, component: e.component, message: e.text }) })), this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { logEvents: t }, { success: function (e) { connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer() }, failure: function (e, t) { connect.getLog().error("SendLogs request failed.").withObject(t).withException(e).sendInternalLogToServer() }, authFailure: connect.hitch(e, e.handleAuthFail) }) }, o.prototype.handleAuthFail = function () { this.conduit.sendDownstream(connect.EventType.AUTH_FAIL) }, o.prototype.handleAccessDenied = function () { this.conduit.sendDownstream(connect.EventType.ACCESS_DENIED) }, o.prototype.checkAuthToken = function () { var e = this, t = new Date(e.initData.authTokenExpiration), n = (new Date).getTime(); t.getTime() < n + 18e5 && (connect.getLog().info("Auth token expires at " + t + " Start refreshing token with retry.").sendInternalLogToServer(), connect.backoff(connect.hitch(e, e.authorize), 1e4, 4)) }, o.prototype.authorize = function (e) { var t = this; connect.core.authorize(this.initData.authorizeEndpoint).then((function (n) { var o = new Date(n.expiration); connect.getLog().info("Authorization succeeded and the token expires at %s", o).sendInternalLogToServer(), t.initData.authToken = n.accessToken, t.initData.authTokenExpiration = o, connect.core.initClient(t.initData), connect.core.initAgentAppClient(t.initData), e.success() })).catch((function (n) { connect.getLog().error("Authorization failed with code %s", n.status).sendInternalLogToServer(), 401 === n.status ? t.handleAuthFail() : e.failure() })) }, o.prototype.filterAuthToken = function (e) { var t = {}; for (var n in e) if ("params" === n) { var o = {}; for (var r in e.params) "authentication" !== r && (o[r] = e.params[r]); t.params = o } else t[n] = e[n]; return t }, connect.worker.main = function () { connect.worker.clientEngine = new o } }() } }, t = {}; function n(o) { var r = t[o]; if (void 0 !== r) return r.exports; var i = t[o] = { exports: {} }; return e[o](i, i.exports, n), i.exports } n.amdO = {}, n.g = function () { if ("object" == typeof globalThis) return globalThis; try { return this || new Function("return this")() } catch (e) { if ("object" == typeof window) return window } }(), n(538), n(778), n(312), n(420), n(547), n(768), n(417), n(738), n(35), n(42), n(743), n(531), n(555), n(960), n(744), n(158), n(7), n(6), n(487), n(340), n(228) })(); \ No newline at end of file +(()=>{var e={340:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.agentApp={};var t="ccp";connect.agentApp.initCCP=connect.core.initCCP,connect.agentApp.isInitialized=function(e){},connect.agentApp.initAppCommunication=function(e,t){var n=document.getElementById(e),o=new connect.IFrameConduit(t,window,n),r=[connect.AgentEvents.UPDATE,connect.ContactEvents.VIEW,connect.EventType.ACKNOWLEDGE,connect.EventType.TERMINATED,connect.TaskEvents.CREATED];n.addEventListener("load",(function(e){r.forEach((function(e){connect.core.getUpstream().onUpstream(e,(function(t){o.sendUpstream(e,t)}))}))}))};var n=function(e){var t=e.indexOf("ccp-v2");return e.slice(0,t-1)};connect.agentApp.initApp=function(e,o,r,i){i=i||{};var s=r.endsWith("/")?r:r+"/",c=i.onLoad?i.onLoad:null,a={endpoint:s,style:i.style,onLoad:c};connect.agentApp.AppRegistry.register(e,a,document.getElementById(o)),connect.agentApp.AppRegistry.start(e,(function(o){var r=o.endpoint,s=o.containerDOM;return{init:function(){return e===t?function(e,t,o){var r={ccpUrl:e,ccpLoadTimeout:1e4,loginPopup:!0,loginUrl:n(e)+"/login",softphone:{allowFramedSoftphone:!0,disableRingtone:!1}},i=connect.merge(r,o.ccpParams);connect.core.initCCP(t,i)}(r,s,i):connect.agentApp.initAppCommunication(e,r)},destroy:function(){return e===t?(o=n(r)+"/logout",connect.fetch(o,{credentials:"include"}).then((function(){return connect.core.getEventBus().trigger(connect.EventType.TERMINATE),!0})).catch((function(e){return connect.getLog().error("An error occured on logout."+e).withException(e),window.location.href=o,!1}))):null;var o}}}))},connect.agentApp.stopApp=function(e){return connect.agentApp.AppRegistry.stop(e)}}()},228:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect;var t,n="ccp";e.connect.agentApp.AppRegistry=(t={},{register:function(e,n,o){t[e]={containerDOM:o,endpoint:n.endpoint,style:n.style,instance:void 0,onLoad:n.onLoad}},start:function(e,o){if(t[e]){var r=t[e].containerDOM,i=t[e].endpoint,s=t[e].style,c=t[e].onLoad;if(e!==n){var a=function(e,t,n,o){var r=document.createElement("iframe");return r.src=t,r.style=n||"width: 100%; height:100%;",r.id=e,r["aria-label"]=e,r.onload=o,r.setAttribute("sandbox","allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"),r}(e,i,s,c);r.appendChild(a)}return t[e].instance=o(t[e]),t[e].instance.init()}},stop:function(e){if(t[e]){var n,o=t[e],r=o.containerDOM.querySelector("iframe");return o.containerDOM.removeChild(r),o.instance&&(n=o.instance.destroy(),delete o.instance),n}}})}()},35:()=>{function e(e,n){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!o){if(Array.isArray(e)||(o=function(e,n){if(e){if("string"==typeof e)return t(e,n);var o=Object.prototype.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){o&&(e=o);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,c=!0,a=!1;return{s:function(){o=o.call(e)},n:function(){var e=o.next();return c=e.done,e},e:function(e){a=!0,s=e},f:function(){try{c||null==o.return||o.return()}finally{if(a)throw s}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n0&&(n=r[0].getConnectionId())}t.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS,{contactId:this.getContactId(),connectionId:n},e)},r.prototype.sendSoftphoneMetrics=function(e,n){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS,{contactId:this.getContactId(),ccpVersion:t.ccpVersion,softphoneStreamStatistics:e},n),connect.publishSoftphoneStats({contactId:this.getContactId(),ccpVersion:t.ccpVersion,stats:e})},r.prototype.sendSoftphoneReport=function(e,n){connect.core.getClient().call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT,{contactId:this.getContactId(),ccpVersion:t.ccpVersion,report:e},n),connect.publishSoftphoneReport({contactId:this.getContactId(),ccpVersion:t.ccpVersion,report:e})},r.prototype.conferenceConnections=function(e){connect.core.getClient().call(connect.ClientMethods.CONFERENCE_CONNECTIONS,{contactId:this.getContactId()},e)},r.prototype.toSnapshot=function(){return new connect.ContactSnapshot(this._getData())};var i=function(e){connect.Contact.call(this,e.contactId),this.contactData=e};(i.prototype=Object.create(r.prototype)).constructor=i,i.prototype._getData=function(){return this.contactData},i.prototype._createConnectionAPI=function(e){return new connect.ConnectionSnapshot(e)};var s=function(e,t){this.contactId=e,this.connectionId=t,this._initMediaController()};s.prototype._getData=function(){return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(),this.getConnectionId())},s.prototype.getContactId=function(){return this.contactId},s.prototype.getConnectionId=function(){return this.connectionId},s.prototype.getEndpoint=function(){return new connect.Endpoint(this._getData().endpoint)},s.prototype.getAddress=s.prototype.getEndpoint,s.prototype.getState=function(){return this._getData().state},s.prototype.getStatus=s.prototype.getState,s.prototype.getStateDuration=function(){return connect.now()-this._getData().state.timestamp.getTime()+connect.core.getSkew()},s.prototype.getStatusDuration=s.prototype.getStateDuration,s.prototype.getType=function(){return this._getData().type},s.prototype.isInitialConnection=function(){return this._getData().initial},s.prototype.isActive=function(){return connect.contains(connect.CONNECTION_ACTIVE_STATES,this.getStatus().type)},s.prototype.isConnected=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTED},s.prototype.isConnecting=function(){return this.getStatus().type===connect.ConnectionStateType.CONNECTING},s.prototype.isOnHold=function(){return this.getStatus().type===connect.ConnectionStateType.HOLD},s.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},s.prototype.getMonitorInfo=function(){return this._getData().monitoringInfo},s.prototype.destroy=function(e){connect.core.getClient().call(connect.ClientMethods.DESTROY_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.sendDigits=function(e,t){connect.core.getClient().call(connect.ClientMethods.SEND_DIGITS,{contactId:this.getContactId(),connectionId:this.getConnectionId(),digits:e},t)},s.prototype.hold=function(e){connect.core.getClient().call(connect.ClientMethods.HOLD_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.resume=function(e){connect.core.getClient().call(connect.ClientMethods.RESUME_CONNECTION,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},s.prototype.toSnapshot=function(){return new connect.ConnectionSnapshot(this._getData())},s.prototype._initMediaController=function(){this.getMediaInfo()&&connect.core.mediaFactory.get(this).catch((function(){}))},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING},s.prototype._isAgentConnectionType=function(){var e=this.getType();return e===connect.ConnectionType.AGENT||e===connect.ConnectionType.MONITORING};var c=function(e){this.contactId=e};c.prototype.getSpeakerId=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){t.call(connect.AgentAppClientMethods.GET_CONTACT,{contactId:e.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),awsAccountId:connect.core.getAgentDataProvider().getAWSAccountId()},{success:function(e){if(e.contactData.customerId){var t={speakerId:e.contactData.customerId};connect.getLog().info("getSpeakerId succeeded").withObject(e).sendInternalLogToServer(),n(t)}else{var r=connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND,"No speakerId assotiated with this call");o(r)}},failure:function(e){connect.getLog().error("Get SpeakerId failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED,"Get SpeakerId failed",e);o(t)}})}))},c.prototype.getSpeakerStatus=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(e){t.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER,{SpeakerId:connect.assertNotNull(r.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("getSpeakerStatus succeeded").withObject(e).sendInternalLogToServer(),n(e)},failure:function(e){var t=JSON.parse(e);switch(t.status){case 400:case 404:var r=t;r.type=r.type?r.type:connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED,connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(),n(r);break;default:connect.getLog().error("getSpeakerStatus failed").withObject({err:e}).sendInternalLogToServer();var i=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED,"Get SpeakerStatus failed",e);o(i)}}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype._optOutSpeakerInLcms=function(e){var t=this,n=connect.core.getClient();return new Promise((function(o,r){n.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA,{ContactId:t.contactId,InstanceId:connect.core.getAgentDataProvider().getInstanceId(),AWSAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),CustomerId:connect.assertNotNull(e,"speakerId"),VoiceIdResult:{SpeakerOptedOut:!0}},{success:function(e){connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(e).sendInternalLogToServer(),o(e)},failure:function(e){connect.getLog().error("optOutSpeakerInLcms failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED,"optOutSpeakerInLcms failed",e);r(t)}})}))},c.prototype.optOutSpeaker=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(i){var s=r.speakerId;t.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER,{SpeakerId:connect.assertNotNull(s,"speakerId"),DomainId:i},{success:function(t){e._optOutSpeakerInLcms(s).catch((function(){})),connect.getLog().info("optOutSpeaker succeeded").withObject(t).sendInternalLogToServer(),n(t)},failure:function(e){connect.getLog().error("optOutSpeaker failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED,"optOutSpeaker failed.",e);o(t)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.deleteSpeaker=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getSpeakerId().then((function(r){e.getDomainId().then((function(e){t.call(connect.AgentAppClientMethods.DELETE_SPEAKER,{SpeakerId:connect.assertNotNull(r.speakerId,"speakerId"),DomainId:e},{success:function(e){connect.getLog().info("deleteSpeaker succeeded").withObject(e).sendInternalLogToServer(),n(e)},failure:function(e){connect.getLog().error("deleteSpeaker failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED,"deleteSpeaker failed.",e);o(t)}})})).catch((function(e){o(e)}))})).catch((function(e){o(e)}))}))},c.prototype.startSession=function(){var e=this;e.checkConferenceCall();var t=connect.core.getClient();return new Promise((function(n,o){e.getDomainId().then((function(r){t.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION,{contactId:e.contactId,instanceId:connect.core.getAgentDataProvider().getInstanceId(),customerAccountId:connect.core.getAgentDataProvider().getAWSAccountId(),clientToken:AWS.util.uuid.v4(),domainId:r},{success:function(e){if(e.sessionId)n(e);else{connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({data:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"No session id returned from start session api");o(t)}},failure:function(e){connect.getLog().error("startVoiceIdSession failed").withObject({err:e}).sendInternalLogToServer();var t=connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED,"startVoiceIdSession failed",e);o(t)}})})).catch((function(e){o(e)}))}))},c.prototype.evaluateSpeaker=function(e){var t=this;t.checkConferenceCall();var n=connect.core.getClient(),o=connect.core.getAgentDataProvider().getContactData(this.contactId),r=0;return new Promise((function(i,s){function c(){t.getDomainId().then((function(e){n.call(connect.AgentAppClientMethods.EVALUATE_SESSION,{SessionNameOrId:o.initialContactId||this.contactId,DomainId:e},{success:function(e){if(++r=1&&(o=n.IntegrationAssociationSummaryList[0].IntegrationArn.replace(/^.*domain\//i,"")),!o){connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer();var r=connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND);return void t(r)}connect.getLog().info("getDomainId succeeded").withObject(n).sendInternalLogToServer(),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.VoiceIdEvents.UPDATE_DOMAIN_ID,data:{domainId:o}}),e(o)}catch(e){connect.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer(),r=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e),t(r)}},failure:function(e){connect.getLog().error("getDomainId failed").withObject({err:e}).sendInternalLogToServer();var n=connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED,"getDomainId failed",e);t(n)}}):t(new Error("Agent doesn't have the permission for Voice ID"))}))},c.prototype.checkConferenceCall=function(){if(connect.core.getAgentDataProvider().getContactData(this.contactId).connections.filter((function(e){return connect.contains(connect.CONNECTION_ACTIVE_STATES,e.state.type)})).length>2)throw new connect.NotImplementedError("VoiceId is not supported for conference calls")},c.prototype.isAuthEnabled=function(e){return e!==connect.ContactFlowAuthenticationDecision.NOT_ENABLED},c.prototype.isAuthResultNotEnoughSpeech=function(e){return e===connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH},c.prototype.isAuthResultInconclusive=function(e){return e===connect.ContactFlowAuthenticationDecision.INCONCLUSIVE},c.prototype.isFraudEnabled=function(e){return e!==connect.ContactFlowFraudDetectionDecision.NOT_ENABLED},c.prototype.isFraudResultNotEnoughSpeech=function(e){return e===connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH},c.prototype.isFraudResultInconclusive=function(e){return e===connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE};var a=function(e,t){this._speakerAuthenticator=new c(e),s.call(this,e,t)};(a.prototype=Object.create(s.prototype)).constructor=a,a.prototype.getSoftphoneMediaInfo=function(){return this._getData().softphoneMediaInfo},a.prototype.getMediaInfo=function(){return this._getData().softphoneMediaInfo},a.prototype.getMediaType=function(){return connect.MediaType.SOFTPHONE},a.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)},a.prototype.getVoiceIdSpeakerId=function(){return this._speakerAuthenticator.getSpeakerId()},a.prototype.getVoiceIdSpeakerStatus=function(){return this._speakerAuthenticator.getSpeakerStatus()},a.prototype.optOutVoiceIdSpeaker=function(){return this._speakerAuthenticator.optOutSpeaker()},a.prototype.deleteVoiceIdSpeaker=function(){return this._speakerAuthenticator.deleteSpeaker()},a.prototype.evaluateSpeakerWithVoiceId=function(e){return this._speakerAuthenticator.evaluateSpeaker(e)},a.prototype.enrollSpeakerInVoiceId=function(){return this._speakerAuthenticator.enrollSpeaker()},a.prototype.updateVoiceIdSpeakerId=function(e){return this._speakerAuthenticator.updateSpeakerIdInVoiceId(e)},a.prototype.getQuickConnectName=function(){return this._getData().quickConnectName},a.prototype.isMute=function(){return this._getData().mute},a.prototype.muteParticipant=function(e){connect.core.getClient().call(connect.ClientMethods.MUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)},a.prototype.unmuteParticipant=function(e){connect.core.getClient().call(connect.ClientMethods.UNMUTE_PARTICIPANT,{contactId:this.getContactId(),connectionId:this.getConnectionId()},e)};var u=function(e,t){s.call(this,e,t)};(u.prototype=Object.create(s.prototype)).constructor=u,u.prototype.getMediaInfo=function(){var e=this._getData().chatMediaInfo;if(e){var t=connect.core.getAgentDataProvider().getContactData(this.contactId),n={contactId:this.contactId,initialContactId:t.initialContactId||this.contactId,participantId:this.connectionId,getConnectionToken:connect.hitch(this,this.getConnectionToken)};if(e.connectionData)try{n.participantToken=JSON.parse(e.connectionData).ConnectionAuthenticationToken}catch(t){connect.getLog().error(connect.LogComponent.CHAT,"Connection data is invalid").withObject(e).withException(t).sendInternalLogToServer(),n.participantToken=null}return n.participantToken=n.participantToken||null,n.originalInfo=this._getData().chatMediaInfo,n}return null},u.prototype.getConnectionToken=function(){client=connect.core.getClient();var e=connect.core.getAgentDataProvider().getContactData(this.contactId),t={transportType:connect.TRANSPORT_TYPES.CHAT_TOKEN,participantId:this.connectionId,contactId:e.initialContactId||this.contactId};return new Promise((function(e,n){client.call(connect.ClientMethods.CREATE_TRANSPORT,t,{success:function(t){connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(),e(t)},failure:function(e,t){connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({err:e,data:t}),n(Error("getConnectionToken failed"))}})}))},u.prototype.getMediaType=function(){return connect.MediaType.CHAT},u.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)},u.prototype._initMediaController=function(){this._isAgentConnectionType()&&connect.core.mediaFactory.get(this).catch((function(){}))};var l=function(e,t){s.call(this,e,t)};(l.prototype=Object.create(s.prototype)).constructor=l,l.prototype.getMediaType=function(){return connect.MediaType.TASK},l.prototype.getMediaInfo=function(){var e=connect.core.getAgentDataProvider().getContactData(this.contactId);return{contactId:this.contactId,initialContactId:e.initialContactId||this.contactId}},l.prototype.getMediaController=function(){return connect.core.mediaFactory.get(this)};var p=function(e){connect.Connection.call(this,e.contactId,e.connectionId),this.connectionData=e};(p.prototype=Object.create(s.prototype)).constructor=p,p.prototype._getData=function(){return this.connectionData},p.prototype._initMediaController=function(){};var h=function(e){var t=e||{};this.endpointARN=t.endpointId||t.endpointARN||null,this.endpointId=this.endpointARN,this.type=t.type||null,this.name=t.name||null,this.phoneNumber=t.phoneNumber||null,this.agentLogin=t.agentLogin||null,this.queue=t.queue||null};h.prototype.stripPhoneNumber=function(){return this.phoneNumber?this.phoneNumber.replace(/sip:([^@]*)@.*/,"$1"):""},h.byPhoneNumber=function(e,t){return new h({type:connect.EndpointType.PHONE_NUMBER,phoneNumber:e,name:t||null})};var d=function(e,t,n){this.errorType=e,this.errorMessage=t,this.endPointUrl=n};d.prototype.getErrorType=function(){return this.errorType},d.prototype.getErrorMessage=function(){return this.errorMessage},d.prototype.getEndPointUrl=function(){return this.endPointUrl},connect.agent=function(e){var t=connect.core.getEventBus().subscribe(connect.AgentEvents.INIT,e);return connect.agent.initialized&&e(new connect.Agent),t},connect.agent.initialized=!1,connect.contact=function(e){return connect.core.getEventBus().subscribe(connect.ContactEvents.INIT,e)},connect.onWebsocketInitFailure=function(e){var t=connect.core.getEventBus().subscribe(connect.WebSocketEvents.INIT_FAILURE,e);return connect.webSocketInitFailed&&e(),t},connect.ifMaster=function(e,t,n,o){if(connect.assertNotNull(e,"A topic must be provided."),connect.assertNotNull(t,"A true callback must be provided."),!connect.core.masterClient)return connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e).sendInternalLogToServer(),void(n&&n());connect.core.getMasterClient().call(connect.MasterMethods.CHECK_MASTER,{topic:e,shouldNotBecomeMasterIfNone:o},{success:function(e){e.isMaster?t():n&&n()}})},connect.becomeMaster=function(e,t,n){connect.assertNotNull(e,"A topic must be provided."),connect.core.masterClient?connect.core.getMasterClient().call(connect.MasterMethods.BECOME_MASTER,{topic:e},{success:function(){t&&t()}}):(connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!",e),n&&n())},connect.Agent=n,connect.AgentSnapshot=o,connect.Contact=r,connect.ContactSnapshot=i,connect.Connection=a,connect.BaseConnection=s,connect.VoiceConnection=a,connect.ChatConnection=u,connect.TaskConnection=l,connect.ConnectionSnapshot=p,connect.Endpoint=h,connect.Address=h,connect.SoftphoneError=d,connect.VoiceId=c}()},538:(e,t,n)=>{var o;function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}!function e(t,n,o){function r(s,c){if(!n[s]){if(!t[s]){if(i)return i(s,!0);var a=new Error("Cannot find module '"+s+"'");throw a.code="MODULE_NOT_FOUND",a}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return r(t[s][1][e]||e)}),u,u.exports,e,t,n,o)}return n[s].exports}for(var i=void 0,s=0;s-1});var r=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]","[object DataView]"];t.exports={isEmptyData:function(e){return"string"==typeof e?0===e.length:0===e.byteLength},convertToBuffer:function(e){return"string"==typeof e&&(e=new o(e,"utf8")),ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e)}}},{"buffer/":81}],12:[function(e,t,n){var o=e("./browserHashUtils");function r(e,t){this.hash=new e,this.outer=new e;var n=function(e,t){var n=o.convertToBuffer(t);if(n.byteLength>e.BLOCK_SIZE){var r=new e;r.update(n),n=r.digest()}var i=new Uint8Array(e.BLOCK_SIZE);return i.set(n),i}(e,t),r=new Uint8Array(e.BLOCK_SIZE);r.set(n);for(var i=0;i>>32-r)+n&4294967295}function a(e,t,n,o,r,i,s){return c(t&n|~t&o,e,t,r,i,s)}function u(e,t,n,o,r,i,s){return c(t&o|n&~o,e,t,r,i,s)}function l(e,t,n,o,r,i,s){return c(t^n^o,e,t,r,i,s)}function p(e,t,n,o,r,i,s){return c(n^(t|~o),e,t,r,i,s)}t.exports=s,s.BLOCK_SIZE=i,s.prototype.update=function(e){if(o.isEmptyData(e))return this;if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=o.convertToBuffer(e),n=0,r=t.byteLength;for(this.bytesHashed+=r;r>0;)this.buffer.setUint8(this.bufferLength++,t[n++]),r--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},s.prototype.digest=function(e){if(!this.finished){var t=this,n=t.buffer,o=t.bufferLength,s=8*t.bytesHashed;if(n.setUint8(this.bufferLength++,128),o%i>=56){for(var c=this.bufferLength;c>>0,!0),n.setUint32(60,Math.floor(s/4294967296),!0),this.hashBuffer(),this.finished=!0}var a=new DataView(new ArrayBuffer(16));for(c=0;c<4;c++)a.setUint32(4*c,this.state[c],!0);var u=new r(a.buffer,a.byteOffset,a.byteLength);return e?u.toString(e):u},s.prototype.hashBuffer=function(){var e=this.buffer,t=this.state,n=t[0],o=t[1],r=t[2],i=t[3];n=a(n,o,r,i,e.getUint32(0,!0),7,3614090360),i=a(i,n,o,r,e.getUint32(4,!0),12,3905402710),r=a(r,i,n,o,e.getUint32(8,!0),17,606105819),o=a(o,r,i,n,e.getUint32(12,!0),22,3250441966),n=a(n,o,r,i,e.getUint32(16,!0),7,4118548399),i=a(i,n,o,r,e.getUint32(20,!0),12,1200080426),r=a(r,i,n,o,e.getUint32(24,!0),17,2821735955),o=a(o,r,i,n,e.getUint32(28,!0),22,4249261313),n=a(n,o,r,i,e.getUint32(32,!0),7,1770035416),i=a(i,n,o,r,e.getUint32(36,!0),12,2336552879),r=a(r,i,n,o,e.getUint32(40,!0),17,4294925233),o=a(o,r,i,n,e.getUint32(44,!0),22,2304563134),n=a(n,o,r,i,e.getUint32(48,!0),7,1804603682),i=a(i,n,o,r,e.getUint32(52,!0),12,4254626195),r=a(r,i,n,o,e.getUint32(56,!0),17,2792965006),n=u(n,o=a(o,r,i,n,e.getUint32(60,!0),22,1236535329),r,i,e.getUint32(4,!0),5,4129170786),i=u(i,n,o,r,e.getUint32(24,!0),9,3225465664),r=u(r,i,n,o,e.getUint32(44,!0),14,643717713),o=u(o,r,i,n,e.getUint32(0,!0),20,3921069994),n=u(n,o,r,i,e.getUint32(20,!0),5,3593408605),i=u(i,n,o,r,e.getUint32(40,!0),9,38016083),r=u(r,i,n,o,e.getUint32(60,!0),14,3634488961),o=u(o,r,i,n,e.getUint32(16,!0),20,3889429448),n=u(n,o,r,i,e.getUint32(36,!0),5,568446438),i=u(i,n,o,r,e.getUint32(56,!0),9,3275163606),r=u(r,i,n,o,e.getUint32(12,!0),14,4107603335),o=u(o,r,i,n,e.getUint32(32,!0),20,1163531501),n=u(n,o,r,i,e.getUint32(52,!0),5,2850285829),i=u(i,n,o,r,e.getUint32(8,!0),9,4243563512),r=u(r,i,n,o,e.getUint32(28,!0),14,1735328473),n=l(n,o=u(o,r,i,n,e.getUint32(48,!0),20,2368359562),r,i,e.getUint32(20,!0),4,4294588738),i=l(i,n,o,r,e.getUint32(32,!0),11,2272392833),r=l(r,i,n,o,e.getUint32(44,!0),16,1839030562),o=l(o,r,i,n,e.getUint32(56,!0),23,4259657740),n=l(n,o,r,i,e.getUint32(4,!0),4,2763975236),i=l(i,n,o,r,e.getUint32(16,!0),11,1272893353),r=l(r,i,n,o,e.getUint32(28,!0),16,4139469664),o=l(o,r,i,n,e.getUint32(40,!0),23,3200236656),n=l(n,o,r,i,e.getUint32(52,!0),4,681279174),i=l(i,n,o,r,e.getUint32(0,!0),11,3936430074),r=l(r,i,n,o,e.getUint32(12,!0),16,3572445317),o=l(o,r,i,n,e.getUint32(24,!0),23,76029189),n=l(n,o,r,i,e.getUint32(36,!0),4,3654602809),i=l(i,n,o,r,e.getUint32(48,!0),11,3873151461),r=l(r,i,n,o,e.getUint32(60,!0),16,530742520),n=p(n,o=l(o,r,i,n,e.getUint32(8,!0),23,3299628645),r,i,e.getUint32(0,!0),6,4096336452),i=p(i,n,o,r,e.getUint32(28,!0),10,1126891415),r=p(r,i,n,o,e.getUint32(56,!0),15,2878612391),o=p(o,r,i,n,e.getUint32(20,!0),21,4237533241),n=p(n,o,r,i,e.getUint32(48,!0),6,1700485571),i=p(i,n,o,r,e.getUint32(12,!0),10,2399980690),r=p(r,i,n,o,e.getUint32(40,!0),15,4293915773),o=p(o,r,i,n,e.getUint32(4,!0),21,2240044497),n=p(n,o,r,i,e.getUint32(32,!0),6,1873313359),i=p(i,n,o,r,e.getUint32(60,!0),10,4264355552),r=p(r,i,n,o,e.getUint32(24,!0),15,2734768916),o=p(o,r,i,n,e.getUint32(52,!0),21,1309151649),n=p(n,o,r,i,e.getUint32(16,!0),6,4149444226),i=p(i,n,o,r,e.getUint32(44,!0),10,3174756917),r=p(r,i,n,o,e.getUint32(8,!0),15,718787259),o=p(o,r,i,n,e.getUint32(36,!0),21,3951481745),t[0]=n+t[0]&4294967295,t[1]=o+t[1]&4294967295,t[2]=r+t[2]&4294967295,t[3]=i+t[3]&4294967295}},{"./browserHashUtils":11,"buffer/":81}],14:[function(e,t,n){var o=e("buffer/").Buffer,r=e("./browserHashUtils");function i(){this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=new Uint32Array(80),this.offset=0,this.shift=24,this.totalLength=0}new Uint32Array([1518500249,1859775393,-1894007588,-899497514]),Math.pow(2,53),t.exports=i,i.BLOCK_SIZE=64,i.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(r.isEmptyData(e))return this;var t=(e=r.convertToBuffer(e)).length;this.totalLength+=8*t;for(var n=0;n14||14===this.offset&&this.shift<24)&&this.processBlock(),this.offset=14,this.shift=24,this.write(0),this.write(0),this.write(this.totalLength>0xffffffffff?this.totalLength/1099511627776:0),this.write(this.totalLength>4294967295?this.totalLength/4294967296:0);for(var t=24;t>=0;t-=8)this.write(this.totalLength>>t);var n=new o(20),r=new DataView(n.buffer);return r.setUint32(0,this.h0,!1),r.setUint32(4,this.h1,!1),r.setUint32(8,this.h2,!1),r.setUint32(12,this.h3,!1),r.setUint32(16,this.h4,!1),e?n.toString(e):n},i.prototype.processBlock=function(){for(var e=16;e<80;e++){var t=this.block[e-3]^this.block[e-8]^this.block[e-14]^this.block[e-16];this.block[e]=t<<1|t>>>31}var n,o,r=this.h0,i=this.h1,s=this.h2,c=this.h3,a=this.h4;for(e=0;e<80;e++){e<20?(n=c^i&(s^c),o=1518500249):e<40?(n=i^s^c,o=1859775393):e<60?(n=i&s|c&(i|s),o=2400959708):(n=i^s^c,o=3395469782);var u=(r<<5|r>>>27)+n+a+o+(0|this.block[e]);a=c,c=s,s=i<<30|i>>>2,i=r,r=u}for(this.h0=this.h0+r|0,this.h1=this.h1+i|0,this.h2=this.h2+s|0,this.h3=this.h3+c|0,this.h4=this.h4+a|0,this.offset=0,e=0;e<16;e++)this.block[e]=0}},{"./browserHashUtils":11,"buffer/":81}],15:[function(e,t,n){var o=e("buffer/").Buffer,r=e("./browserHashUtils"),i=64,s=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),c=Math.pow(2,53)-1;function a(){this.state=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}t.exports=a,a.BLOCK_SIZE=i,a.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");if(r.isEmptyData(e))return this;var t=0,n=(e=r.convertToBuffer(e)).byteLength;if(this.bytesHashed+=n,8*this.bytesHashed>c)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===i&&(this.hashBuffer(),this.bufferLength=0);return this},a.prototype.digest=function(e){if(!this.finished){var t=8*this.bytesHashed,n=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),r=this.bufferLength;if(n.setUint8(this.bufferLength++,128),r%i>=56){for(var s=this.bufferLength;s>>24&255,c[4*s+1]=this.state[s]>>>16&255,c[4*s+2]=this.state[s]>>>8&255,c[4*s+3]=this.state[s]>>>0&255;return e?c.toString(e):c},a.prototype.hashBuffer=function(){for(var e=this.buffer,t=this.state,n=t[0],o=t[1],r=t[2],c=t[3],a=t[4],u=t[5],l=t[6],p=t[7],h=0;h>>17|d<<15)^(d>>>19|d<<13)^d>>>10,g=((d=this.temp[h-15])>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;this.temp[h]=(f+this.temp[h-7]|0)+(g+this.temp[h-16]|0)}var m=(((a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7))+(a&u^~a&l)|0)+(p+(s[h]+this.temp[h]|0)|0)|0,v=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&o^n&r^o&r)|0;p=l,l=u,u=a,a=c+m|0,c=r,r=o,o=n,n=m+v|0}t[0]+=n,t[1]+=o,t[2]+=r,t[3]+=c,t[4]+=a,t[5]+=u,t[6]+=l,t[7]+=p}},{"./browserHashUtils":11,"buffer/":81}],16:[function(e,t,n){(function(n){(function(){var n=e("./util");n.crypto.lib=e("./browserCryptoLib"),n.Buffer=e("buffer/").Buffer,n.url=e("url/"),n.querystring=e("querystring/"),n.realClock=e("./realclock/browserClock"),n.environment="js",n.createEventStream=e("./event-stream/buffered-create-event-stream").createEventStream,n.isBrowser=function(){return!0},n.isNode=function(){return!1};var o=e("./core");if(t.exports=o,e("./credentials"),e("./credentials/credential_provider_chain"),e("./credentials/temporary_credentials"),e("./credentials/chainable_temporary_credentials"),e("./credentials/web_identity_credentials"),e("./credentials/cognito_identity_credentials"),e("./credentials/saml_credentials"),o.XML.Parser=e("./xml/browser_parser"),e("./http/xhr"),void 0===r)var r={browser:!0}}).call(this)}).call(this,e("_process"))},{"./browserCryptoLib":10,"./core":18,"./credentials":19,"./credentials/chainable_temporary_credentials":20,"./credentials/cognito_identity_credentials":21,"./credentials/credential_provider_chain":22,"./credentials/saml_credentials":23,"./credentials/temporary_credentials":24,"./credentials/web_identity_credentials":25,"./event-stream/buffered-create-event-stream":27,"./http/xhr":35,"./realclock/browserClock":52,"./util":71,"./xml/browser_parser":72,_process:86,"buffer/":81,"querystring/":92,"url/":94}],17:[function(e,t,n){var o,r=e("./core");e("./credentials"),e("./credentials/credential_provider_chain"),r.Config=r.util.inherit({constructor:function(e){void 0===e&&(e={}),e=this.extractCredentials(e),r.util.each.call(this,this.keys,(function(t,n){this.set(t,e[t],n)}))},getCredentials:function(e){var t,n=this;function o(t){e(t,t?null:n.credentials)}function i(e,t){return new r.util.error(t||new Error,{code:"CredentialsError",message:e,name:"CredentialsError"})}n.credentials?"function"==typeof n.credentials.get?n.credentials.get((function(e){e&&(e=i("Could not load credentials from "+n.credentials.constructor.name,e)),o(e)})):(t=null,n.credentials.accessKeyId&&n.credentials.secretAccessKey||(t=i("Missing credentials")),o(t)):n.credentialProvider?n.credentialProvider.resolve((function(e,t){e&&(e=i("Could not load credentials from any providers",e)),n.credentials=t,o(e)})):o(i("No credentials to load"))},update:function(e,t){t=t||!1,e=this.extractCredentials(e),r.util.each.call(this,e,(function(e,n){(t||Object.prototype.hasOwnProperty.call(this.keys,e)||r.Service.hasService(e))&&this.set(e,n)}))},loadFromPath:function(e){this.clear();var t=JSON.parse(r.util.readFileSync(e)),n=new r.FileSystemCredentials(e),o=new r.CredentialProviderChain;return o.providers.unshift(n),o.resolve((function(e,n){if(e)throw e;t.credentials=n})),this.constructor(t),this},clear:function(){r.util.each.call(this,this.keys,(function(e){delete this[e]})),this.set("credentials",void 0),this.set("credentialProvider",void 0)},set:function(e,t,n){void 0===t?(void 0===n&&(n=this.keys[e]),this[e]="function"==typeof n?n.call(this):n):"httpOptions"===e&&this[e]?this[e]=r.util.merge(this[e],t):this[e]=t},keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:void 0,httpOptions:{timeout:12e4},maxRetries:void 0,maxRedirects:10,paramValidation:!0,sslEnabled:!0,s3ForcePathStyle:!1,s3BucketEndpoint:!1,s3DisableBodySigning:!0,computeChecksums:!0,convertResponseTypes:!0,correctClockSkew:!1,customUserAgent:null,dynamoDbCrc32:!0,systemClockOffset:0,signatureVersion:null,signatureCache:!0,retryDelayOptions:{},useAccelerateEndpoint:!1,clientSideMonitoring:!1,endpointDiscoveryEnabled:!1,endpointCacheSize:1e3,hostPrefixEnabled:!0,stsRegionalEndpoints:null},extractCredentials:function(e){return e.accessKeyId&&e.secretAccessKey&&((e=r.util.copy(e)).credentials=new r.Credentials(e)),e},setPromisesDependency:function(e){o=e,null===e&&"function"==typeof Promise&&(o=Promise);var t=[r.Request,r.Credentials,r.CredentialProviderChain];r.S3&&(t.push(r.S3),r.S3.ManagedUpload&&t.push(r.S3.ManagedUpload)),r.util.addPromises(t,o)},getPromisesDependency:function(){return o}}),r.config=new r.Config},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(e,t,n){var o={util:e("./util")};({}).toString(),t.exports=o,o.util.update(o,{VERSION:"2.553.0",Signers:{},Protocol:{Json:e("./protocol/json"),Query:e("./protocol/query"),Rest:e("./protocol/rest"),RestJson:e("./protocol/rest_json"),RestXml:e("./protocol/rest_xml")},XML:{Builder:e("./xml/builder"),Parser:null},JSON:{Builder:e("./json/builder"),Parser:e("./json/parser")},Model:{Api:e("./model/api"),Operation:e("./model/operation"),Shape:e("./model/shape"),Paginator:e("./model/paginator"),ResourceWaiter:e("./model/resource_waiter")},apiLoader:e("./api_loader"),EndpointCache:e("../vendor/endpoint-cache").EndpointCache}),e("./sequential_executor"),e("./service"),e("./config"),e("./http"),e("./event_listeners"),e("./request"),e("./response"),e("./resource_waiter"),e("./signers/request_signer"),e("./param_validator"),o.events=new o.SequentialExecutor,o.util.memoizedProperty(o,"endpointCache",(function(){return new o.EndpointCache(o.config.endpointCacheSize)}),!0)},{"../vendor/endpoint-cache":103,"./api_loader":9,"./config":17,"./event_listeners":33,"./http":34,"./json/builder":36,"./json/parser":37,"./model/api":38,"./model/operation":40,"./model/paginator":41,"./model/resource_waiter":42,"./model/shape":43,"./param_validator":44,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./request":55,"./resource_waiter":56,"./response":57,"./sequential_executor":58,"./service":59,"./signers/request_signer":63,"./util":71,"./xml/builder":73}],19:[function(e,t,n){var o=e("./core");o.Credentials=o.util.inherit({constructor:function(){if(o.util.hideProperties(this,["secretAccessKey"]),this.expired=!1,this.expireTime=null,this.refreshCallbacks=[],1===arguments.length&&"object"===r(arguments[0])){var e=arguments[0].credentials||arguments[0];this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken}else this.accessKeyId=arguments[0],this.secretAccessKey=arguments[1],this.sessionToken=arguments[2]},expiryWindow:15,needsRefresh:function(){var e=o.util.date.getDate().getTime(),t=new Date(e+1e3*this.expiryWindow);return!!(this.expireTime&&t>this.expireTime)||this.expired||!this.accessKeyId||!this.secretAccessKey},get:function(e){var t=this;this.needsRefresh()?this.refresh((function(n){n||(t.expired=!1),e&&e(n)})):e&&e()},refresh:function(e){this.expired=!1,e()},coalesceRefresh:function(e,t){var n=this;1===n.refreshCallbacks.push(e)&&n.load((function(e){o.util.arrayEach(n.refreshCallbacks,(function(n){t?n(e):o.util.defer((function(){n(e)}))})),n.refreshCallbacks.length=0}))},load:function(e){e()}}),o.Credentials.addPromisesToClass=function(e){this.prototype.getPromise=o.util.promisifyMethod("get",e),this.prototype.refreshPromise=o.util.promisifyMethod("refresh",e)},o.Credentials.deletePromisesFromClass=function(){delete this.prototype.getPromise,delete this.prototype.refreshPromise},o.util.addPromises(o.Credentials)},{"./core":18}],20:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.ChainableTemporaryCredentials=o.util.inherit(o.Credentials,{constructor:function(e){o.Credentials.call(this),e=e||{},this.errorCode="ChainableTemporaryCredentialsProviderFailure",this.expired=!0,this.tokenCodeFn=null;var t=o.util.copy(e.params)||{};if(t.RoleArn&&(t.RoleSessionName=t.RoleSessionName||"temporary-credentials"),t.SerialNumber){if(!e.tokenCodeFn||"function"!=typeof e.tokenCodeFn)throw new o.util.error(new Error("tokenCodeFn must be a function when params.SerialNumber is given"),{code:this.errorCode});this.tokenCodeFn=e.tokenCodeFn}var n=o.util.merge({params:t,credentials:e.masterCredentials||o.config.credentials},e.stsConfig||{});this.service=new r(n)},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this,n=t.service.config.params.RoleArn?"assumeRole":"getSessionToken";this.getTokenCode((function(o,r){var i={};o?e(o):(r&&(i.TokenCode=r),t.service[n](i,(function(n,o){n||t.service.credentialsFrom(o,t),e(n)})))}))},getTokenCode:function(e){var t=this;this.tokenCodeFn?this.tokenCodeFn(this.service.config.params.SerialNumber,(function(n,r){if(n){var i=n;return n instanceof Error&&(i=n.message),void e(o.util.error(new Error("Error fetching MFA token: "+i),{code:t.errorCode}))}e(null,r)})):e(null)}})},{"../../clients/sts":8,"../core":18}],21:[function(e,t,n){var o=e("../core"),i=e("../../clients/cognitoidentity"),s=e("../../clients/sts");o.CognitoIdentityCredentials=o.util.inherit(o.Credentials,{localStorageKey:{id:"aws.cognito.identity-id.",providers:"aws.cognito.identity-providers."},constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.data=null,this._identityId=null,this._clientConfig=o.util.copy(t||{}),this.loadCachedId();var n=this;Object.defineProperty(this,"identityId",{get:function(){return n.loadCachedId(),n._identityId||n.params.IdentityId},set:function(e){n._identityId=e}})},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.data=null,t._identityId=null,t.getId((function(n){n?(t.clearIdOnNotAuthorized(n),e(n)):t.params.RoleArn?t.getCredentialsFromSTS(e):t.getCredentialsForIdentity(e)}))},clearCachedId:function(){this._identityId=null,delete this.params.IdentityId;var e=this.params.IdentityPoolId,t=this.params.LoginId||"";delete this.storage[this.localStorageKey.id+e+t],delete this.storage[this.localStorageKey.providers+e+t]},clearIdOnNotAuthorized:function(e){"NotAuthorizedException"==e.code&&this.clearCachedId()},getId:function(e){var t=this;if("string"==typeof t.params.IdentityId)return e(null,t.params.IdentityId);t.cognito.getId((function(n,o){!n&&o.IdentityId?(t.params.IdentityId=o.IdentityId,e(null,o.IdentityId)):e(n)}))},loadCredentials:function(e,t){e&&t&&(t.expired=!1,t.accessKeyId=e.Credentials.AccessKeyId,t.secretAccessKey=e.Credentials.SecretKey,t.sessionToken=e.Credentials.SessionToken,t.expireTime=e.Credentials.Expiration)},getCredentialsForIdentity:function(e){var t=this;t.cognito.getCredentialsForIdentity((function(n,o){n?t.clearIdOnNotAuthorized(n):(t.cacheId(o),t.data=o,t.loadCredentials(t.data,t)),e(n)}))},getCredentialsFromSTS:function(e){var t=this;t.cognito.getOpenIdToken((function(n,o){n?(t.clearIdOnNotAuthorized(n),e(n)):(t.cacheId(o),t.params.WebIdentityToken=o.Token,t.webIdentityCredentials.refresh((function(n){n||(t.data=t.webIdentityCredentials.data,t.sts.credentialsFrom(t.data,t)),e(n)})))}))},loadCachedId:function(){var e=this;if(o.util.isBrowser()&&!e.params.IdentityId){var t=e.getStorage("id");if(t&&e.params.Logins){var n=Object.keys(e.params.Logins);0!==(e.getStorage("providers")||"").split(",").filter((function(e){return-1!==n.indexOf(e)})).length&&(e.params.IdentityId=t)}else t&&(e.params.IdentityId=t)}},createClients:function(){var e=this._clientConfig;if(this.webIdentityCredentials=this.webIdentityCredentials||new o.WebIdentityCredentials(this.params,e),!this.cognito){var t=o.util.merge({},e);t.params=this.params,this.cognito=new i(t)}this.sts=this.sts||new s(e)},cacheId:function(e){this._identityId=e.IdentityId,this.params.IdentityId=this._identityId,o.util.isBrowser()&&(this.setStorage("id",e.IdentityId),this.params.Logins&&this.setStorage("providers",Object.keys(this.params.Logins).join(",")))},getStorage:function(e){return this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]},setStorage:function(e,t){try{this.storage[this.localStorageKey[e]+this.params.IdentityPoolId+(this.params.LoginId||"")]=t}catch(e){}},storage:function(){try{var e=o.util.isBrowser()&&null!==window.localStorage&&"object"===r(window.localStorage)?window.localStorage:{};return e["aws.test-storage"]="foobar",delete e["aws.test-storage"],e}catch(e){return{}}}()})},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(e,t,n){var o=e("../core");o.CredentialProviderChain=o.util.inherit(o.Credentials,{constructor:function(e){this.providers=e||o.CredentialProviderChain.defaultProviders.slice(0),this.resolveCallbacks=[]},resolve:function(e){var t=this;if(0===t.providers.length)return e(new Error("No providers")),t;if(1===t.resolveCallbacks.push(e)){var n=0,r=t.providers.slice(0);!function e(i,s){if(!i&&s||n===r.length)return o.util.arrayEach(t.resolveCallbacks,(function(e){e(i,s)})),void(t.resolveCallbacks.length=0);var c=r[n++];(s="function"==typeof c?c.call():c).get?s.get((function(t){e(t,t?null:s)})):e(null,s)}()}return t}}),o.CredentialProviderChain.defaultProviders=[],o.CredentialProviderChain.addPromisesToClass=function(e){this.prototype.resolvePromise=o.util.promisifyMethod("resolve",e)},o.CredentialProviderChain.deletePromisesFromClass=function(){delete this.prototype.resolvePromise},o.util.addPromises(o.CredentialProviderChain)},{"../core":18}],23:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.SAMLCredentials=o.util.inherit(o.Credentials,{constructor:function(e){o.Credentials.call(this),this.expired=!0,this.params=e},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithSAML((function(n,o){n||t.service.credentialsFrom(o,t),e(n)}))},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],24:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.TemporaryCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.Credentials.call(this),this.loadMasterCredentials(t),this.expired=!0,this.params=e||{},this.params.RoleArn&&(this.params.RoleSessionName=this.params.RoleSessionName||"temporary-credentials")},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.masterCredentials.get((function(){t.service.config.credentials=t.masterCredentials,(t.params.RoleArn?t.service.assumeRole:t.service.getSessionToken).call(t.service,(function(n,o){n||t.service.credentialsFrom(o,t),e(n)}))}))},loadMasterCredentials:function(e){for(this.masterCredentials=e||o.config.credentials;this.masterCredentials.masterCredentials;)this.masterCredentials=this.masterCredentials.masterCredentials;"function"!=typeof this.masterCredentials.get&&(this.masterCredentials=new o.Credentials(this.masterCredentials))},createClients:function(){this.service=this.service||new r({params:this.params})}})},{"../../clients/sts":8,"../core":18}],25:[function(e,t,n){var o=e("../core"),r=e("../../clients/sts");o.WebIdentityCredentials=o.util.inherit(o.Credentials,{constructor:function(e,t){o.Credentials.call(this),this.expired=!0,this.params=e,this.params.RoleSessionName=this.params.RoleSessionName||"web-identity",this.data=null,this._clientConfig=o.util.copy(t||{})},refresh:function(e){this.coalesceRefresh(e||o.util.fn.callback)},load:function(e){var t=this;t.createClients(),t.service.assumeRoleWithWebIdentity((function(n,o){t.data=null,n||(t.data=o,t.service.credentialsFrom(o,t)),e(n)}))},createClients:function(){if(!this.service){var e=o.util.merge({},this._clientConfig);e.params=this.params,this.service=new r(e)}}})},{"../../clients/sts":8,"../core":18}],26:[function(e,t,n){(function(n){(function(){var o=e("./core"),r=e("./util"),i=["AWS_ENABLE_ENDPOINT_DISCOVERY","AWS_ENDPOINT_DISCOVERY_ENABLED"];function s(e){var t=e.service,n=t.api||{},o=(n.operations,{});return t.config.region&&(o.region=t.config.region),n.serviceId&&(o.serviceId=n.serviceId),t.config.credentials.accessKeyId&&(o.accessKeyId=t.config.credentials.accessKeyId),o}function c(e,t,n){n&&null!=t&&"structure"===n.type&&n.required&&n.required.length>0&&r.arrayEach(n.required,(function(o){var r=n.members[o];if(!0===r.endpointDiscoveryId){var i=r.isLocationName?r.name:o;e[i]=String(t[o])}else c(e,t[o],r)}))}function a(e,t){var n={};return c(n,e.params,t),n}function u(e){var t=e.service,n=t.api,i=n.operations?n.operations[e.operation]:void 0,c=a(e,i?i.input:void 0),u=s(e);Object.keys(c).length>0&&(u=r.update(u,c),i&&(u.operation=i.name));var l=o.endpointCache.get(u);if(!l||1!==l.length||""!==l[0].Address)if(l&&l.length>0)e.httpRequest.updateEndpoint(l[0].Address);else{var p=t.makeRequest(n.endpointOperation,{Operation:i.name,Identifiers:c});h(p),p.removeListener("validate",o.EventListeners.Core.VALIDATE_PARAMETERS),p.removeListener("retry",o.EventListeners.Core.RETRY_CHECK),o.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}]),p.send((function(e,t){t&&t.Endpoints?o.endpointCache.put(u,t.Endpoints):e&&o.endpointCache.put(u,[{Address:"",CachePeriodInMinutes:1}])}))}}var l={};function p(e,t){var n=e.service,i=n.api,c=i.operations?i.operations[e.operation]:void 0,u=c?c.input:void 0,p=a(e,u),d=s(e);Object.keys(p).length>0&&(d=r.update(d,p),c&&(d.operation=c.name));var f=o.EndpointCache.getKeyString(d),g=o.endpointCache.get(f);if(g&&1===g.length&&""===g[0].Address)return l[f]||(l[f]=[]),void l[f].push({request:e,callback:t});if(g&&g.length>0)e.httpRequest.updateEndpoint(g[0].Address),t();else{var m=n.makeRequest(i.endpointOperation,{Operation:c.name,Identifiers:p});m.removeListener("validate",o.EventListeners.Core.VALIDATE_PARAMETERS),h(m),o.endpointCache.put(f,[{Address:"",CachePeriodInMinutes:60}]),m.send((function(n,i){if(n){var s={code:"EndpointDiscoveryException",message:"Request cannot be fulfilled without specifying an endpoint",retryable:!1};if(e.response.error=r.error(n,s),o.endpointCache.remove(d),l[f]){var c=l[f];r.arrayEach(c,(function(e){e.request.response.error=r.error(n,s),e.callback()})),delete l[f]}}else i&&(o.endpointCache.put(f,i.Endpoints),e.httpRequest.updateEndpoint(i.Endpoints[0].Address),l[f])&&(c=l[f],r.arrayEach(c,(function(e){e.request.httpRequest.updateEndpoint(i.Endpoints[0].Address),e.callback()})),delete l[f]);t()}))}}function h(e){var t=e.service.api.apiVersion;t&&!e.httpRequest.headers["x-amz-api-version"]&&(e.httpRequest.headers["x-amz-api-version"]=t)}function d(e){var t=e.error,n=e.httpResponse;if(t&&("InvalidEndpointException"===t.code||421===n.statusCode)){var i=e.request,c=i.service.api.operations||{},u=a(i,c[i.operation]?c[i.operation].input:void 0),l=s(i);Object.keys(u).length>0&&(l=r.update(l,u),c[i.operation]&&(l.operation=c[i.operation].name)),o.endpointCache.remove(l)}}function f(e){return["false","0"].indexOf(e)>=0}t.exports={discoverEndpoint:function(e,t){var s=e.service||{};if(function(e){if(e._originalConfig&&e._originalConfig.endpoint&&!0===e._originalConfig.endpointDiscoveryEnabled)throw r.error(new Error,{code:"ConfigurationException",message:"Custom endpoint is supplied; endpointDiscoveryEnabled must not be true."});var t=o.config[e.serviceIdentifier]||{};return Boolean(o.config.endpoint||t.endpoint||e._originalConfig&&e._originalConfig.endpoint)}(s)||e.isPresigned())return t();if(!function(e){if(!0===(e.service||{}).config.endpointDiscoveryEnabled)return!0;if(r.isBrowser())return!1;for(var t=0;t-1&&(e[t]++,0===e[t]);t--);}i.fromNumber=function(e){if(e>0x8000000000000000||e<-0x8000000000000000)throw new Error(e+" is too large (or, if negative, too small) to represent as an Int64");for(var t=new Uint8Array(8),n=7,o=Math.abs(Math.round(e));n>-1&&o>0;n--,o/=256)t[n]=o;return e<0&&s(t),new i(t)},i.prototype.valueOf=function(){var e=this.bytes.slice(0),t=128&e[0];return t&&s(e),parseInt(e.toString("hex"),16)*(t?-1:1)},i.prototype.toString=function(){return String(this.valueOf())},t.exports={Int64:i}},{"../core":18}],30:[function(e,t,n){var o=e("./parse-message").parseMessage;t.exports={parseEvent:function(e,t,n){var r=o(t),i=r.headers[":message-type"];if(i){if("error"===i.value)throw function(e){var t=e.headers[":error-code"],n=e.headers[":error-message"],o=new Error(n.value||n);return o.code=o.name=t.value||t,o}(r);if("event"!==i.value)return}var s=r.headers[":event-type"],c=n.members[s.value];if(c){var a={},u=c.eventPayloadMemberName;if(u){var l=c.members[u];"binary"===l.type?a[u]=r.body:a[u]=e.parse(r.body.toString(),l)}for(var p=c.eventHeaderMemberNames,h=0;h=0)return e.httpRequest.headers["X-Amz-Content-Sha256"]="UNSIGNED-PAYLOAD",t();o.util.computeSha256(i,(function(n,o){n?t(n):(e.httpRequest.headers["X-Amz-Content-Sha256"]=o,t())}))}else t()}})),e("SET_CONTENT_LENGTH","afterBuild",(function(e){var t=function(e){if(!e.service.api.operations)return"";var t=e.service.api.operations[e.operation];return t?t.authtype:""}(e),n=o.util.getRequestPayloadShape(e);if(void 0===e.httpRequest.headers["Content-Length"])try{var r=o.util.string.byteLength(e.httpRequest.body);e.httpRequest.headers["Content-Length"]=r}catch(o){if(n&&n.isStreaming){if(n.requiresLength)throw o;if(t.indexOf("unsigned-body")>=0)return void(e.httpRequest.headers["Transfer-Encoding"]="chunked");throw o}throw o}})),e("SET_HTTP_HOST","afterBuild",(function(e){e.httpRequest.headers.Host=e.httpRequest.endpoint.host})),e("RESTART","restart",(function(){var e=this.response.error;e&&e.retryable&&(this.httpRequest=new o.HttpRequest(this.service.endpoint,this.service.region),this.response.retryCount=600?this.emit("sign",[this],(function(e){e?t(e):i()})):i()})),e("HTTP_HEADERS","httpHeaders",(function(e,t,n,r){n.httpResponse.statusCode=e,n.httpResponse.statusMessage=r,n.httpResponse.headers=t,n.httpResponse.body=o.util.buffer.toBuffer(""),n.httpResponse.buffers=[],n.httpResponse.numBytes=0;var i=t.date||t.Date,s=n.request.service;if(i){var c=Date.parse(i);s.config.correctClockSkew&&s.isClockSkewed(c)&&s.applyClockOffset(c)}})),e("HTTP_DATA","httpData",(function(e,t){if(e){if(o.util.isNode()){t.httpResponse.numBytes+=e.length;var n=t.httpResponse.headers["content-length"],r={loaded:t.httpResponse.numBytes,total:n};t.request.emit("httpDownloadProgress",[r,t])}t.httpResponse.buffers.push(o.util.buffer.toBuffer(e))}})),e("HTTP_DONE","httpDone",(function(e){if(e.httpResponse.buffers&&e.httpResponse.buffers.length>0){var t=o.util.buffer.concat(e.httpResponse.buffers);e.httpResponse.body=t}delete e.httpResponse.numBytes,delete e.httpResponse.buffers})),e("FINALIZE_ERROR","retry",(function(e){e.httpResponse.statusCode&&(e.error.statusCode=e.httpResponse.statusCode,void 0===e.error.retryable&&(e.error.retryable=this.service.retryableError(e.error,this)))})),e("INVALIDATE_CREDENTIALS","retry",(function(e){if(e.error)switch(e.error.code){case"RequestExpired":case"ExpiredTokenException":case"ExpiredToken":e.error.retryable=!0,e.request.service.config.credentials.expired=!0}})),e("EXPIRED_SIGNATURE","retry",(function(e){var t=e.error;t&&"string"==typeof t.code&&"string"==typeof t.message&&t.code.match(/Signature/)&&t.message.match(/expired/)&&(e.error.retryable=!0)})),e("CLOCK_SKEWED","retry",(function(e){e.error&&this.service.clockSkewError(e.error)&&this.service.config.correctClockSkew&&(e.error.retryable=!0)})),e("REDIRECT","retry",(function(e){e.error&&e.error.statusCode>=300&&e.error.statusCode<400&&e.httpResponse.headers.location&&(this.httpRequest.endpoint=new o.Endpoint(e.httpResponse.headers.location),this.httpRequest.headers.Host=this.httpRequest.endpoint.host,e.error.redirect=!0,e.error.retryable=!0)})),e("RETRY_CHECK","retry",(function(e){e.error&&(e.error.redirect&&e.redirectCount=this.HEADERS_RECEIVED&&!h&&(u.statusCode=p.status,u.headers=c.parseHeaders(p.getAllResponseHeaders()),u.emit("headers",u.statusCode,u.headers,p.statusText),h=!0),this.readyState===this.DONE&&c.finishRequest(p,u)}),!1),p.upload.addEventListener("progress",(function(e){u.emit("sendProgress",e)})),p.addEventListener("progress",(function(e){u.emit("receiveProgress",e)}),!1),p.addEventListener("timeout",(function(){s(o.util.error(new Error("Timeout"),{code:"TimeoutError"}))}),!1),p.addEventListener("error",(function(){s(o.util.error(new Error("Network Failure"),{code:"NetworkingError"}))}),!1),p.addEventListener("abort",(function(){s(o.util.error(new Error("Request aborted"),{code:"RequestAbortedError"}))}),!1),n(u),p.open(e.method,l,!1!==t.xhrAsync),o.util.each(e.headers,(function(e,t){"Content-Length"!==e&&"User-Agent"!==e&&"Host"!==e&&p.setRequestHeader(e,t)})),t.timeout&&!1!==t.xhrAsync&&(p.timeout=t.timeout),t.xhrWithCredentials&&(p.withCredentials=!0);try{p.responseType="arraybuffer"}catch(e){}try{e.body?p.send(e.body):p.send()}catch(t){if(!e.body||"object"!==r(e.body.buffer))throw t;p.send(e.body.buffer)}return u},parseHeaders:function(e){var t={};return o.util.arrayEach(e.split(/\r?\n/),(function(e){var n=e.split(":",1)[0],o=e.substring(n.length+2);n.length>0&&(t[n.toLowerCase()]=o)})),t},finishRequest:function(e,t){var n;if("arraybuffer"===e.responseType&&e.response){var r=e.response;n=new o.util.Buffer(r.byteLength);for(var i=new Uint8Array(r),s=0;s-1?t||"":t,this.isJsonValue?JSON.parse(t):t&&"function"==typeof t.toString?t.toString():t},this.toWireFormat=function(e){return this.isJsonValue?JSON.stringify(e):e}}function f(){a.apply(this,arguments),this.toType=function(e){var t=i.base64.decode(e);if(this.isSensitive&&i.isNode()&&"function"==typeof i.Buffer.alloc){var n=i.Buffer.alloc(t.length,t);t.fill(0),t=n}return t},this.toWireFormat=i.base64.encode}function g(){f.apply(this,arguments)}function m(){a.apply(this,arguments),this.toType=function(e){return"boolean"==typeof e?e:null==e?null:"true"===e}}a.normalizedTypes={character:"string",double:"float",long:"integer",short:"integer",biginteger:"integer",bigdecimal:"float",blob:"binary"},a.types={structure:l,list:p,map:h,boolean:m,timestamp:function(e){var t=this;if(a.apply(this,arguments),e.timestampFormat)s(this,"timestampFormat",e.timestampFormat);else if(t.isTimestampFormatSet&&this.timestampFormat)s(this,"timestampFormat",this.timestampFormat);else if("header"===this.location)s(this,"timestampFormat","rfc822");else if("querystring"===this.location)s(this,"timestampFormat","iso8601");else if(this.api)switch(this.api.protocol){case"json":case"rest-json":s(this,"timestampFormat","unixTimestamp");break;case"rest-xml":case"query":case"ec2":s(this,"timestampFormat","iso8601")}this.toType=function(e){return null==e?null:"function"==typeof e.toUTCString?e:"string"==typeof e||"number"==typeof e?i.date.parseTimestamp(e):null},this.toWireFormat=function(e){return i.date.format(e,t.timestampFormat)}},float:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseFloat(e)},this.toWireFormat=this.toType},integer:function(){a.apply(this,arguments),this.toType=function(e){return null==e?null:parseInt(e,10)},this.toWireFormat=this.toType},string:d,base64:g,binary:f},a.resolve=function(e,t){if(e.shape){var n=t.api.shapes[e.shape];if(!n)throw new Error("Cannot find shape reference: "+e.shape);return n}return null},a.create=function(e,t,n){if(e.isShape)return e;var o=a.resolve(e,t);if(o){var r=Object.keys(e);t.documentation||(r=r.filter((function(e){return!e.match(/documentation/)})));var i=function(){o.constructor.call(this,e,t,n)};return i.prototype=o,new i}e.type||(e.members?e.type="structure":e.member?e.type="list":e.key?e.type="map":e.type="string");var s=e.type;if(a.normalizedTypes[e.type]&&(e.type=a.normalizedTypes[e.type]),a.types[e.type])return new a.types[e.type](e,t,n);throw new Error("Unrecognized shape type: "+s)},a.shapes={StructureShape:l,ListShape:p,MapShape:h,StringShape:d,BooleanShape:m,Base64Shape:g},t.exports=a},{"../util":71,"./collection":39}],44:[function(e,t,n){var o=e("./core");o.ParamValidator=o.util.inherit({constructor:function(e){!0!==e&&void 0!==e||(e={min:!0}),this.validation=e},validate:function(e,t,n){if(this.errors=[],this.validateMember(e,t||{},n||"params"),this.errors.length>1){var r=this.errors.join("\n* ");throw r="There were "+this.errors.length+" validation errors:\n* "+r,o.util.error(new Error(r),{code:"MultipleValidationErrors",errors:this.errors})}if(1===this.errors.length)throw this.errors[0];return!0},fail:function(e,t){this.errors.push(o.util.error(new Error(t),{code:e}))},validateStructure:function(e,t,n){var o;this.validateType(t,n,["object"],"structure");for(var r=0;e.required&&r= 1, but found "'+t+'" for '+n)},validatePattern:function(e,t,n){this.validation.pattern&&void 0!==e.pattern&&(new RegExp(e.pattern).test(t)||this.fail("PatternMatchError",'Provided value "'+t+'" does not match regex pattern /'+e.pattern+"/ for "+n))},validateRange:function(e,t,n,o){this.validation.min&&void 0!==e.min&&t= "+e.min+", but found "+t+" for "+n),this.validation.max&&void 0!==e.max&&t>e.max&&this.fail("MaxRangeError","Expected "+o+" <= "+e.max+", but found "+t+" for "+n)},validateEnum:function(e,t,n){this.validation.enum&&void 0!==e.enum&&-1===e.enum.indexOf(t)&&this.fail("EnumError","Found string value of "+t+", but expected "+e.enum.join("|")+" for "+n)},validateType:function(e,t,n,i){if(null==e)return!1;for(var s=!1,c=0;c63)throw o.error(new Error,{code:"ValidationError",message:"Hostname label length should be between 1 to 63 characters, inclusive."});if(!i.test(e))throw r.util.error(new Error,{code:"ValidationError",message:e+" is not hostname compatible."})}))}return e}}},{"../core":18,"../util":71}],46:[function(e,t,n){var o=e("../util"),r=e("../json/builder"),i=e("../json/parser"),s=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.httpRequest,n=e.service.api,o=n.targetPrefix+"."+n.operations[e.operation].name,i=n.jsonVersion||"1.0",c=n.operations[e.operation].input,a=new r;1===i&&(i="1.0"),t.body=a.build(e.params||{},c),t.headers["Content-Type"]="application/x-amz-json-"+i,t.headers["X-Amz-Target"]=o,s(e)},extractError:function(e){var t={},n=e.httpResponse;if(t.code=n.headers["x-amzn-errortype"]||"UnknownError","string"==typeof t.code&&(t.code=t.code.split(":")[0]),n.body.length>0)try{var r=JSON.parse(n.body.toString());(r.__type||r.code)&&(t.code=(r.__type||r.code).split("#").pop()),"RequestEntityTooLarge"===t.code?t.message="Request body must be less than 1 MB":t.message=r.message||r.Message||null}catch(r){t.statusCode=n.statusCode,t.message=n.statusMessage}else t.statusCode=n.statusCode,t.message=n.statusCode.toString();e.error=o.error(new Error,t)},extractData:function(e){var t=e.httpResponse.body.toString()||"{}";if(!1===e.request.service.config.convertResponseTypes)e.data=JSON.parse(t);else{var n=e.request.service.api.operations[e.request.operation].output||{},o=new i;e.data=o.parse(t,n)}}}},{"../json/builder":36,"../json/parser":37,"../util":71,"./helpers":45}],47:[function(e,t,n){var o=e("../core"),r=e("../util"),i=e("../query/query_param_serializer"),s=e("../model/shape"),c=e("./helpers").populateHostPrefix;t.exports={buildRequest:function(e){var t=e.service.api.operations[e.operation],n=e.httpRequest;n.headers["Content-Type"]="application/x-www-form-urlencoded; charset=utf-8",n.params={Version:e.service.api.apiVersion,Action:t.name},(new i).serialize(e.params,t.input,(function(e,t){n.params[e]=t})),n.body=r.queryParamsToString(n.params),c(e)},extractError:function(e){var t,n=e.httpResponse.body.toString();if(n.match("=0?"&":"?";var a=[];o.arrayEach(Object.keys(s).sort(),(function(e){Array.isArray(s[e])||(s[e]=[s[e]]);for(var t=0;t0){var p=(t=new o.XML.Parser).parse(s.toString(),a);r.update(e.data,p)}}}},{"../core":18,"../util":71,"./rest":48}],51:[function(e,t,n){var o=e("../util");function r(){}function i(e){return e.isQueryName||"ec2"!==e.api.protocol?e.name:e.name[0].toUpperCase()+e.name.substr(1)}function s(e,t,n,r){o.each(n.members,(function(n,o){var s=t[n];if(null!=s){var a=i(o);c(a=e?e+"."+a:a,s,o,r)}}))}function c(e,t,n,r){null!=t&&("structure"===n.type?s(e,t,n,r):"list"===n.type?function(e,t,n,r){var s=n.member||{};0!==t.length?o.arrayEach(t,(function(t,o){var a="."+(o+1);if("ec2"===n.api.protocol)a+="";else if(n.flattened){if(s.name){var u=e.split(".");u.pop(),u.push(i(s)),e=u.join(".")}}else a="."+(s.name?s.name:"member")+a;c(e+a,t,s,r)})):r.call(this,e,null)}(e,t,n,r):"map"===n.type?function(e,t,n,r){var i=1;o.each(t,(function(t,o){var s=(n.flattened?".":".entry.")+i+++".",a=s+(n.key.name||"key"),u=s+(n.value.name||"value");c(e+a,t,n.key,r),c(e+u,o,n.value,r)}))}(e,t,n,r):r(e,n.toWireFormat(t).toString()))}r.prototype.serialize=function(e,t,n){s("",e,t,n)},t.exports=r},{"../util":71}],52:[function(e,t,n){t.exports={now:function(){return"undefined"!=typeof performance&&"function"==typeof performance.now?performance.now():Date.now()}}},{}],53:[function(e,t,n){var o=e("./util"),r=e("./region_config_data.json");function i(e,t){o.each(t,(function(t,n){"globalEndpoint"!==t&&(void 0!==e.config[t]&&null!==e.config[t]||(e.config[t]=n))}))}t.exports=function(e){for(var t=function(e){var t=e.config.region,n=function(e){if(!e)return null;var t=e.split("-");return t.length<3?null:t.slice(0,t.length-2).join("-")+"-*"}(t),o=e.api.endpointPrefix;return[[t,o],[n,o],[t,"*"],[n,"*"],["*",o],["*","*"]].map((function(e){return e[0]&&e[1]?e.join("/"):null}))}(e),n=0;n=0){a=!0;var u=0}var l=function(){a&&u!==c?r.emit("error",n.util.error(new Error("Stream content length mismatch. Received "+u+" of "+c+" bytes."),{code:"StreamContentLengthMismatch"})):2===n.HttpClient.streamsApiVersion?r.end():r.emit("end")},p=s.httpResponse.createUnbufferedStream();if(2===n.HttpClient.streamsApiVersion)if(a){var h=new e.PassThrough;h._write=function(t){return t&&t.length&&(u+=t.length),e.PassThrough.prototype._write.apply(this,arguments)},h.on("end",l),r.on("error",(function(e){a=!1,p.unpipe(h),h.emit("end"),h.end()})),p.pipe(h).pipe(r,{end:!1})}else p.pipe(r);else a&&p.on("data",(function(e){e&&e.length&&(u+=e.length)})),p.on("data",(function(e){r.emit("data",e)})),p.on("end",l);p.on("error",(function(e){a=!1,r.emit("error",e)}))}})),r},emitEvent:function(e,t,o){"function"==typeof t&&(o=t,t=null),o||(o=function(){}),t||(t=this.eventParameters(e,this.response)),n.SequentialExecutor.prototype.emit.call(this,e,t,(function(e){e&&(this.response.error=e),o.call(this,e)}))},eventParameters:function(e){switch(e){case"restart":case"validate":case"sign":case"build":case"afterValidate":case"afterBuild":return[this];case"error":return[this.response.error,this.response];default:return[this.response]}},presign:function(e,t){return t||"function"!=typeof e||(t=e,e=null),(new n.Signers.Presign).sign(this.toGet(),e,t)},isPresigned:function(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,"presigned-expires")},toUnauthenticated:function(){return this._unAuthenticated=!0,this.removeListener("validate",n.EventListeners.Core.VALIDATE_CREDENTIALS),this.removeListener("sign",n.EventListeners.Core.SIGN),this},toGet:function(){return"query"!==this.service.api.protocol&&"ec2"!==this.service.api.protocol||(this.removeListener("build",this.buildAsGet),this.addListener("build",this.buildAsGet)),this},buildAsGet:function(e){e.httpRequest.method="GET",e.httpRequest.path=e.service.endpoint.path+"?"+e.httpRequest.body,e.httpRequest.body="",delete e.httpRequest.headers["Content-Length"],delete e.httpRequest.headers["Content-Type"]},haltHandlersOnError:function(){this._haltHandlersOnError=!0}}),n.Request.addPromisesToClass=function(e){this.prototype.promise=function(){var t=this;return this.httpRequest.appendToUserAgent("promise"),new e((function(e,n){t.on("complete",(function(t){t.error?n(t.error):e(Object.defineProperty(t.data||{},"$response",{value:t}))})),t.runTo()}))}},n.Request.deletePromisesFromClass=function(){delete this.prototype.promise},n.util.addPromises(n.Request),n.util.mixin(n.Request,n.SequentialExecutor)}).call(this)}).call(this,e("_process"))},{"./core":18,"./state_machine":70,_process:86,jmespath:85}],56:[function(e,t,n){var o=e("./core"),r=o.util.inherit,i=e("jmespath");function s(e){var t=e.request._waiter,n=t.config.acceptors,o=!1,r="retry";n.forEach((function(n){if(!o){var i=t.matchers[n.matcher];i&&i(e,n.expected,n.argument)&&(o=!0,r=n.state)}})),!o&&e.error&&(r="failure"),"success"===r?t.setSuccess(e):t.setError(e,"retry"===r)}o.ResourceWaiter=r({constructor:function(e,t){this.service=e,this.state=t,this.loadWaiterConfig(this.state)},service:null,state:null,config:null,matchers:{path:function(e,t,n){try{var o=i.search(e.data,n)}catch(e){return!1}return i.strictDeepEqual(o,t)},pathAll:function(e,t,n){try{var o=i.search(e.data,n)}catch(e){return!1}Array.isArray(o)||(o=[o]);var r=o.length;if(!r)return!1;for(var s=0;s-1&&n.splice(r,1)}return this},removeAllListeners:function(e){return e?delete this._events[e]:this._events={},this},emit:function(e,t,n){n||(n=function(){});var o=this.listeners(e),r=o.length;return this.callListeners(o,t,n),r>0},callListeners:function(e,t,n,r){var i=this,s=r||null;function c(r){if(r&&(s=o.util.error(s||new Error,r),i._haltHandlersOnError))return n.call(i,s);i.callListeners(e,t,n,s)}for(;e.length>0;){var a=e.shift();if(a._isAsync)return void a.apply(i,t.concat([c]));try{a.apply(i,t)}catch(e){s=o.util.error(s||new Error,e)}if(s&&i._haltHandlersOnError)return void n.call(i,s)}n.call(i,s)},addListeners:function(e){var t=this;return e._events&&(e=e._events),o.util.each(e,(function(e,n){"function"==typeof n&&(n=[n]),o.util.arrayEach(n,(function(n){t.on(e,n)}))})),t},addNamedListener:function(e,t,n,o){return this[e]=n,this.addListener(t,n,o),this},addNamedAsyncListener:function(e,t,n,o){return n._isAsync=!0,this.addNamedListener(e,t,n,o)},addNamedListeners:function(e){var t=this;return e((function(){t.addNamedListener.apply(t,arguments)}),(function(){t.addNamedAsyncListener.apply(t,arguments)})),this}}),o.SequentialExecutor.prototype.addListener=o.SequentialExecutor.prototype.on,t.exports=o.SequentialExecutor},{"./core":18}],59:[function(e,t,n){(function(n){(function(){var o=e("./core"),i=e("./model/api"),s=e("./region_config"),c=o.util.inherit,a=0;o.Service=c({constructor:function(e){if(!this.loadServiceClass)throw o.util.error(new Error,"Service must be constructed with `new' operator");var t=this.loadServiceClass(e||{});if(t){var n=o.util.copy(e),r=new t(e);return Object.defineProperty(r,"_originalConfig",{get:function(){return n},enumerable:!1,configurable:!0}),r._clientId=++a,r}this.initialize(e)},initialize:function(e){var t=o.config[this.serviceIdentifier];if(this.config=new o.Config(o.config),t&&this.config.update(t,!0),e&&this.config.update(e,!0),this.validateService(),this.config.endpoint||s(this),this.config.endpoint=this.endpointFromTemplate(this.config.endpoint),this.setEndpoint(this.config.endpoint),o.SequentialExecutor.call(this),o.Service.addDefaultMonitoringListeners(this),(this.config.clientSideMonitoring||o.Service._clientSideMonitoring)&&this.publisher){var r=this.publisher;this.addNamedListener("PUBLISH_API_CALL","apiCall",(function(e){n.nextTick((function(){r.eventHandler(e)}))})),this.addNamedListener("PUBLISH_API_ATTEMPT","apiCallAttempt",(function(e){n.nextTick((function(){r.eventHandler(e)}))}))}},validateService:function(){},loadServiceClass:function(e){var t=e;if(o.util.isEmpty(this.api)){if(t.apiConfig)return o.Service.defineServiceApi(this.constructor,t.apiConfig);if(this.constructor.services){(t=new o.Config(o.config)).update(e,!0);var n=t.apiVersions[this.constructor.serviceIdentifier];return n=n||t.apiVersion,this.getLatestServiceClass(n)}return null}return null},getLatestServiceClass:function(e){return e=this.getLatestServiceVersion(e),null===this.constructor.services[e]&&o.Service.defineServiceApi(this.constructor,e),this.constructor.services[e]},getLatestServiceVersion:function(e){if(!this.constructor.services||0===this.constructor.services.length)throw new Error("No services defined on "+this.constructor.serviceIdentifier);if(e?o.util.isType(e,Date)&&(e=o.util.date.iso8601(e).split("T")[0]):e="latest",Object.hasOwnProperty(this.constructor.services,e))return e;for(var t=Object.keys(this.constructor.services).sort(),n=null,r=t.length-1;r>=0;r--)if("*"!==t[r][t[r].length-1]&&(n=t[r]),t[r].substr(0,10)<=e)return n;throw new Error("Could not find "+this.constructor.serviceIdentifier+" API to satisfy version constraint `"+e+"'")},api:{},defaultRetryCount:3,customizeRequests:function(e){if(e){if("function"!=typeof e)throw new Error("Invalid callback type '"+r(e)+"' provided in customizeRequests");this.customRequestHandler=e}else this.customRequestHandler=null},makeRequest:function(e,t,n){if("function"==typeof t&&(n=t,t=null),t=t||{},this.config.params){var r=this.api.operations[e];r&&(t=o.util.copy(t),o.util.each(this.config.params,(function(e,n){r.input.members[e]&&(void 0!==t[e]&&null!==t[e]||(t[e]=n))})))}var i=new o.Request(this,e,t);return this.addAllRequestListeners(i),this.attachMonitoringEmitter(i),n&&i.send(n),i},makeUnauthenticatedRequest:function(e,t,n){"function"==typeof t&&(n=t,t={});var o=this.makeRequest(e,t).toUnauthenticated();return n?o.send(n):o},waitFor:function(e,t,n){return new o.ResourceWaiter(this,e).wait(t,n)},addAllRequestListeners:function(e){for(var t=[o.events,o.EventListeners.Core,this.serviceInterface(),o.EventListeners.CorePost],n=0;n299?(r.code&&(n.FinalAwsException=r.code),r.message&&(n.FinalAwsExceptionMessage=r.message)):((r.code||r.name)&&(n.FinalSdkException=r.code||r.name),r.message&&(n.FinalSdkExceptionMessage=r.message))}return n},apiAttemptEvent:function(e){var t=e.service.api.operations[e.operation],n={Type:"ApiCallAttempt",Api:t?t.name:e.operation,Version:1,Service:e.service.api.serviceId||e.service.api.endpointPrefix,Fqdn:e.httpRequest.endpoint.hostname,UserAgent:e.httpRequest.getUserAgent()},o=e.response;return o.httpResponse.statusCode&&(n.HttpStatusCode=o.httpResponse.statusCode),!e._unAuthenticated&&e.service.config.credentials&&e.service.config.credentials.accessKeyId&&(n.AccessKey=e.service.config.credentials.accessKeyId),o.httpResponse.headers?(e.httpRequest.headers["x-amz-security-token"]&&(n.SessionToken=e.httpRequest.headers["x-amz-security-token"]),o.httpResponse.headers["x-amzn-requestid"]&&(n.XAmznRequestId=o.httpResponse.headers["x-amzn-requestid"]),o.httpResponse.headers["x-amz-request-id"]&&(n.XAmzRequestId=o.httpResponse.headers["x-amz-request-id"]),o.httpResponse.headers["x-amz-id-2"]&&(n.XAmzId2=o.httpResponse.headers["x-amz-id-2"]),n):n},attemptFailEvent:function(e){var t=this.apiAttemptEvent(e),n=e.response,o=n.error;return n.httpResponse.statusCode>299?(o.code&&(t.AwsException=o.code),o.message&&(t.AwsExceptionMessage=o.message)):((o.code||o.name)&&(t.SdkException=o.code||o.name),o.message&&(t.SdkExceptionMessage=o.message)),t},attachMonitoringEmitter:function(e){var t,n,r,i,s,c,a=0,u=this;e.on("validate",(function(){i=o.util.realClock.now(),c=Date.now()}),!0),e.on("sign",(function(){n=o.util.realClock.now(),t=Date.now(),s=e.httpRequest.region,a++}),!0),e.on("validateResponse",(function(){r=Math.round(o.util.realClock.now()-n)})),e.addNamedListener("API_CALL_ATTEMPT","success",(function(){var n=u.apiAttemptEvent(e);n.Timestamp=t,n.AttemptLatency=r>=0?r:0,n.Region=s,u.emit("apiCallAttempt",[n])})),e.addNamedListener("API_CALL_ATTEMPT_RETRY","retry",(function(){var i=u.attemptFailEvent(e);i.Timestamp=t,r=r||Math.round(o.util.realClock.now()-n),i.AttemptLatency=r>=0?r:0,i.Region=s,u.emit("apiCallAttempt",[i])})),e.addNamedListener("API_CALL","complete",(function(){var t=u.apiCallEvent(e);if(t.AttemptCount=a,!(t.AttemptCount<=0)){t.Timestamp=c;var n=Math.round(o.util.realClock.now()-i);t.Latency=n>=0?n:0;var r=e.response;"number"==typeof r.retryCount&&"number"==typeof r.maxRetries&&r.retryCount>=r.maxRetries&&(t.MaxRetriesExceeded=1),u.emit("apiCall",[t])}}))},setupRequestListeners:function(e){},getSignerClass:function(e){var t,n=null,r="";return e&&(r=(n=(e.service.api.operations||{})[e.operation]||null)?n.authtype:""),t=this.config.signatureVersion?this.config.signatureVersion:"v4"===r||"v4-unsigned-body"===r?"v4":this.api.signatureVersion,o.Signers.RequestSigner.getVersion(t)},serviceInterface:function(){switch(this.api.protocol){case"ec2":case"query":return o.EventListeners.Query;case"json":return o.EventListeners.Json;case"rest-json":return o.EventListeners.RestJson;case"rest-xml":return o.EventListeners.RestXml}if(this.api.protocol)throw new Error("Invalid service `protocol' "+this.api.protocol+" in API config")},successfulResponse:function(e){return e.httpResponse.statusCode<300},numRetries:function(){return void 0!==this.config.maxRetries?this.config.maxRetries:this.defaultRetryCount},retryDelays:function(e){return o.util.calculateRetryDelay(e,this.config.retryDelayOptions)},retryableError:function(e){return!!this.timeoutError(e)||!!this.networkingError(e)||!!this.expiredCredentialsError(e)||!!this.throttledError(e)||e.statusCode>=500},networkingError:function(e){return"NetworkingError"===e.code},timeoutError:function(e){return"TimeoutError"===e.code},expiredCredentialsError:function(e){return"ExpiredTokenException"===e.code},clockSkewError:function(e){switch(e.code){case"RequestTimeTooSkewed":case"RequestExpired":case"InvalidSignatureException":case"SignatureDoesNotMatch":case"AuthFailure":case"RequestInTheFuture":return!0;default:return!1}},getSkewCorrectedDate:function(){return new Date(Date.now()+this.config.systemClockOffset)},applyClockOffset:function(e){e&&(this.config.systemClockOffset=e-Date.now())},isClockSkewed:function(e){if(e)return Math.abs(this.getSkewCorrectedDate().getTime()-e)>=3e4},throttledError:function(e){if(429===e.statusCode)return!0;switch(e.code){case"ProvisionedThroughputExceededException":case"Throttling":case"ThrottlingException":case"RequestLimitExceeded":case"RequestThrottled":case"RequestThrottledException":case"TooManyRequestsException":case"TransactionInProgressException":return!0;default:return!1}},endpointFromTemplate:function(e){if("string"!=typeof e)return e;var t=e;return t=(t=(t=t.replace(/\{service\}/g,this.api.endpointPrefix)).replace(/\{region\}/g,this.config.region)).replace(/\{scheme\}/g,this.config.sslEnabled?"https":"http")},setEndpoint:function(e){this.endpoint=new o.Endpoint(e,this.config)},paginationConfig:function(e,t){var n=this.api.operations[e].paginator;if(!n){if(t){var r=new Error;throw o.util.error(r,"No pagination configuration for "+e)}return null}return n}}),o.util.update(o.Service,{defineMethods:function(e){o.util.each(e.prototype.api.operations,(function(t){e.prototype[t]||("none"===e.prototype.api.operations[t].authtype?e.prototype[t]=function(e,n){return this.makeUnauthenticatedRequest(t,e,n)}:e.prototype[t]=function(e,n){return this.makeRequest(t,e,n)})}))},defineService:function(e,t,n){o.Service._serviceMap[e]=!0,Array.isArray(t)||(n=t,t=[]);var r=c(o.Service,n||{});if("string"==typeof e){o.Service.addVersions(r,t);var i=r.serviceIdentifier||e;r.serviceIdentifier=i}else r.prototype.api=e,o.Service.defineMethods(r);if(o.SequentialExecutor.call(this.prototype),!this.prototype.publisher&&o.util.clientSideMonitoring){var s=o.util.clientSideMonitoring.Publisher,a=(0,o.util.clientSideMonitoring.configProvider)();this.prototype.publisher=new s(a),a.enabled&&(o.Service._clientSideMonitoring=!0)}return o.SequentialExecutor.call(r.prototype),o.Service.addDefaultMonitoringListeners(r.prototype),r},addVersions:function(e,t){Array.isArray(t)||(t=[t]),e.services=e.services||{};for(var n=0;n=0))throw n.util.error(new Error,t);this.config.stsRegionalEndpoints=e.toLowerCase()},validateRegionalEndpointsFlag:function(){var e=this.config;if(e.stsRegionalEndpoints&&this.validateRegionalEndpointsFlagValue(e.stsRegionalEndpoints,{code:"InvalidConfiguration",message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" or "regional". Got "'+e.stsRegionalEndpoints+'".'}),n.util.isNode()){if(Object.prototype.hasOwnProperty.call(t.env,r)){var o=t.env[r];this.validateRegionalEndpointsFlagValue(o,{code:"InvalidEnvironmentalVariable",message:"invalid "+r+' environmental variable. Expect "legacy" or "regional". Got "'+t.env[r]+'".'})}var s={};try{s=n.util.getProfilesFromSharedConfig(n.util.iniLoader)[t.env.AWS_PROFILE||n.util.defaultProfile]}catch(e){}if(s&&Object.prototype.hasOwnProperty.call(s,i)){var c=s[i];this.validateRegionalEndpointsFlagValue(c,{code:"InvalidConfiguration",message:"invalid "+i+' profile config. Expect "legacy" or "regional". Got "'+s[i]+'".'})}}},optInRegionalEndpoint:function(){this.validateRegionalEndpointsFlag();var e=this.config;if("regional"===e.stsRegionalEndpoints){if(o(this),!this.isGlobalEndpoint)return;if(this.isGlobalEndpoint=!1,!e.region)throw n.util.error(new Error,{code:"ConfigError",message:"Missing region in config"});var t=e.endpoint.indexOf(".amazonaws.com");e.endpoint=e.endpoint.substring(0,t)+"."+e.region+e.endpoint.substring(t)}},validateService:function(){this.optInRegionalEndpoint()}})}).call(this)}).call(this,e("_process"))},{"../core":18,"../region_config":53,_process:86}],62:[function(e,t,n){var o=e("../core"),r=o.util.inherit,i="presigned-expires";function s(e){var t=e.httpRequest.headers[i],n=e.service.getSignerClass(e);if(delete e.httpRequest.headers["User-Agent"],delete e.httpRequest.headers["X-Amz-User-Agent"],n===o.Signers.V4){if(t>604800)throw o.util.error(new Error,{code:"InvalidExpiryTime",message:"Presigning does not support expiry time greater than a week with SigV4 signing.",retryable:!1});e.httpRequest.headers[i]=t}else{if(n!==o.Signers.S3)throw o.util.error(new Error,{message:"Presigning only supports S3 or SigV4 signing.",code:"UnsupportedSigner",retryable:!1});var r=e.service?e.service.getSkewCorrectedDate():o.util.date.getDate();e.httpRequest.headers[i]=parseInt(o.util.date.unixTimestamp(r)+t,10).toString()}}function c(e){var t=e.httpRequest.endpoint,n=o.util.urlParse(e.httpRequest.path),r={};n.search&&(r=o.util.queryStringParse(n.search.substr(1)));var s=e.httpRequest.headers.Authorization.split(" ");if("AWS"===s[0])s=s[1].split(":"),r.AWSAccessKeyId=s[0],r.Signature=s[1],o.util.each(e.httpRequest.headers,(function(e,t){e===i&&(e="Expires"),0===e.indexOf("x-amz-meta-")&&(delete r[e],e=e.toLowerCase()),r[e]=t})),delete e.httpRequest.headers[i],delete r.Authorization,delete r.Host;else if("AWS4-HMAC-SHA256"===s[0]){s.shift();var c=s.join(" ").match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];r["X-Amz-Signature"]=c,delete r.Expires}t.pathname=n.pathname,t.search=o.util.queryParamsToString(r)}o.Signers.Presign=r({sign:function(e,t,n){if(e.httpRequest.headers[i]=t||3600,e.on("build",s),e.on("sign",c),e.removeListener("afterBuild",o.EventListeners.Core.SET_CONTENT_LENGTH),e.removeListener("afterBuild",o.EventListeners.Core.COMPUTE_SHA256),e.emit("beforePresign",[e]),!n){if(e.build(),e.response.error)throw e.response.error;return o.util.urlFormat(e.httpRequest.endpoint)}e.build((function(){this.response.error?n(this.response.error):n(null,o.util.urlFormat(e.httpRequest.endpoint))}))}}),t.exports=o.Signers.Presign},{"../core":18}],63:[function(e,t,n){var o=e("../core"),r=o.util.inherit;o.Signers.RequestSigner=r({constructor:function(e){this.request=e},setServiceClientId:function(e){this.serviceClientId=e},getServiceClientId:function(){return this.serviceClientId}}),o.Signers.RequestSigner.getVersion=function(e){switch(e){case"v2":return o.Signers.V2;case"v3":return o.Signers.V3;case"s3v4":case"v4":return o.Signers.V4;case"s3":return o.Signers.S3;case"v3https":return o.Signers.V3Https}throw new Error("Unknown signing version "+e)},e("./v2"),e("./v3"),e("./v3https"),e("./v4"),e("./s3"),e("./presign")},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(e,t,n){var o=e("../core"),r=o.util.inherit;o.Signers.S3=r(o.Signers.RequestSigner,{subResources:{acl:1,accelerate:1,analytics:1,cors:1,lifecycle:1,delete:1,inventory:1,location:1,logging:1,metrics:1,notification:1,partNumber:1,policy:1,requestPayment:1,replication:1,restore:1,tagging:1,torrent:1,uploadId:1,uploads:1,versionId:1,versioning:1,versions:1,website:1},responseHeaders:{"response-content-type":1,"response-content-language":1,"response-expires":1,"response-cache-control":1,"response-content-disposition":1,"response-content-encoding":1},addAuthorization:function(e,t){this.request.headers["presigned-expires"]||(this.request.headers["X-Amz-Date"]=o.util.date.rfc822(t)),e.sessionToken&&(this.request.headers["x-amz-security-token"]=e.sessionToken);var n=this.sign(e.secretAccessKey,this.stringToSign()),r="AWS "+e.accessKeyId+":"+n;this.request.headers.Authorization=r},stringToSign:function(){var e=this.request,t=[];t.push(e.method),t.push(e.headers["Content-MD5"]||""),t.push(e.headers["Content-Type"]||""),t.push(e.headers["presigned-expires"]||"");var n=this.canonicalizedAmzHeaders();return n&&t.push(n),t.push(this.canonicalizedResource()),t.join("\n")},canonicalizedAmzHeaders:function(){var e=[];o.util.each(this.request.headers,(function(t){t.match(/^x-amz-/i)&&e.push(t)})),e.sort((function(e,t){return e.toLowerCase()=0?"&":"?";this.request.path+=i+o.util.queryParamsToString(r)},authorization:function(e,t){var n=[],o=this.credentialString(t);return n.push(this.algorithm+" Credential="+e.accessKeyId+"/"+o),n.push("SignedHeaders="+this.signedHeaders()),n.push("Signature="+this.signature(e,t)),n.join(", ")},signature:function(e,t){var n=r.getSigningKey(e,t.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return o.util.crypto.hmac(n,this.stringToSign(t),"hex")},stringToSign:function(e){var t=[];return t.push("AWS4-HMAC-SHA256"),t.push(e),t.push(this.credentialString(e)),t.push(this.hexEncodedHash(this.canonicalString())),t.join("\n")},canonicalString:function(){var e=[],t=this.request.pathname();return"s3"!==this.serviceName&&"s3v4"!==this.signatureVersion&&(t=o.util.uriEscapePath(t)),e.push(this.request.method),e.push(t),e.push(this.request.search()),e.push(this.canonicalHeaders()+"\n"),e.push(this.signedHeaders()),e.push(this.hexEncodedBodyHash()),e.join("\n")},canonicalHeaders:function(){var e=[];o.util.each.call(this,this.request.headers,(function(t,n){e.push([t,n])})),e.sort((function(e,t){return e[0].toLowerCase()50&&delete r[i.shift()]),d},emptyCache:function(){r={},i=[]}}},{"../core":18}],70:[function(e,t,n){function o(e,t){this.currentState=t||null,this.states=e||{}}o.prototype.runTo=function(e,t,n,o){"function"==typeof e&&(o=n,n=t,t=e,e=null);var r=this,i=r.states[r.currentState];i.fn.call(n||r,o,(function(o){if(o){if(!i.fail)return t?t.call(n,o):null;r.currentState=i.fail}else{if(!i.accept)return t?t.call(n):null;r.currentState=i.accept}if(r.currentState===e)return t?t.call(n,o):null;r.runTo(e,t,n,o)}))},o.prototype.addState=function(e,t,n,o){return"function"==typeof t?(o=t,t=null,n=null):"function"==typeof n&&(o=n,n=null),this.currentState||(this.currentState=e),this.states[e]={accept:t,fail:n,fn:o},this},t.exports=o},{}],71:[function(e,t,n){(function(n,o){(function(){var i,s={environment:"nodejs",engine:function(){if(s.isBrowser()&&"undefined"!=typeof navigator)return navigator.userAgent;var e=n.platform+"/"+n.version;return n.env.AWS_EXECUTION_ENV&&(e+=" exec-env/"+n.env.AWS_EXECUTION_ENV),e},userAgent:function(){var t=s.environment,n="aws-sdk-"+t+"/"+e("./core").VERSION;return"nodejs"===t&&(n+=" "+s.engine()),n},uriEscape:function(e){var t=encodeURIComponent(e);return t=(t=t.replace(/[^A-Za-z0-9_.~\-%]+/g,escape)).replace(/[*]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))},uriEscapePath:function(e){var t=[];return s.arrayEach(e.split("/"),(function(e){t.push(s.uriEscape(e))})),t.join("/")},urlParse:function(e){return s.url.parse(e)},urlFormat:function(e){return s.url.format(e)},queryStringParse:function(e){return s.querystring.parse(e)},queryParamsToString:function(e){var t=[],n=s.uriEscape,o=Object.keys(e).sort();return s.arrayEach(o,(function(o){var r=e[o],i=n(o),c=i+"=";if(Array.isArray(r)){var a=[];s.arrayEach(r,(function(e){a.push(n(e))})),c=i+"="+a.sort().join("&"+i+"=")}else null!=r&&(c=i+"="+n(r));t.push(c)})),t.join("&")},readFileSync:function(t){return s.isBrowser()?null:e("fs").readFileSync(t,"utf-8")},base64:{encode:function(e){if("number"==typeof e)throw s.error(new Error("Cannot base64 encode number "+e));return null==e?e:s.buffer.toBuffer(e).toString("base64")},decode:function(e){if("number"==typeof e)throw s.error(new Error("Cannot base64 decode number "+e));return null==e?e:s.buffer.toBuffer(e,"base64")}},buffer:{toBuffer:function(e,t){return"function"==typeof s.Buffer.from&&s.Buffer.from!==Uint8Array.from?s.Buffer.from(e,t):new s.Buffer(e,t)},alloc:function(e,t,n){if("number"!=typeof e)throw new Error("size passed to alloc must be a number.");if("function"==typeof s.Buffer.alloc)return s.Buffer.alloc(e,t,n);var o=new s.Buffer(e);return void 0!==t&&"function"==typeof o.fill&&o.fill(t,void 0,void 0,n),o},toStream:function(e){s.Buffer.isBuffer(e)||(e=s.buffer.toBuffer(e));var t=new s.stream.Readable,n=0;return t._read=function(o){if(n>=e.length)return t.push(null);var r=n+o;r>e.length&&(r=e.length),t.push(e.slice(n,r)),n=r},t},concat:function(e){var t,n,o=0,r=0;for(n=0;n>>8^t[255&(n^e.readUInt8(o))];return(-1^n)>>>0},hmac:function(e,t,n,o){return n||(n="binary"),"buffer"===n&&(n=void 0),o||(o="sha256"),"string"==typeof t&&(t=s.buffer.toBuffer(t)),s.crypto.lib.createHmac(o,e).update(t).digest(n)},md5:function(e,t,n){return s.crypto.hash("md5",e,t,n)},sha256:function(e,t,n){return s.crypto.hash("sha256",e,t,n)},hash:function(e,t,n,o){var i=s.crypto.createHash(e);n||(n="binary"),"buffer"===n&&(n=void 0),"string"==typeof t&&(t=s.buffer.toBuffer(t));var c=s.arraySliceFn(t),a=s.Buffer.isBuffer(t);if(s.isBrowser()&&"undefined"!=typeof ArrayBuffer&&t&&t.buffer instanceof ArrayBuffer&&(a=!0),o&&"object"===r(t)&&"function"==typeof t.on&&!a)t.on("data",(function(e){i.update(e)})),t.on("error",(function(e){o(e)})),t.on("end",(function(){o(null,i.digest(n))}));else{if(!o||!c||a||"undefined"==typeof FileReader){s.isBrowser()&&"object"===r(t)&&!a&&(t=new s.Buffer(new Uint8Array(t)));var u=i.update(t).digest(n);return o&&o(null,u),u}var l=0,p=new FileReader;p.onerror=function(){o(new Error("Failed to read data."))},p.onload=function(){var e=new s.Buffer(new Uint8Array(p.result));i.update(e),l+=e.length,p._continueReading()},p._continueReading=function(){if(l>=t.size)o(null,i.digest(n));else{var e=l+524288;e>t.size&&(e=t.size),p.readAsArrayBuffer(c.call(t,l,e))}},p._continueReading()}},toHex:function(e){for(var t=[],n=0;n=3e5,!1),i.config.isClockSkewed},applyClockOffset:function(e){e&&(i.config.systemClockOffset=e-(new Date).getTime())},extractRequestId:function(e){var t=e.httpResponse.headers["x-amz-request-id"]||e.httpResponse.headers["x-amzn-requestid"];!t&&e.data&&e.data.ResponseMetadata&&(t=e.data.ResponseMetadata.RequestId),t&&(e.requestId=t),e.error&&(e.error.requestId=t)},addPromises:function(e,t){var n=!1;void 0===t&&i&&i.config&&(t=i.config.getPromisesDependency()),void 0===t&&"undefined"!=typeof Promise&&(t=Promise),"function"!=typeof t&&(n=!0),Array.isArray(e)||(e=[e]);for(var o=0;o=500||429===o});r&&i.retryable&&(i.retryAfter=r),a(i)}}))}),a)};i.util.defer(u)},uuid:{v4:function(){return e("uuid").v4()}},convertPayloadToString:function(e){var t=e.request,n=t.operation,o=t.service.api.operations[n].output||{};o.payload&&e.data[o.payload]&&(e.data[o.payload]=e.data[o.payload].toString())},defer:function(e){"object"===r(n)&&"function"==typeof n.nextTick?n.nextTick(e):"function"==typeof o?o(e):setTimeout(e,0)},getRequestPayloadShape:function(e){var t=e.service.api.operations;if(t){var n=(t||{})[e.operation];if(n&&n.input&&n.input.payload)return n.input.members[n.input.payload]}},getProfilesFromSharedConfig:function(e,t){var o={},r={};n.env[s.configOptInEnv]&&(r=e.loadFrom({isConfig:!0,filename:n.env[s.sharedConfigFileEnv]}));for(var i=e.loadFrom({filename:t||n.env[s.configOptInEnv]&&n.env[s.sharedCredentialsFileEnv]}),c=0,a=Object.keys(r);c0||o?i.toString():""},t.exports=s},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(e,t,n){t.exports={escapeAttribute:function(e){return e.replace(/&/g,"&").replace(/'/g,"'").replace(//g,">").replace(/"/g,""")}}},{}],75:[function(e,t,n){t.exports={escapeElement:function(e){return e.replace(/&/g,"&").replace(//g,">")}}},{}],76:[function(e,t,n){var o=e("./escape-attribute").escapeAttribute;function r(e,t){void 0===t&&(t=[]),this.name=e,this.children=t,this.attributes={}}r.prototype.addAttribute=function(e,t){return this.attributes[e]=t,this},r.prototype.addChildNode=function(e){return this.children.push(e),this},r.prototype.removeAttribute=function(e){return delete this.attributes[e],this},r.prototype.toString=function(){for(var e=Boolean(this.children.length),t="<"+this.name,n=this.attributes,r=0,i=Object.keys(n);r"+this.children.map((function(e){return e.toString()})).join("")+"":"/>")},t.exports={XmlNode:r}},{"./escape-attribute":74}],77:[function(e,t,n){var o=e("./escape-element").escapeElement;function r(e){this.value=e}r.prototype.toString=function(){return o(""+this.value)},t.exports={XmlText:r}},{"./escape-element":75}],78:[function(e,t,n){"use strict";n.byteLength=function(e){var t=a(e),n=t[0],o=t[1];return 3*(n+o)/4-o},n.toByteArray=function(e){var t,n,o=a(e),s=o[0],c=o[1],u=new i(function(e,t,n){return 3*(t+n)/4-n}(0,s,c)),l=0,p=c>0?s-4:s;for(n=0;n>16&255,u[l++]=t>>8&255,u[l++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,u[l++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t),u},n.fromByteArray=function(e){for(var t,n=e.length,r=n%3,i=[],s=16383,c=0,a=n-r;ca?a:c+s));return 1===r?(t=e[n-1],i.push(o[t>>2]+o[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],i.push(o[t>>10]+o[t>>4&63]+o[t<<2&63]+"=")),i.join("")};for(var o=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0;c<64;++c)o[c]=s[c],r[s.charCodeAt(c)]=c;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function u(e,t,n){for(var r,i,s=[],c=t;c>18&63]+o[i>>12&63]+o[i>>6&63]+o[63&i]);return s.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},{}],79:[function(e,t,n){},{}],80:[function(e,t,i){(function(e){(function(){!function(s){var c="object"==r(i)&&i&&!i.nodeType&&i,a="object"==r(t)&&t&&!t.nodeType&&t,u="object"==r(e)&&e;u.global!==u&&u.window!==u&&u.self!==u||(s=u);var l,p,h=2147483647,d=36,f=1,g=26,m=38,v=700,y=72,E=128,S="-",b=/^xn--/,C=/[^\x20-\x7E]/,T=/[\x2E\u3002\uFF0E\uFF61]/g,I={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},A=d-f,_=Math.floor,w=String.fromCharCode;function R(e){throw RangeError(I[e])}function N(e,t){for(var n=e.length,o=[];n--;)o[n]=t(e[n]);return o}function k(e,t){var n=e.split("@"),o="";return n.length>1&&(o=n[0]+"@",e=n[1]),o+N((e=e.replace(T,".")).split("."),t).join(".")}function O(e){for(var t,n,o=[],r=0,i=e.length;r=55296&&t<=56319&&r65535&&(t+=w((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=w(e)})).join("")}function D(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function P(e,t,n){var o=0;for(e=n?_(e/v):e>>1,e+=_(e/t);e>A*g>>1;o+=d)e=_(e/A);return _(o+(A+1)*e/(e+m))}function x(e){var t,n,o,r,i,s,c,a,u,l,p,m=[],v=e.length,b=0,C=E,T=y;for((n=e.lastIndexOf(S))<0&&(n=0),o=0;o=128&&R("not-basic"),m.push(e.charCodeAt(o));for(r=n>0?n+1:0;r=v&&R("invalid-input"),((a=(p=e.charCodeAt(r++))-48<10?p-22:p-65<26?p-65:p-97<26?p-97:d)>=d||a>_((h-b)/s))&&R("overflow"),b+=a*s,!(a<(u=c<=T?f:c>=T+g?g:c-T));c+=d)s>_(h/(l=d-u))&&R("overflow"),s*=l;T=P(b-i,t=m.length+1,0==i),_(b/t)>h-C&&R("overflow"),C+=_(b/t),b%=t,m.splice(b++,0,C)}return L(m)}function M(e){var t,n,o,r,i,s,c,a,u,l,p,m,v,b,C,T=[];for(m=(e=O(e)).length,t=E,n=0,i=y,s=0;s=t&&p_((h-n)/(v=o+1))&&R("overflow"),n+=(c-t)*v,t=c,s=0;sh&&R("overflow"),p==t){for(a=n,u=d;!(a<(l=u<=i?f:u>=i+g?g:u-i));u+=d)C=a-l,b=d-l,T.push(w(D(l+C%b,0))),a=_(C/b);T.push(w(D(a,0))),i=P(n,v,o==r),n=0,++o}++n,++t}return T.join("")}if(l={version:"1.3.2",ucs2:{decode:O,encode:L},decode:x,encode:M,toASCII:function(e){return k(e,(function(e){return C.test(e)?"xn--"+M(e):e}))},toUnicode:function(e){return k(e,(function(e){return b.test(e)?x(e.slice(4).toLowerCase()):e}))}},"object"==r(n.amdO)&&n.amdO)void 0===(o=function(){return l}.call(i,n,i,t))||(t.exports=o);else if(c&&a)if(t.exports==c)a.exports=l;else for(p in l)l.hasOwnProperty(p)&&(c[p]=l[p]);else s.punycode=l}(this)}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],81:[function(e,t,o){(function(t,n){(function(){"use strict";var n=e("base64-js"),r=e("ieee754"),i=e("isarray");function s(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function c(e,t){if(s()=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function f(e,t){if(a.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var o=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return j(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return B(e).length;default:if(o)return j(e).length;t=(""+t).toLowerCase(),o=!0}}function g(e,t,n){var o=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return k(this,t,n);case"utf8":case"utf-8":return _(this,t,n);case"ascii":return R(this,t,n);case"latin1":case"binary":return N(this,t,n);case"base64":return A(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function m(e,t,n){var o=e[t];e[t]=e[n],e[n]=o}function v(e,t,n,o,r){if(0===e.length)return-1;if("string"==typeof n?(o=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=r?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(r)return-1;n=e.length-1}else if(n<0){if(!r)return-1;n=0}if("string"==typeof t&&(t=a.from(t,o)),a.isBuffer(t))return 0===t.length?-1:y(e,t,n,o,r);if("number"==typeof t)return t&=255,a.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?r?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):y(e,[t],n,o,r);throw new TypeError("val must be string, number or Buffer")}function y(e,t,n,o,r){var i,s=1,c=e.length,a=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s=2,c/=2,a/=2,n/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(r){var l=-1;for(i=n;ic&&(n=c-a),i=n;i>=0;i--){for(var p=!0,h=0;hr&&(o=r):o=r;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");o>i/2&&(o=i/2);for(var s=0;s>8,r=n%256,i.push(r),i.push(o);return i}(t,e.length-n),e,n,o)}function A(e,t,o){return 0===t&&o===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,o))}function _(e,t,n){n=Math.min(e.length,n);for(var o=[],r=t;r239?4:u>223?3:u>191?2:1;if(r+p<=n)switch(p){case 1:u<128&&(l=u);break;case 2:128==(192&(i=e[r+1]))&&(a=(31&u)<<6|63&i)>127&&(l=a);break;case 3:i=e[r+1],s=e[r+2],128==(192&i)&&128==(192&s)&&(a=(15&u)<<12|(63&i)<<6|63&s)>2047&&(a<55296||a>57343)&&(l=a);break;case 4:i=e[r+1],s=e[r+2],c=e[r+3],128==(192&i)&&128==(192&s)&&128==(192&c)&&(a=(15&u)<<18|(63&i)<<12|(63&s)<<6|63&c)>65535&&a<1114112&&(l=a)}null===l?(l=65533,p=1):l>65535&&(l-=65536,o.push(l>>>10&1023|55296),l=56320|1023&l),o.push(l),r+=p}return function(e){var t=e.length;if(t<=w)return String.fromCharCode.apply(String,e);for(var n="",o=0;o0&&(e=this.toString("hex",0,t).match(/.{2}/g).join(" "),this.length>t&&(e+=" ... ")),""},a.prototype.compare=function(e,t,n,o,r){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===o&&(o=0),void 0===r&&(r=this.length),t<0||n>e.length||o<0||r>this.length)throw new RangeError("out of range index");if(o>=r&&t>=n)return 0;if(o>=r)return-1;if(t>=n)return 1;if(this===e)return 0;for(var i=(r>>>=0)-(o>>>=0),s=(n>>>=0)-(t>>>=0),c=Math.min(i,s),u=this.slice(o,r),l=e.slice(t,n),p=0;pr)&&(n=r),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");for(var i=!1;;)switch(o){case"hex":return E(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return b(this,e,t,n);case"latin1":case"binary":return C(this,e,t,n);case"base64":return T(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),i=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var w=4096;function R(e,t,n){var o="";n=Math.min(e.length,n);for(var r=t;rr)&&(n=r);for(var i="",s=t;sn)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,n,o,r,i){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>r||te.length)throw new RangeError("Index out of range")}function P(e,t,n,o){t<0&&(t=65535+t+1);for(var r=0,i=Math.min(e.length-n,2);r>>8*(o?r:1-r)}function x(e,t,n,o){t<0&&(t=4294967295+t+1);for(var r=0,i=Math.min(e.length-n,4);r>>8*(o?r:3-r)&255}function M(e,t,n,o,r,i){if(n+o>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function U(e,t,n,o,i){return i||M(e,0,n,4),r.write(e,t,n,o,23,4),n+4}function q(e,t,n,o,i){return i||M(e,0,n,8),r.write(e,t,n,o,52,8),n+8}a.prototype.slice=function(e,t){var n,o=this.length;if((e=~~e)<0?(e+=o)<0&&(e=0):e>o&&(e=o),(t=void 0===t?o:~~t)<0?(t+=o)<0&&(t=0):t>o&&(t=o),t0&&(r*=256);)o+=this[e+--t]*r;return o},a.prototype.readUInt8=function(e,t){return t||L(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return t||L(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return t||L(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var o=this[e],r=1,i=0;++i=(r*=128)&&(o-=Math.pow(2,8*t)),o},a.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||L(e,t,this.length);for(var o=t,r=1,i=this[e+--o];o>0&&(r*=256);)i+=this[e+--o]*r;return i>=(r*=128)&&(i-=Math.pow(2,8*t)),i},a.prototype.readInt8=function(e,t){return t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){t||L(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt16BE=function(e,t){t||L(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},a.prototype.readInt32LE=function(e,t){return t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return t||L(e,4,this.length),r.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return t||L(e,4,this.length),r.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return t||L(e,8,this.length),r.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return t||L(e,8,this.length),r.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,n,o){e=+e,t|=0,n|=0,o||D(this,e,t,n,Math.pow(2,8*n)-1,0);var r=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+r]=e/i&255;return t+n},a.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,255,0),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):x(this,e,t,!0),t+4},a.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},a.prototype.writeIntLE=function(e,t,n,o){if(e=+e,t|=0,!o){var r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}var i=0,s=1,c=0;for(this[t]=255&e;++i>0)-c&255;return t+n},a.prototype.writeIntBE=function(e,t,n,o){if(e=+e,t|=0,!o){var r=Math.pow(2,8*n-1);D(this,e,t,n,r-1,-r)}var i=n-1,s=1,c=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===c&&0!==this[t+i+1]&&(c=1),this[t+i]=(e/s>>0)-c&255;return t+n},a.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,1,127,-128),a.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):P(this,e,t,!0),t+2},a.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):P(this,e,t,!1),t+2},a.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):x(this,e,t,!0),t+4},a.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),a.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):x(this,e,t,!1),t+4},a.prototype.writeFloatLE=function(e,t,n){return U(this,e,t,!0,n)},a.prototype.writeFloatBE=function(e,t,n){return U(this,e,t,!1,n)},a.prototype.writeDoubleLE=function(e,t,n){return q(this,e,t,!0,n)},a.prototype.writeDoubleBE=function(e,t,n){return q(this,e,t,!1,n)},a.prototype.copy=function(e,t,n,o){if(n||(n=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o=this.length)throw new RangeError("sourceStart out of bounds");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t=0;--r)e[r+t]=this[r+n];else if(i<1e3||!a.TYPED_ARRAY_SUPPORT)for(r=0;r>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i55295&&n<57344){if(!r){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===o){(t-=3)>-1&&i.push(239,191,189);continue}r=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),r=n;continue}n=65536+(r-55296<<10|n-56320)}else r&&(t-=3)>-1&&i.push(239,191,189);if(r=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function B(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(F,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function V(e,t,n,o){for(var r=0;r=t.length||r>=e.length);++r)t[r+n]=e[r];return r}}).call(this)}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"base64-js":78,buffer:81,ieee754:83,isarray:84}],82:[function(e,t,n){function o(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(e){return"function"==typeof e}function s(e){return"object"===r(e)&&null!==e}function c(e){return void 0===e}t.exports=o,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._maxListeners=void 0,o.defaultMaxListeners=10,o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},o.prototype.emit=function(e){var t,n,o,r,a,u;if(this._events||(this._events={}),"error"===e&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var l=new Error('Uncaught, unspecified "error" event. ('+t+")");throw l.context=t,l}if(c(n=this._events[e]))return!1;if(i(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:r=Array.prototype.slice.call(arguments,1),n.apply(this,r)}else if(s(n))for(r=Array.prototype.slice.call(arguments,1),o=(u=n.slice()).length,a=0;a0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},o.prototype.on=o.prototype.addListener,o.prototype.once=function(e,t){if(!i(t))throw TypeError("listener must be a function");var n=!1;function o(){this.removeListener(e,o),n||(n=!0,t.apply(this,arguments))}return o.listener=t,this.on(e,o),this},o.prototype.removeListener=function(e,t){var n,o,r,c;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(r=(n=this._events[e]).length,o=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(s(n)){for(c=r;c-- >0;)if(n[c]===t||n[c].listener&&n[c].listener===t){o=c;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},o.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},o.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},o.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},o.listenerCount=function(e,t){return e.listenerCount(t)}},{}],83:[function(e,t,n){n.read=function(e,t,n,o,r){var i,s,c=8*r-o-1,a=(1<>1,l=-7,p=n?r-1:0,h=n?-1:1,d=e[t+p];for(p+=h,i=d&(1<<-l)-1,d>>=-l,l+=c;l>0;i=256*i+e[t+p],p+=h,l-=8);for(s=i&(1<<-l)-1,i>>=-l,l+=o;l>0;s=256*s+e[t+p],p+=h,l-=8);if(0===i)i=1-u;else{if(i===a)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,o),i-=u}return(d?-1:1)*s*Math.pow(2,i-o)},n.write=function(e,t,n,o,r,i){var s,c,a,u=8*i-r-1,l=(1<>1,h=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,d=o?0:i-1,f=o?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-s))<1&&(s--,a*=2),(t+=s+p>=1?h/a:h*Math.pow(2,1-p))*a>=2&&(s++,a/=2),s+p>=l?(c=0,s=l):s+p>=1?(c=(t*a-1)*Math.pow(2,r),s+=p):(c=t*Math.pow(2,p-1)*Math.pow(2,r),s=0));r>=8;e[n+d]=255&c,d+=f,c/=256,r-=8);for(s=s<0;e[n+d]=255&s,d+=f,s/=256,u-=8);e[n+d-f]|=128*g}},{}],84:[function(e,t,n){var o={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==o.call(e)}},{}],85:[function(e,t,n){!function(e){"use strict";function t(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function n(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function o(e,r){if(e===r)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(r))return!1;if(!0===t(e)){if(e.length!==r.length)return!1;for(var i=0;i":!0,"=":!0,"!":!0},G={" ":!0,"\t":!0,"\n":!0};function z(e){return e>="0"&&e<="9"||"-"===e}function K(){}K.prototype={tokenize:function(e){var t,n,o,r,i=[];for(this._current=0;this._current="a"&&r<="z"||r>="A"&&r<="Z"||"_"===r)t=this._current,n=this._consumeUnquotedIdentifier(e),i.push({type:g,value:n,start:t});else if(void 0!==H[e[this._current]])i.push({type:H[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(z(e[this._current]))o=this._consumeNumber(e),i.push(o);else if("["===e[this._current])o=this._consumeLBracket(e),i.push(o);else if('"'===e[this._current])t=this._current,n=this._consumeQuotedIdentifier(e),i.push({type:m,value:n,start:t});else if("'"===e[this._current])t=this._current,n=this._consumeRawStringLiteral(e),i.push({type:V,value:n,start:t});else if("`"===e[this._current]){t=this._current;var s=this._consumeLiteral(e);i.push({type:V,value:s,start:t})}else if(void 0!==W[e[this._current]])i.push(this._consumeOperator(e));else if(void 0!==G[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,i.push({type:w,value:"&&",start:t})):i.push({type:I,value:"&",start:t});else{if("|"!==e[this._current]){var c=new Error("Unknown character:"+e[this._current]);throw c.name="LexerError",c}t=this._current,this._current++,"|"===e[this._current]?(this._current++,i.push({type:_,value:"||",start:t})):i.push({type:A,value:"|",start:t})}return i},_consumeUnquotedIdentifier:function(e){var t,n=this._current;for(this._current++;this._current="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||"_"===t);)this._current++;return e.slice(n,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var n=e.length;'"'!==e[this._current]&&this._current"===n?"="===e[this._current]?(this._current++,{type:O,value:">=",start:t}):{type:N,value:">",start:t}:"="===n&&"="===e[this._current]?(this._current++,{type:R,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,n=this._current,o=e.length;"`"!==e[this._current]&&this._current=0)return!0;if(["true","false","null"].indexOf(e)>=0)return!0;if(!("-0123456789".indexOf(e[0])>=0))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var Y={};function X(){}function J(e){this.runtime=e}function Q(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[s]}]},avg:{_func:this._functionAvg,_signature:[{types:[h]}]},ceil:{_func:this._functionCeil,_signature:[{types:[s]}]},contains:{_func:this._functionContains,_signature:[{types:[a,u]},{types:[c]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[a]},{types:[a]}]},floor:{_func:this._functionFloor,_signature:[{types:[s]}]},length:{_func:this._functionLength,_signature:[{types:[a,u,l]}]},map:{_func:this._functionMap,_signature:[{types:[p]},{types:[u]}]},max:{_func:this._functionMax,_signature:[{types:[h,d]}]},merge:{_func:this._functionMerge,_signature:[{types:[l],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[u]},{types:[p]}]},sum:{_func:this._functionSum,_signature:[{types:[h]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[a]},{types:[a]}]},min:{_func:this._functionMin,_signature:[{types:[h,d]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[u]},{types:[p]}]},type:{_func:this._functionType,_signature:[{types:[c]}]},keys:{_func:this._functionKeys,_signature:[{types:[l]}]},values:{_func:this._functionValues,_signature:[{types:[l]}]},sort:{_func:this._functionSort,_signature:[{types:[d,h]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[u]},{types:[p]}]},join:{_func:this._functionJoin,_signature:[{types:[a]},{types:[d]}]},reverse:{_func:this._functionReverse,_signature:[{types:[a,u]}]},to_array:{_func:this._functionToArray,_signature:[{types:[c]}]},to_string:{_func:this._functionToString,_signature:[{types:[c]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[c]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[c],variadic:!0}]}}}Y[f]=0,Y[g]=0,Y[m]=0,Y[v]=0,Y[y]=0,Y[E]=0,Y[b]=0,Y[C]=0,Y[T]=0,Y[I]=0,Y[A]=1,Y[_]=2,Y[w]=3,Y[R]=5,Y[N]=5,Y[k]=5,Y[O]=5,Y[L]=5,Y[D]=5,Y[P]=9,Y[x]=20,Y[M]=21,Y[U]=40,Y[q]=45,Y[F]=50,Y[j]=55,Y[B]=60,X.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)!==f){var n=this._lookaheadToken(0),o=new Error("Unexpected token type: "+n.type+", value: "+n.value);throw o.name="ParserError",o}return t},_loadTokens:function(e){var t=(new K).tokenize(e);t.push({type:f,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var n=this.nud(t),o=this._lookahead(0);e=0?this.expression(e):t===j?(this._match(j),this._parseMultiselectList()):t===F?(this._match(F),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(Y[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===j)t=this.expression(e);else if(this._lookahead(0)===M)t=this.expression(e);else{if(this._lookahead(0)!==U){var n=this._lookaheadToken(0),o=new Error("Sytanx error, unexpected token: "+n.value+"("+n.type+")");throw o.name="ParserError",o}this._match(U),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==v;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===E&&(this._match(E),this._lookahead(0)===v))throw new Error("Unexpected token Rbracket")}return this._match(v),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,n,o=[],r=[g,m];;){if(e=this._lookaheadToken(0),r.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(S),n={type:"KeyValuePair",name:t,value:this.expression(0)},o.push(n),this._lookahead(0)===E)this._match(E);else if(this._lookahead(0)===b){this._match(b);break}}return{type:"MultiSelectHash",children:o}}},J.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,i){var s,c,a,u,l,p,h,d,f;switch(e.type){case"Field":return null===i?null:n(i)?void 0===(p=i[e.name])?null:p:null;case"Subexpression":for(a=this.visit(e.children[0],i),f=1;f0)for(f=y;fE;f+=S)a.push(i[f]);return a;case"Projection":var b=this.visit(e.children[0],i);if(!t(b))return null;for(d=[],f=0;fl;break;case O:a=u>=l;break;case k:a=u=e&&(t=n<0?e-1:e),t}},Q.prototype={callFunction:function(e,t){var n=this.functionTable[e];if(void 0===n)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,n._signature),n._func.call(this,t)},_validateArgs:function(e,t,n){var o,r,i,s;if(n[n.length-1].variadic){if(t.length=0;o--)n+=t[o];return n}var r=e[0].slice(0);return r.reverse(),r},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,n=e[0],o=0;o=0},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return n(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],n=this._interpreter,o=e[0],r=e[1],i=0;i0){if(this._getTypeName(e[0][0])===s)return Math.max.apply(Math,e[0]);for(var t=e[0],n=t[0],o=1;o0){if(this._getTypeName(e[0][0])===s)return Math.min.apply(Math,e[0]);for(var t=e[0],n=t[0],o=1;oc?1:sc&&(c=n,t=r[u]);return t},_functionMinBy:function(e){for(var t,n,o=e[1],r=e[0],i=this.createKeyFunction(o,[s,a]),c=1/0,u=0;u1)for(var n=1;n0&&u>a&&(u=a);for(var l=0;l=0?(p=g.substr(0,m),h=g.substr(m+1)):(p=g,h=""),d=decodeURIComponent(p),f=decodeURIComponent(h),o(s,d)?r(s[d])?s[d].push(f):s[d]=[s[d],f]:s[d]=f}return s};var r=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],88:[function(e,t,n){"use strict";var o=function(e){switch(r(e)){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"===r(e)?s(c(e),(function(r){var c=encodeURIComponent(o(r))+n;return i(e[r])?s(e[r],(function(e){return c+encodeURIComponent(o(e))})).join(t):c+encodeURIComponent(o(e[r]))})).join(t):a?encodeURIComponent(o(a))+n+encodeURIComponent(o(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],o=0;o0&&a>c&&(a=c);for(var u=0;u=0?(l=f.substr(0,g),p=f.substr(g+1)):(l=f,p=""),h=decodeURIComponent(l),d=decodeURIComponent(p),o(i,h)?Array.isArray(i[h])?i[h].push(d):i[h]=[i[h],d]:i[h]=d}return i}},{}],91:[function(e,t,n){"use strict";var o=function(e){switch(r(e)){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,i){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"===r(e)?Object.keys(e).map((function(r){var i=encodeURIComponent(o(r))+n;return Array.isArray(e[r])?e[r].map((function(e){return i+encodeURIComponent(o(e))})).join(t):i+encodeURIComponent(o(e[r]))})).join(t):i?encodeURIComponent(o(i))+n+encodeURIComponent(o(e)):""}},{}],92:[function(e,t,n){arguments[4][89][0].apply(n,arguments)},{"./decode":90,"./encode":91,dup:89}],93:[function(e,t,n){(function(t,o){(function(){var r=e("process/browser.js").nextTick,i=Function.prototype.apply,s=Array.prototype.slice,c={},a=0;function u(e,t){this._id=e,this._clearFn=t}n.setTimeout=function(){return new u(i.call(setTimeout,window,arguments),clearTimeout)},n.setInterval=function(){return new u(i.call(setInterval,window,arguments),clearInterval)},n.clearTimeout=n.clearInterval=function(e){e.close()},u.prototype.unref=u.prototype.ref=function(){},u.prototype.close=function(){this._clearFn.call(window,this._id)},n.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},n.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},n._unrefActive=n.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout((function(){e._onTimeout&&e._onTimeout()}),t))},n.setImmediate="function"==typeof t?t:function(e){var t=a++,o=!(arguments.length<2)&&s.call(arguments,1);return c[t]=!0,r((function(){c[t]&&(o?e.apply(null,o):e.call(null),n.clearImmediate(t))})),t},n.clearImmediate="function"==typeof o?o:function(e){delete c[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":86,timers:93}],94:[function(e,t,n){var o=e("punycode");function i(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=y,n.resolve=function(e,t){return y(e,!1,!0).resolve(t)},n.resolveObject=function(e,t){return e?y(e,!1,!0).resolveObject(t):t},n.format=function(e){return E(e)&&(e=y(e)),e instanceof i?e.format():i.prototype.format.call(e)},n.Url=i;var s=/^([a-z0-9.+-]+:)/i,c=/:[0-9]*$/,a=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(a),l=["%","/","?",";","#"].concat(u),p=["/","?","#"],h=/^[a-z0-9A-Z_-]{0,63}$/,d=/^([a-z0-9A-Z_-]{0,63})(.*)$/,f={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},m={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=e("querystring");function y(e,t,n){if(e&&S(e)&&e instanceof i)return e;var o=new i;return o.parse(e,t,n),o}function E(e){return"string"==typeof e}function S(e){return"object"===r(e)&&null!==e}function b(e){return null===e}i.prototype.parse=function(e,t,n){if(!E(e))throw new TypeError("Parameter 'url' must be a string, not "+r(e));var i=e;i=i.trim();var c=s.exec(i);if(c){var a=(c=c[0]).toLowerCase();this.protocol=a,i=i.substr(c.length)}if(n||c||i.match(/^\/\/[^@\/]+@[^@\/]+/)){var y="//"===i.substr(0,2);!y||c&&g[c]||(i=i.substr(2),this.slashes=!0)}if(!g[c]&&(y||c&&!m[c])){for(var S,b,C=-1,T=0;T127?N+="x":N+=R[k];if(!N.match(h)){var L=_.slice(0,T),D=_.slice(T+1),P=R.match(d);P&&(L.push(P[1]),D.unshift(P[2])),D.length&&(i="/"+D.join(".")+i),this.hostname=L.join(".");break}}}if(this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),!A){var x=this.hostname.split("."),M=[];for(T=0;T0)&&n.host.split("@"))&&(n.auth=S.shift(),n.host=n.hostname=S.shift())),n.search=e.search,n.query=e.query,b(n.pathname)&&b(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!p.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var d=p.slice(-1)[0],f=(n.host||e.host)&&("."===d||".."===d)||""===d,v=0,y=p.length;y>=0;y--)"."==(d=p[y])?p.splice(y,1):".."===d?(p.splice(y,1),v++):v&&(p.splice(y,1),v--);if(!u&&!l)for(;v--;v)p.unshift("..");!u||""===p[0]||p[0]&&"/"===p[0].charAt(0)||p.unshift(""),f&&"/"!==p.join("/").substr(-1)&&p.push("");var S,C=""===p[0]||p[0]&&"/"===p[0].charAt(0);return h&&(n.hostname=n.host=C?"":p.length?p.shift():"",(S=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=S.shift(),n.host=n.hostname=S.shift())),(u=u||n.host&&p.length)&&!C&&p.unshift(""),p.length?n.pathname=p.join("/"):(n.pathname=null,n.path=null),b(n.pathname)&&b(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},i.prototype.parseHost=function(){var e=this.host,t=c.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{punycode:80,querystring:89}],95:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],96:[function(e,t,n){t.exports=function(e){return e&&"object"===r(e)&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],97:[function(e,t,o){(function(t,n){(function(){var i=/%[sdj%]/g;o.format=function(e){if(!y(e)){for(var t=[],n=0;n=r)return e;switch(e){case"%s":return String(o[n++]);case"%d":return Number(o[n++]);case"%j":try{return JSON.stringify(o[n++])}catch(e){return"[Circular]"}default:return e}})),c=o[n];n=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(t)?n.showHidden=t:t&&o._extend(n,t),E(n.showHidden)&&(n.showHidden=!1),E(n.depth)&&(n.depth=2),E(n.colors)&&(n.colors=!1),E(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),p(n,e,n.depth)}function u(e,t){var n=a.styles[t];return n?"["+a.colors[n][0]+"m"+e+"["+a.colors[n][1]+"m":e}function l(e,t){return e}function p(e,t,n){if(e.customInspect&&t&&I(t.inspect)&&t.inspect!==o.inspect&&(!t.constructor||t.constructor.prototype!==t)){var r=t.inspect(n,e);return y(r)||(r=p(e,r,n)),r}var i=function(e,t){if(E(t))return e.stylize("undefined","undefined");if(y(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return v(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):m(t)?e.stylize("null","null"):void 0}(e,t);if(i)return i;var s=Object.keys(t),c=function(e){var t={};return e.forEach((function(e,n){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(t)),T(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return h(t);if(0===s.length){if(I(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(S(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(C(t))return e.stylize(Date.prototype.toString.call(t),"date");if(T(t))return h(t)}var u,l="",b=!1,A=["{","}"];return f(t)&&(b=!0,A=["[","]"]),I(t)&&(l=" [Function"+(t.name?": "+t.name:"")+"]"),S(t)&&(l=" "+RegExp.prototype.toString.call(t)),C(t)&&(l=" "+Date.prototype.toUTCString.call(t)),T(t)&&(l=" "+h(t)),0!==s.length||b&&0!=t.length?n<0?S(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=b?function(e,t,n,o,r){for(var i=[],s=0,c=t.length;s60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}(u,l,A)):A[0]+l+A[1]}function h(e){return"["+Error.prototype.toString.call(e)+"]"}function d(e,t,n,o,r,i){var s,c,a;if((a=Object.getOwnPropertyDescriptor(t,r)||{value:t[r]}).get?c=a.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):a.set&&(c=e.stylize("[Setter]","special")),R(o,r)||(s="["+r+"]"),c||(e.seen.indexOf(a.value)<0?(c=m(n)?p(e,a.value,null):p(e,a.value,n-1)).indexOf("\n")>-1&&(c=i?c.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+c.split("\n").map((function(e){return" "+e})).join("\n")):c=e.stylize("[Circular]","special")),E(s)){if(i&&r.match(/^\d+$/))return c;(s=JSON.stringify(""+r)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+c}function f(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function m(e){return null===e}function v(e){return"number"==typeof e}function y(e){return"string"==typeof e}function E(e){return void 0===e}function S(e){return b(e)&&"[object RegExp]"===A(e)}function b(e){return"object"===r(e)&&null!==e}function C(e){return b(e)&&"[object Date]"===A(e)}function T(e){return b(e)&&("[object Error]"===A(e)||e instanceof Error)}function I(e){return"function"==typeof e}function A(e){return Object.prototype.toString.call(e)}function _(e){return e<10?"0"+e.toString(10):e.toString(10)}o.debuglog=function(e){if(E(s)&&(s=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!c[e])if(new RegExp("\\b"+e+"\\b","i").test(s)){var n=t.pid;c[e]=function(){var t=o.format.apply(o,arguments);console.error("%s %d: %s",e,n,t)}}else c[e]=function(){};return c[e]},o.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},o.isArray=f,o.isBoolean=g,o.isNull=m,o.isNullOrUndefined=function(e){return null==e},o.isNumber=v,o.isString=y,o.isSymbol=function(e){return"symbol"===r(e)},o.isUndefined=E,o.isRegExp=S,o.isObject=b,o.isDate=C,o.isError=T,o.isFunction=I,o.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"===r(e)||void 0===e},o.isBuffer=e("./support/isBuffer");var w=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}o.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[_(e.getHours()),_(e.getMinutes()),_(e.getSeconds())].join(":"),[e.getDate(),w[e.getMonth()],t].join(" ")),o.format.apply(o,arguments))},o.inherits=e("inherits"),o._extend=function(e,t){if(!t||!b(t))return e;for(var n=Object.keys(t),o=n.length;o--;)e[n[o]]=t[n[o]];return e}}).call(this)}).call(this,e("_process"),void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":96,_process:86,inherits:95}],98:[function(e,t,n){var o=e("./v1"),r=e("./v4"),i=r;i.v1=o,i.v4=r,t.exports=i},{"./v1":101,"./v4":102}],99:[function(e,t,n){for(var o=[],r=0;r<256;++r)o[r]=(r+256).toString(16).substr(1);t.exports=function(e,t){var n=t||0,r=o;return[r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],"-",r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]],r[e[n++]]].join("")}},{}],100:[function(e,t,n){var o="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(o){var r=new Uint8Array(16);t.exports=function(){return o(r),r}}else{var i=new Array(16);t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),i[t]=e>>>((3&t)<<3)&255;return i}}},{}],101:[function(e,t,n){var o,r,i=e("./lib/rng"),s=e("./lib/bytesToUuid"),c=0,a=0;t.exports=function(e,t,n){var u=t&&n||0,l=t||[],p=(e=e||{}).node||o,h=void 0!==e.clockseq?e.clockseq:r;if(null==p||null==h){var d=i();null==p&&(p=o=[1|d[0],d[1],d[2],d[3],d[4],d[5]]),null==h&&(h=r=16383&(d[6]<<8|d[7]))}var f=void 0!==e.msecs?e.msecs:(new Date).getTime(),g=void 0!==e.nsecs?e.nsecs:a+1,m=f-c+(g-a)/1e4;if(m<0&&void 0===e.clockseq&&(h=h+1&16383),(m<0||f>c)&&void 0===e.nsecs&&(g=0),g>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");c=f,a=g,r=h;var v=(1e4*(268435455&(f+=122192928e5))+g)%4294967296;l[u++]=v>>>24&255,l[u++]=v>>>16&255,l[u++]=v>>>8&255,l[u++]=255&v;var y=f/4294967296*1e4&268435455;l[u++]=y>>>8&255,l[u++]=255&y,l[u++]=y>>>24&15|16,l[u++]=y>>>16&255,l[u++]=h>>>8|128,l[u++]=255&h;for(var E=0;E<6;++E)l[u+E]=p[E];return t||s(l)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(e,t,n){var o=e("./lib/rng"),r=e("./lib/bytesToUuid");t.exports=function(e,t,n){var i=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t)for(var c=0;c<16;++c)t[i+c]=s[c];return t||r(s)}},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var o=e("./utils/LRU"),r=function(){function e(e){void 0===e&&(e=1e3),this.maxSize=e,this.cache=new o.LRUCache(e)}return Object.defineProperty(e.prototype,"size",{get:function(){return this.cache.length},enumerable:!0,configurable:!0}),e.prototype.put=function(t,n){var o="string"!=typeof t?e.getKeyString(t):t,r=this.populateValue(n);this.cache.put(o,r)},e.prototype.get=function(t){var n="string"!=typeof t?e.getKeyString(t):t,o=Date.now(),r=this.cache.get(n);if(r)for(var i=0;i{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.ClientMethods=connect.makeEnum(["getAgentSnapshot","putAgentState","getAgentStates","getDialableCountryCodes","getRoutingProfileQueues","getAgentPermissions","getAgentConfiguration","updateAgentConfiguration","acceptContact","createOutboundContact","createTaskContact","clearContact","completeContact","destroyContact","rejectContact","notifyContactIssue","updateContactAttributes","createAdditionalConnection","destroyConnection","holdConnection","resumeConnection","toggleActiveConnections","conferenceConnections","sendClientLogs","sendDigits","sendSoftphoneCallReport","sendSoftphoneCallMetrics","getEndpoints","getNewAuthToken","createTransport","muteParticipant","unmuteParticipant"]),connect.AgentAppClientMethods={GET_CONTACT:"AgentAppService.Lcms.getContact",DELETE_SPEAKER:"AgentAppService.VoiceId.deleteSpeaker",ENROLL_BY_SESSION:"AgentAppService.VoiceId.enrollBySession",EVALUATE_SESSION:"AgentAppService.VoiceId.evaluateSession",DESCRIBE_SPEAKER:"AgentAppService.VoiceId.describeSpeaker",OPT_OUT_SPEAKER:"AgentAppService.VoiceId.optOutSpeaker",UPDATE_VOICE_ID_DATA:"AgentAppService.Lcms.updateVoiceIdData",DESCRIBE_SESSION:"AgentAppService.VoiceId.describeSession",UPDATE_SESSION:"AgentAppService.VoiceId.updateSession",START_VOICE_ID_SESSION:"AgentAppService.Nasa.startVoiceIdSession",LIST_INTEGRATION_ASSOCIATIONS:"AgentAppService.Acs.listIntegrationAssociations"},connect.MasterMethods=connect.makeEnum(["becomeMaster","checkMaster"]);var t=function(){};t.EMPTY_CALLBACKS={success:function(){},failure:function(){}},t.prototype.call=function(e,n,o){connect.assertNotNull(e,"method");var r=n||{},i=o||t.EMPTY_CALLBACKS;this._callImpl(e,r,i)},t.prototype._callImpl=function(e,t,n){throw new connect.NotImplementedError};var n=function(){t.call(this)};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype._callImpl=function(e,t,n){if(n&&n.failure){var o=connect.sprintf("No such method exists on NULL client: %s",e);n.failure(new connect.ValueError(o),{message:o})}};var o=function(e,n,o){t.call(this),this.conduit=e,this.requestEvent=n,this.responseEvent=o,this._requestIdCallbacksMap={},this.conduit.onUpstream(o,connect.hitch(this,this._handleResponse))};(o.prototype=Object.create(t.prototype)).constructor=o,o.prototype._callImpl=function(e,t,n){var o=connect.EventFactory.createRequest(this.requestEvent,e,t);this._requestIdCallbacksMap[o.requestId]=n,this.conduit.sendUpstream(o.event,o)},o.prototype._getCallbacksForRequest=function(e){var t=this._requestIdCallbacksMap[e]||null;return null!=t&&delete this._requestIdCallbacksMap[e],t},o.prototype._handleResponse=function(e){var t=this._getCallbacksForRequest(e.requestId);null!=t&&(e.err&&t.failure?t.failure(e.err,e.data):t.success&&t.success(e.data))};var r=function(e){o.call(this,e,connect.EventType.API_REQUEST,connect.EventType.API_RESPONSE)};(r.prototype=Object.create(o.prototype)).constructor=r;var i=function(e){o.call(this,e,connect.EventType.MASTER_REQUEST,connect.EventType.MASTER_RESPONSE)};(i.prototype=Object.create(o.prototype)).constructor=i;var s=function(e,n,o){connect.assertNotNull(e,"authCookieName"),connect.assertNotNull(n,"authToken"),connect.assertNotNull(o,"endpoint"),t.call(this),this.endpointUrl=connect.getUrlWithProtocol(o),this.authToken=n,this.authCookieName=e};(s.prototype=Object.create(t.prototype)).constructor=s,s.prototype._callImpl=function(e,t,n){var o=this,r={};r[o.authCookieName]=o.authToken;var i={method:"post",body:JSON.stringify(t||{}),headers:{Accept:"application/json","Content-Type":"application/json","X-Amz-target":e,"X-Amz-Bearer":JSON.stringify(r)}};connect.fetch(o.endpointUrl,i).then((function(e){n.success(e)})).catch((function(e){var t=e.body.getReader(),o="",r=new TextDecoder;t.read().then((function i(s){var c=s.done,a=s.value;if(c){var u=JSON.parse(o);return u.status=e.status,void n.failure(u)}return o+=r.decode(a),t.read().then(i)}))}))};var c=function(e,n,o){connect.assertNotNull(e,"authToken"),connect.assertNotNull(n,"region"),t.call(this),AWS.config.credentials=new AWS.Credentials({}),AWS.config.region=n,this.authToken=e;var r=connect.getBaseUrl(),i=o||(r.includes(".awsapps.com")?r+"/connect/api":r+"/api"),s=new AWS.Endpoint(i);this.client=new AWS.Connect({endpoint:s})};(c.prototype=Object.create(t.prototype)).constructor=c,c.prototype._callImpl=function(e,t,n){var o=this,r=connect.getLog();if(connect.contains(this.client,e))t=this._translateParams(e,t),r.trace("AWSClient: --\x3e Calling operation '%s'",e).sendInternalLogToServer(),this.client[e](t).on("build",(function(e){e.httpRequest.headers["X-Amz-Bearer"]=o.authToken})).send((function(t,o){try{if(t){if(t.code===connect.CTIExceptions.UNAUTHORIZED_EXCEPTION)n.authFailure();else if(!n.accessDenied||t.code!==connect.CTIExceptions.ACCESS_DENIED_EXCEPTION&&403!==t.statusCode){var i={};i.type=t.code,i.message=t.message,i.stack=t.stack?t.stack.split("\n"):[],n.failure(i,o)}else n.accessDenied();r.trace("AWSClient: <-- Operation '%s' failed: %s",e,JSON.stringify(t)).sendInternalLogToServer()}else r.trace("AWSClient: <-- Operation '%s' succeeded.",e).withObject(o).sendInternalLogToServer(),n.success(o)}catch(t){connect.getLog().error("Failed to handle AWS API request for method %s",e).withException(t).sendInternalLogToServer()}}));else{var i=connect.sprintf("No such method exists on AWS client: %s",e);n.failure(new connect.ValueError(i),{message:i})}},c.prototype._requiresAuthenticationParam=function(e){return e!==connect.ClientMethods.COMPLETE_CONTACT&&e!==connect.ClientMethods.CLEAR_CONTACT&&e!==connect.ClientMethods.REJECT_CONTACT&&e!==connect.ClientMethods.CREATE_TASK_CONTACT},c.prototype._translateParams=function(e,t){switch(e){case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION:t.configuration=this._translateAgentConfiguration(t.configuration);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS:t.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(t.softphoneStreamStatistics);break;case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT:t.report=this._translateSoftphoneCallReport(t.report)}return this._requiresAuthenticationParam(e)&&(t.authentication={authToken:this.authToken}),t},c.prototype._translateAgentConfiguration=function(e){return{name:e.name,softphoneEnabled:e.softphoneEnabled,softphoneAutoAccept:e.softphoneAutoAccept,extension:e.extension,routingProfile:this._translateRoutingProfile(e.routingProfile),agentPreferences:e.agentPreferences}},c.prototype._translateRoutingProfile=function(e){return{name:e.name,routingProfileARN:e.routingProfileARN,defaultOutboundQueue:this._translateQueue(e.defaultOutboundQueue)}},c.prototype._translateQueue=function(e){return{queueARN:e.queueARN,name:e.name}},c.prototype._translateSoftphoneStreamStatistics=function(e){return e.forEach((function(e){"packetsCount"in e&&(e.packetCount=e.packetsCount,delete e.packetsCount)})),e},c.prototype._translateSoftphoneCallReport=function(e){return"handshakingTimeMillis"in e&&(e.handshakeTimeMillis=e.handshakingTimeMillis,delete e.handshakingTimeMillis),"preTalkingTimeMillis"in e&&(e.preTalkTimeMillis=e.preTalkingTimeMillis,delete e.preTalkingTimeMillis),"handshakingFailure"in e&&(e.handshakeFailure=e.handshakingFailure,delete e.handshakingFailure),"talkingTimeMillis"in e&&(e.talkTimeMillis=e.talkingTimeMillis,delete e.talkingTimeMillis),e.softphoneStreamStatistics=this._translateSoftphoneStreamStatistics(e.softphoneStreamStatistics),e},connect.ClientBase=t,connect.NullClient=n,connect.UpstreamConduitClient=r,connect.UpstreamConduitMasterClient=i,connect.AWSClient=c,connect.AgentAppClient=s}()},531:()=>{function e(e,n){var o="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!o){if(Array.isArray(e)||(o=function(e,n){if(e){if("string"==typeof e)return t(e,n);var o=Object.prototype.toString.call(e).slice(8,-1);return"Object"===o&&e.constructor&&(o=e.constructor.name),"Map"===o||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?t(e,n):void 0}}(e))||n&&e&&"number"==typeof e.length){o&&(e=o);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,c=!0,a=!1;return{s:function(){o=o.call(e)},n:function(){var e=o.next();return c=e.done,e},e:function(e){a=!0,s=e},f:function(){try{c||null==o.return||o.return()}finally{if(a)throw s}}}}function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n{!function(){connect=this.connect||{},this.connect=connect;var e="<>",t=connect.makeEnum(["acknowledge","ack_timeout","init","api_request","api_response","auth_fail","access_denied","close","configure","log","master_request","master_response","synchronize","terminate","terminated","send_logs","reload_agent_configuration","broadcast","api_metric","client_metric","softphone_stats","softphone_report","client_side_logs","server_bound_internal_log","mute","iframe_style","update_connected_ccps","outer_context_info","media_device_request","media_device_response"]),n=connect.makeNamespacedEnum("connect",["loginPopup","sendLogs","softphone","ringtone","metrics"]),o=connect.makeNamespacedEnum("agent",["init","update","refresh","routable","not_routable","pending","contact_pending","offline","error","softphone_error","websocket_connection_lost","websocket_connection_gained","state_change","acw","mute_toggle","local_media_stream_created","enqueued_next_state"]),r=connect.makeNamespacedEnum("webSocket",["init_failure","connection_open","connection_close","connection_error","connection_gain","connection_lost","subscription_update","subscription_failure","all_message","send","subscribe"]),i=connect.makeNamespacedEnum("contact",["init","refresh","destroyed","incoming","pending","connecting","connected","missed","acw","view","ended","error","accepted"]),s=connect.makeNamespacedEnum("taskList",["activate_channel_with_view_type"]),c=connect.makeNamespacedEnum("task",["created"]),a=connect.makeNamespacedEnum("connection",["session_init","ready_to_start_session"]),u=connect.makeNamespacedEnum("configuration",["configure","set_speaker_device","set_microphone_device","set_ringer_device","speaker_device_changed","microphone_device_changed","ringer_device_changed"]),l=connect.makeNamespacedEnum("voiceId",["update_domain_id"]),p=function(){};p.createRequest=function(e,t,n){return{event:e,requestId:connect.randomId(),method:t,params:n}},p.createResponse=function(e,t,n,o){return{event:e,requestId:t.requestId,data:n,err:o||null}};var h=function(e,t,n){this.subMap=e,this.id=connect.randomId(),this.eventName=t,this.f=n};h.prototype.unsubscribe=function(){this.subMap.unsubscribe(this.eventName,this.id)};var d=function(){this.subIdMap={},this.subEventNameMap={}};d.prototype.subscribe=function(e,t){var n=new h(this,e,t);this.subIdMap[n.id]=n;var o=this.subEventNameMap[e]||[];return o.push(n),this.subEventNameMap[e]=o,n},d.prototype.unsubscribe=function(e,t){connect.contains(this.subEventNameMap,e)&&(this.subEventNameMap[e]=this.subEventNameMap[e].filter((function(e){return e.id!==t})),this.subEventNameMap[e].length<1&&delete this.subEventNameMap[e]),connect.contains(this.subIdMap,t)&&delete this.subIdMap[t]},d.prototype.getAllSubscriptions=function(){return connect.values(this.subEventNameMap).reduce((function(e,t){return e.concat(t)}),[])},d.prototype.getSubscriptions=function(e){return this.subEventNameMap[e]||[]};var f=function(e){var t=e||{};this.subMap=new d,this.logEvents=t.logEvents||!1};f.prototype.subscribe=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.subMap.subscribe(e,t)},f.prototype.subscribeAll=function(t){return connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.subMap.subscribe(e,t)},f.prototype.getSubscriptions=function(e){return this.subMap.getSubscriptions(e)},f.prototype.trigger=function(t,n){connect.assertNotNull(t,"eventName");var o=this,r=this.subMap.getSubscriptions(e),i=this.subMap.getSubscriptions(t);this.logEvents&&t!==connect.EventType.LOG&&t!==connect.EventType.MASTER_RESPONSE&&t!==connect.EventType.API_METRIC&&t!==connect.EventType.SERVER_BOUND_INTERNAL_LOG&&connect.getLog().trace("Publishing event: %s",t).sendInternalLogToServer(),t.startsWith(connect.ContactEvents.ACCEPTED)&&n&&n.contactId&&!(n instanceof connect.Contact)&&(n=new connect.Contact(n.contactId)),r.concat(i).forEach((function(e){try{e.f(n||null,t,o)}catch(e){connect.getLog().error("'%s' event handler failed.",t).withException(e).sendInternalLogToServer()}}))},f.prototype.bridge=function(){var e=this;return function(t,n){e.trigger(n,t)}},f.prototype.unsubscribeAll=function(){this.subMap.getAllSubscriptions().forEach((function(e){e.unsubscribe()}))},connect.EventBus=f,connect.EventFactory=p,connect.EventType=t,connect.AgentEvents=o,connect.ConfigurationEvents=u,connect.ConnectionEvents=a,connect.ConnnectionEvents=a,connect.ContactEvents=i,connect.ChannelViewEvents=s,connect.TaskEvents=c,connect.VoiceIdEvents=l,connect.WebSocketEvents=r,connect.MasterTopics=n}()},42:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(t){var n={};function o(e){if(n[e])return n[e].exports;var r=n[e]={i:e,l:!1,exports:{}};return t[e].call(r.exports,r,r.exports,o),r.l=!0,r.exports}o.m=t,o.c=n,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.t=function(t,n){if(1&n&&(t=o(t)),8&n)return t;if(4&n&&"object"==e(t)&&t&&t.__esModule)return t;var r=Object.create(null);if(o.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&n&&"string"!=typeof t)for(var i in t)o.d(r,i,function(e){return t[e]}.bind(null,i));return r},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,"a",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p="",o(o.s=2)}([function(t,n,o){"use strict";var r=o(1),i="DEBUG",s="aws/subscribe",c="aws/heartbeat",a="disconnected";function u(t){return(u="function"==typeof Symbol&&"symbol"==e(Symbol.iterator)?function(t){return e(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":e(t)})(t)}var l={assertTrue:function(e,t){if(!e)throw new Error(t)},assertNotNull:function(e,t){return l.assertTrue(null!==e&&void 0!==u(e),Object(r.sprintf)("%s must be provided",t||"A value")),e},isNonEmptyString:function(e){return"string"==typeof e&&e.length>0},assertIsList:function(e,t){if(!Array.isArray(e))throw new Error(t+" is not an array")},isFunction:function(e){return!!(e&&e.constructor&&e.call&&e.apply)},isObject:function(e){return!("object"!==u(e)||null===e)},isString:function(e){return"string"==typeof e},isNumber:function(e){return"number"==typeof e}},p=new RegExp("^(wss://)\\w*");l.validWSUrl=function(e){return p.test(e)},l.getSubscriptionResponse=function(e,t,n){return{topic:e,content:{status:t?"success":"failure",topics:n}}},l.assertIsObject=function(e,t){if(!l.isObject(e))throw new Error(t+" is not an object!")},l.addJitter=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;t=Math.min(t,1);var n=Math.random()>.5?1:-1;return Math.floor(e+n*e*Math.random()*t)},l.isNetworkOnline=function(){return navigator.onLine},l.isNetworkFailure=function(e){return!(!e._debug||!e._debug.type)&&"NetworkingError"===e._debug.type};var h=l;function d(t){return(d="function"==typeof Symbol&&"symbol"==e(Symbol.iterator)?function(t){return e(t)}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":e(t)})(t)}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function g(e,t){return(g=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function m(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function v(e,t){for(var n=0;n=this._level}},{key:"hasClientLogger",value:function(){return null!==this._clientLogger}},{key:"getLogger",value:function(e){var t=e.prefix||"";return this._logsDestination===i?this.consoleLoggerWrapper:new T(t)}},{key:"updateLoggerConfig",value:function(e){var t=e||{};this._level=t.level||S.DEBUG,this._clientLogger=t.logger||null,this._logsDestination="NULL",t.debug&&(this._logsDestination=i),t.logger&&(this._logsDestination="CLIENT_LOGGER")}}]),e}(),C=function(){function e(){m(this,e)}return y(e,[{key:"debug",value:function(){}},{key:"info",value:function(){}},{key:"warn",value:function(){}},{key:"error",value:function(){}}]),e}(),T=function(e){function t(e){var n;return m(this,t),(n=function(e,t){return!t||"object"!==d(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}(this,f(t).call(this))).prefix=e||"",n}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&g(e,t)}(t,C),y(t,[{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:2e3;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.numAttempts=0,this.executor=t,this.hasActiveReconnection=!1,this.defaultRetry=n}var t,n;return t=e,(n=[{key:"retry",value:function(){var e=this;this.hasActiveReconnection||(this.hasActiveReconnection=!0,setTimeout((function(){e._execute()}),this._getDelay()))}},{key:"_execute",value:function(){this.hasActiveReconnection=!1,this.executor(),this.numAttempts++}},{key:"connected",value:function(){this.numAttempts=0}},{key:"_getDelay",value:function(){var e=Math.pow(2,this.numAttempts)*this.defaultRetry;return e<=3e4?e:3e4}}])&&_(t.prototype,n),e}();o.d(n,"a",(function(){return N}));var R=function(){var e=A.getLogger({}),t=h.isNetworkOnline(),n={primary:null,secondary:null},o={reconnectWebSocket:!0,websocketInitFailed:!1,exponentialBackOffTime:1e3,exponentialTimeoutHandle:null,lifeTimeTimeoutHandle:null,webSocketInitCheckerTimeoutId:null,connState:null},r={connectWebSocketRetryCount:0,connectionAttemptStartTime:null,noOpenConnectionsTimestamp:null},i={pendingResponse:!1,intervalHandle:null},u={initFailure:new Set,getWebSocketTransport:null,subscriptionUpdate:new Set,subscriptionFailure:new Set,topic:new Map,allMessage:new Set,connectionGain:new Set,connectionLost:new Set,connectionOpen:new Set,connectionClose:new Set},l={connConfig:null,promiseHandle:null,promiseCompleted:!0},p={subscribed:new Set,pending:new Set,subscriptionHistory:new Set},d={responseCheckIntervalId:null,requestCompleted:!0,reSubscribeIntervalId:null,consecutiveFailedSubscribeAttempts:0,consecutiveNoResponseRequest:0},f=new w((function(){B()})),g=new Set([s,"aws/unsubscribe",c]),m=setInterval((function(){if(t!==h.isNetworkOnline()){if(!(t=h.isNetworkOnline()))return void W(e.info("Network offline"));var n=T();t&&(!n||S(n,WebSocket.CLOSING)||S(n,WebSocket.CLOSED))&&(W(e.info("Network online, connecting to WebSocket server")),B())}}),250),v=function(t,n){t.forEach((function(t){try{t(n)}catch(t){W(e.error("Error executing callback",t))}}))},y=function(e){if(null===e)return"NULL";switch(e.readyState){case WebSocket.CONNECTING:return"CONNECTING";case WebSocket.OPEN:return"OPEN";case WebSocket.CLOSING:return"CLOSING";case WebSocket.CLOSED:return"CLOSED";default:return"UNDEFINED"}},E=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";W(e.debug("["+t+"] Primary WebSocket: "+y(n.primary)+" | Secondary WebSocket: "+y(n.secondary)))},S=function(e,t){return e&&e.readyState===t},b=function(e){return S(e,WebSocket.OPEN)},C=function(e){return null===e||void 0===e.readyState||S(e,WebSocket.CLOSED)},T=function(){return null!==n.secondary?n.secondary:n.primary},I=function(){return b(T())},_=function(){if(i.pendingResponse)return W(e.warn("Heartbeat response not received")),clearInterval(i.intervalHandle),i.pendingResponse=!1,void B();I()?(W(e.debug("Sending heartbeat")),T().send(F(c)),i.pendingResponse=!0):(W(e.warn("Failed to send heartbeat since WebSocket is not open")),E("sendHeartBeat"),B())},R=function(){o.exponentialBackOffTime=1e3,i.pendingResponse=!1,o.reconnectWebSocket=!0,clearTimeout(o.lifeTimeTimeoutHandle),clearInterval(i.intervalHandle),clearTimeout(o.exponentialTimeoutHandle),clearTimeout(o.webSocketInitCheckerTimeoutId)},N=function(){d.consecutiveFailedSubscribeAttempts=0,d.consecutiveNoResponseRequest=0,clearInterval(d.responseCheckIntervalId),clearInterval(d.reSubscribeIntervalId)},k=function(){r.connectWebSocketRetryCount=0,r.connectionAttemptStartTime=null,r.noOpenConnectionsTimestamp=null},O=function(){try{W(e.info("WebSocket connection established!")),E("webSocketOnOpen"),null!==o.connState&&o.connState!==a||v(u.connectionGain),o.connState="connected";var t=Date.now();v(u.connectionOpen,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,noOpenConnectionsTimestamp:r.noOpenConnectionsTimestamp,connectionEstablishedTime:t,timeToConnect:t-r.connectionAttemptStartTime,timeWithoutConnection:r.noOpenConnectionsTimestamp?t-r.noOpenConnectionsTimestamp:null}),k(),R(),T().openTimestamp=Date.now(),0===p.subscribed.size&&b(n.secondary)&&x(n.primary,"[Primary WebSocket] Closing WebSocket"),(p.subscribed.size>0||p.pending.size>0)&&(b(n.secondary)&&W(e.info("Subscribing secondary websocket to topics of primary websocket")),p.subscribed.forEach((function(e){p.subscriptionHistory.add(e),p.pending.add(e)})),p.subscribed.clear(),P()),_(),i.intervalHandle=setInterval(_,1e4);var s=1e3*l.connConfig.webSocketTransport.transportLifeTimeInSeconds;W(e.debug("Scheduling WebSocket manager reconnection, after delay "+s+" ms")),o.lifeTimeTimeoutHandle=setTimeout((function(){W(e.debug("Starting scheduled WebSocket manager reconnection")),B()}),s)}catch(t){W(e.error("Error after establishing WebSocket connection",t))}},L=function(t){E("webSocketOnError"),W(e.error("WebSocketManager Error, error_event: ",JSON.stringify(t))),B()},D=function(t){var o=JSON.parse(t.data);switch(o.topic){case s:if(W(e.debug("Subscription Message received from webSocket server",t.data)),d.requestCompleted=!0,d.consecutiveNoResponseRequest=0,"success"===o.content.status)d.consecutiveFailedSubscribeAttempts=0,o.content.topics.forEach((function(e){p.subscriptionHistory.delete(e),p.pending.delete(e),p.subscribed.add(e)})),0===p.subscriptionHistory.size?b(n.secondary)&&(W(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")),x(n.primary,"[Primary WebSocket] Closing WebSocket")):P(),v(u.subscriptionUpdate,o);else{if(clearInterval(d.reSubscribeIntervalId),++d.consecutiveFailedSubscribeAttempts,5===d.consecutiveFailedSubscribeAttempts)return v(u.subscriptionFailure,o),void(d.consecutiveFailedSubscribeAttempts=0);d.reSubscribeIntervalId=setInterval((function(){P()}),500)}break;case c:W(e.debug("Heartbeat response received")),i.pendingResponse=!1;break;default:if(o.topic){if(W(e.debug("Message received for topic "+o.topic)),b(n.primary)&&b(n.secondary)&&0===p.subscriptionHistory.size&&this===n.primary)return void W(e.warn("Ignoring Message for Topic "+o.topic+", to avoid duplicates"));if(0===u.allMessage.size&&0===u.topic.size)return void W(e.warn("No registered callback listener for Topic",o.topic));v(u.allMessage,o),u.topic.has(o.topic)&&v(u.topic.get(o.topic),o)}else o.message?W(e.warn("WebSocketManager Message Error",o)):W(e.warn("Invalid incoming message",o))}},P=function t(){if(d.consecutiveNoResponseRequest>3)return W(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")),void v(u.subscriptionFailure,h.getSubscriptionResponse(s,!1,Array.from(p.pending)));I()?(clearInterval(d.responseCheckIntervalId),T().send(F(s,{topics:Array.from(p.pending)})),d.requestCompleted=!1,d.responseCheckIntervalId=setInterval((function(){d.requestCompleted||(++d.consecutiveNoResponseRequest,t())}),1e3)):W(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open"))},x=function(t,n){S(t,WebSocket.CONNECTING)||S(t,WebSocket.OPEN)?t.close(1e3,n):W(e.warn("Ignoring WebSocket Close request, WebSocket State: "+y(t)))},M=function(e){x(n.primary,"[Primary] WebSocket "+e),x(n.secondary,"[Secondary] WebSocket "+e)},U=function(){r.connectWebSocketRetryCount++;var t=h.addJitter(o.exponentialBackOffTime,.3);Date.now()+t<=l.connConfig.urlConnValidTime?(W(e.debug("Scheduling WebSocket reinitialization, after delay "+t+" ms")),o.exponentialTimeoutHandle=setTimeout((function(){return V()}),t),o.exponentialBackOffTime*=2):(W(e.warn("WebSocket URL cannot be used to establish connection")),B())},q=function(t){R(),N(),W(e.error("WebSocket Initialization failed")),o.websocketInitFailed=!0,M("Terminating WebSocket Manager"),clearInterval(m),v(u.initFailure,{connectWebSocketRetryCount:r.connectWebSocketRetryCount,connectionAttemptStartTime:r.connectionAttemptStartTime,reason:t}),k()},F=function(e,t){return JSON.stringify({topic:e,content:t})},j=function(t){return!!(h.isObject(t)&&h.isObject(t.webSocketTransport)&&h.isNonEmptyString(t.webSocketTransport.url)&&h.validWSUrl(t.webSocketTransport.url)&&1e3*t.webSocketTransport.transportLifeTimeInSeconds>=3e5)||(W(e.error("Invalid WebSocket Connection Configuration",t)),!1)},B=function(){if(h.isNetworkOnline())if(o.websocketInitFailed)W(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else{if(l.promiseCompleted)return R(),W(e.info("Fetching new WebSocket connection configuration")),r.connectionAttemptStartTime=r.connectionAttemptStartTime||Date.now(),l.promiseCompleted=!1,l.promiseHandle=u.getWebSocketTransport(),l.promiseHandle.then((function(t){return l.promiseCompleted=!0,W(e.debug("Successfully fetched webSocket connection configuration",t)),j(t)?(l.connConfig=t,l.connConfig.urlConnValidTime=Date.now()+85e3,f.connected(),V()):(q("Invalid WebSocket connection configuration: "+t),{webSocketConnectionFailed:!0})}),(function(t){return l.promiseCompleted=!0,W(e.error("Failed to fetch webSocket connection configuration",t)),h.isNetworkFailure(t)?(W(e.info("Retrying fetching new WebSocket connection configuration")),f.retry()):q("Failed to fetch webSocket connection configuration: "+JSON.stringify(t)),{webSocketConnectionFailed:!0}}));W(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored"))}else W(e.info("Network offline, ignoring this getWebSocketConnConfig request"))},V=function(){if(o.websocketInitFailed)return W(e.info("web-socket initializing had failed, aborting re-init")),{webSocketConnectionFailed:!0};if(!h.isNetworkOnline())return W(e.warn("System is offline aborting web-socket init")),{webSocketConnectionFailed:!0};W(e.info("Initializing Websocket Manager")),E("initWebSocket");try{if(j(l.connConfig)){var t=null;return b(n.primary)?(W(e.debug("Primary Socket connection is already open")),S(n.secondary,WebSocket.CONNECTING)||(W(e.debug("Establishing a secondary web-socket connection")),n.secondary=H()),t=n.secondary):(S(n.primary,WebSocket.CONNECTING)||(W(e.debug("Establishing a primary web-socket connection")),n.primary=H()),t=n.primary),o.webSocketInitCheckerTimeoutId=setTimeout((function(){b(t)||U()}),1e3),{webSocketConnectionFailed:!1}}}catch(t){return W(e.error("Error Initializing web-socket-manager",t)),q("Failed to initialize new WebSocket: "+t.message),{webSocketConnectionFailed:!0}}},H=function(){var t=new WebSocket(l.connConfig.webSocketTransport.url);return t.addEventListener("open",O),t.addEventListener("message",D),t.addEventListener("error",L),t.addEventListener("close",(function(i){return function(t,i){W(e.info("Socket connection is closed",t)),E("webSocketOnClose before-cleanup"),v(u.connectionClose,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),C(n.primary)&&(n.primary=null),C(n.secondary)&&(n.secondary=null),o.reconnectWebSocket&&(b(n.primary)||b(n.secondary)?C(n.primary)&&b(n.secondary)&&(W(e.info("[Primary] WebSocket Cleanly Closed")),n.primary=n.secondary,n.secondary=null):(W(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")),o.connState===a?W(e.info("Ignoring connectionLost callback invocation")):(v(u.connectionLost,{openTimestamp:i.openTimestamp,closeTimestamp:Date.now(),connectionDuration:Date.now()-i.openTimestamp,code:t.code,reason:t.reason}),r.noOpenConnectionsTimestamp=Date.now()),o.connState=a,B()),E("webSocketOnClose after-cleanup"))}(i,t)})),t},W=function(e){return e&&"function"==typeof e.sendInternalLogToServer&&e.sendInternalLogToServer(),e};this.init=function(t){if(h.assertTrue(h.isFunction(t),"transportHandle must be a function"),null===u.getWebSocketTransport)return u.getWebSocketTransport=t,B();W(e.warn("Web Socket Manager was already initialized"))},this.onInitFailure=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.initFailure.add(e),o.websocketInitFailed&&e(),function(){return u.initFailure.delete(e)}},this.onConnectionOpen=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionOpen.add(e),function(){return u.connectionOpen.delete(e)}},this.onConnectionClose=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionClose.add(e),function(){return u.connectionClose.delete(e)}},this.onConnectionGain=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionGain.add(e),I()&&e(),function(){return u.connectionGain.delete(e)}},this.onConnectionLost=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.connectionLost.add(e),o.connState===a&&e(),function(){return u.connectionLost.delete(e)}},this.onSubscriptionUpdate=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.subscriptionUpdate.add(e),function(){return u.subscriptionUpdate.delete(e)}},this.onSubscriptionFailure=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.subscriptionFailure.add(e),function(){return u.subscriptionFailure.delete(e)}},this.onMessage=function(e,t){return h.assertNotNull(e,"topicName"),h.assertTrue(h.isFunction(t),"cb must be a function"),u.topic.has(e)?u.topic.get(e).add(t):u.topic.set(e,new Set([t])),function(){return u.topic.get(e).delete(t)}},this.onAllMessage=function(e){return h.assertTrue(h.isFunction(e),"cb must be a function"),u.allMessage.add(e),function(){return u.allMessage.delete(e)}},this.subscribeTopics=function(e){h.assertNotNull(e,"topics"),h.assertIsList(e),e.forEach((function(e){p.subscribed.has(e)||p.pending.add(e)})),d.consecutiveNoResponseRequest=0,P()},this.sendMessage=function(t){if(h.assertIsObject(t,"payload"),void 0===t.topic||g.has(t.topic))W(e.warn("Cannot send message, Invalid topic",t));else{try{t=JSON.stringify(t)}catch(n){return void W(e.warn("Error stringify message",t))}I()?T().send(t):W(e.warn("Cannot send message, web socket connection is not open"))}},this.closeWebSocket=function(){R(),N(),o.reconnectWebSocket=!1,clearInterval(m),M("User request to close WebSocket")},this.terminateWebSocketManager=q},N={create:function(){return new R},setGlobalConfig:function(e){var t=e.loggerConfig;A.updateLoggerConfig(t)},LogLevel:S,Logger:E}},function(t,n,o){var r;!function(){"use strict";var i={not_string:/[^s]/,not_bool:/[^t]/,not_type:/[^T]/,not_primitive:/[^v]/,number:/[diefg]/,numeric_arg:/[bcdiefguxX]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[+-]/};function s(t){return function(t,n){var o,r,c,a,u,l,p,h,d,f=1,g=t.length,m="";for(r=0;r=0),a.type){case"b":o=parseInt(o,10).toString(2);break;case"c":o=String.fromCharCode(parseInt(o,10));break;case"d":case"i":o=parseInt(o,10);break;case"j":o=JSON.stringify(o,null,a.width?parseInt(a.width):0);break;case"e":o=a.precision?parseFloat(o).toExponential(a.precision):parseFloat(o).toExponential();break;case"f":o=a.precision?parseFloat(o).toFixed(a.precision):parseFloat(o);break;case"g":o=a.precision?String(Number(o.toPrecision(a.precision))):parseFloat(o);break;case"o":o=(parseInt(o,10)>>>0).toString(8);break;case"s":o=String(o),o=a.precision?o.substring(0,a.precision):o;break;case"t":o=String(!!o),o=a.precision?o.substring(0,a.precision):o;break;case"T":o=Object.prototype.toString.call(o).slice(8,-1).toLowerCase(),o=a.precision?o.substring(0,a.precision):o;break;case"u":o=parseInt(o,10)>>>0;break;case"v":o=o.valueOf(),o=a.precision?o.substring(0,a.precision):o;break;case"x":o=(parseInt(o,10)>>>0).toString(16);break;case"X":o=(parseInt(o,10)>>>0).toString(16).toUpperCase()}i.json.test(a.type)?m+=o:(!i.number.test(a.type)||h&&!a.sign?d="":(d=h?"+":"-",o=o.toString().replace(i.sign,"")),l=a.pad_char?"0"===a.pad_char?"0":a.pad_char.charAt(1):" ",p=a.width-(d+o).length,u=a.width&&p>0?l.repeat(p):"",m+=a.align?d+o+u:"0"===l?d+u+o:u+d+o)}return m}(function(e){if(a[e])return a[e];for(var t,n=e,o=[],r=0;n;){if(null!==(t=i.text.exec(n)))o.push(t[0]);else if(null!==(t=i.modulo.exec(n)))o.push("%");else{if(null===(t=i.placeholder.exec(n)))throw new SyntaxError("[sprintf] unexpected placeholder");if(t[2]){r|=1;var s=[],c=t[2],u=[];if(null===(u=i.key.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(s.push(u[1]);""!==(c=c.substring(u[0].length));)if(null!==(u=i.key_access.exec(c)))s.push(u[1]);else{if(null===(u=i.index_access.exec(c)))throw new SyntaxError("[sprintf] failed to parse named argument key");s.push(u[1])}t[2]=s}else r|=2;if(3===r)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");o.push({placeholder:t[0],param_no:t[1],keys:t[2],sign:t[3],pad_char:t[4],align:t[5],width:t[6],precision:t[7],type:t[8]})}n=n.substring(t[0].length)}return a[e]=o}(t),arguments)}function c(e,t){return s.apply(null,[e].concat(t||[]))}var a=Object.create(null);n.sprintf=s,n.vsprintf=c,"undefined"!=typeof window&&(window.sprintf=s,window.vsprintf=c,void 0===(r=function(){return{sprintf:s,vsprintf:c}}.call(n,o,n,t))||(t.exports=r))}()},function(e,t,n){"use strict";n.r(t),function(e){n.d(t,"WebSocketManager",(function(){return r}));var o=n(0);e.connect=e.connect||{},connect.WebSocketManager=o.a;var r=o.a}.call(this,n(3))},function(t,n){var o;o=function(){return this}();try{o=o||new Function("return this")()}catch(t){"object"==("undefined"==typeof window?"undefined":e(window))&&(o=window)}t.exports=o}])},312:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect;var n={TEST:"TEST",TRACE:"TRACE",DEBUG:"DEBUG",INFO:"INFO",LOG:"LOG",WARN:"WARN",ERROR:"ERROR",CRITICAL:"CRITICAL"},o={CCP:"ccp",SOFTPHONE:"softphone",CHAT:"chat",TASK:"task"},r={TEST:0,TRACE:10,DEBUG:20,INFO:30,LOG:40,WARN:50,ERROR:100,CRITICAL:200},i={TRACE:function(e){console.info(e)},DEBUG:function(e){console.info(e)},INFO:function(e){console.info(e)},LOG:function(e){console.log(e)},TEST:function(e){console.log(e)},WARN:function(e){console.warn(e)},ERROR:function(e){console.error(e)},CRITICAL:function(e){console.error(e)}},s=function(e){var t,n,r=Array.prototype.slice.call(e,0),i=r.shift();return function(e){return-1!==Object.values(o).indexOf(e)}(i)?(n=i,t=r.shift()):(t=i,n=o.CCP),{format:t,component:n,args:r}},c=function(e,t,n,o){this.component=e,this.level=t,this.text=n,this.time=new Date,this.exception=null,this.objects=[],this.line=0,this.agentResourceId=null;try{connect.agent.initialized&&(this.agentResourceId=(new connect.Agent)._getResourceId())}catch(e){console.log("Issue finding agentResourceId: ",e)}this.loggerId=o};c.fromObject=function(e){var t=new c(o.CCP,e.level,e.text,e.loggerId);return"[object Date]"===Object.prototype.toString.call(e.time)?t.time=new Date(e.time.getTime()):"number"==typeof e.time?t.time=new Date(e.time):"string"==typeof e.time?t.time=Date.parse(e.time):t.time=new Date,t.exception=e.exception,t.objects=e.objects,t};var a=function t(n){var o=/AuthToken.*\=/g;n&&"object"===e(n)&&Object.keys(n).forEach((function(r){"object"===e(n[r])?t(n[r]):"string"==typeof n[r]&&("url"===r||"text"===r?n[r]=n[r].replace(o,"[redacted]"):"quickConnectName"===r&&(n[r]="[redacted]"))}))},u=function(e){this.type=e instanceof Error?e.name:e.code||Object.prototype.toString.call(e),this.message=e.message,this.stack=e.stack?e.stack.split("\n"):[]};c.prototype.toString=function(){return connect.sprintf("[%s] [%s] [%s]: %s",this.getTime()&&this.getTime().toISOString?this.getTime().toISOString():"???",this.getLevel(),this.getAgentResourceId(),this.getText())},c.prototype.getTime=function(){return this.time},c.prototype.getAgentResourceId=function(){return this.agentResourceId},c.prototype.getLevel=function(){return this.level},c.prototype.getText=function(){return this.text},c.prototype.getComponent=function(){return this.component},c.prototype.withException=function(e){return this.exception=new u(e),this},c.prototype.withObject=function(e){var t=connect.deepcopy(e);return a(t),this.objects.push(t),this},c.prototype.withCrossOriginEventObject=function(e){var t=connect.deepcopyCrossOriginEvent(e);return a(t),this.objects.push(t),this},c.prototype.sendInternalLogToServer=function(){return connect.getLog()._serverBoundInternalLogs.push(this),this};var l=function(){this._logs=[],this._rolledLogs=[],this._logsToPush=[],this._serverBoundInternalLogs=[],this._echoLevel=r.INFO,this._logLevel=r.INFO,this._lineCount=0,this._logRollInterval=0,this._logRollTimer=null,this._loggerId=(new Date).getTime()+"-"+Math.random().toString(36).slice(2),this.setLogRollInterval(18e5),this._startLogIndexToPush=0};l.prototype.setLogRollInterval=function(e){var n=this;this._logRollTimer&&e===this._logRollInterval?this.warn("Logger is already set to the given interval: %d",this._logRollInterval):(this._logRollTimer&&t.clearInterval(this._logRollTimer),this._logRollInterval=e,this._logRollTimer=t.setInterval((function(){this._rolledLogs=this._logs,this._logs=[],this._startLogIndexToPush=0,n.info("Log roll interval occurred.")}),this._logRollInterval))},l.prototype.setLogLevel=function(e){if(!(e in r))throw new Error("Unknown logging level: "+e);this._logLevel=r[e]},l.prototype.setEchoLevel=function(e){if(!(e in r))throw new Error("Unknown logging level: "+e);this._echoLevel=r[e]},l.prototype.write=function(e,t,n){var o=new c(e,t,n,this.getLoggerId());return a(o),this.addLogEntry(o),o},l.prototype.addLogEntry=function(e){a(e),this._logs.push(e),o.SOFTPHONE===e.component&&this._logsToPush.push(e),e.level in r&&r[e.level]>=this._logLevel&&(r[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.sendInternalLogEntryToServer=function(e){this._serverBoundInternalLogs.push(e),e.level in r&&r[e.level]>=this._logLevel&&(r[e.level]>=this._echoLevel&&i[e.getLevel()](e.toString()),e.line=this._lineCount++)},l.prototype.clearObjects=function(){for(var e=0;e=s._logLevel})));var a=new t.Blob([JSON.stringify(c,void 0,4)],["text/plain"]),u=document.createElement("a");o=o||"agent-log",u.href=t.URL.createObjectURL(a),u.download=o+".txt",document.body.appendChild(u),u.click(),document.body.removeChild(u)},l.prototype.scheduleUpstreamLogPush=function(e){connect.upstreamLogPushScheduled||(connect.upstreamLogPushScheduled=!0,t.setInterval(connect.hitch(this,this.reportMasterLogsUpStream,e),5e3))},l.prototype.reportMasterLogsUpStream=function(e){var t=this._logsToPush.slice();this._logsToPush=[],connect.ifMaster(connect.MasterTopics.SEND_LOGS,(function(){t.length>0&&e.sendUpstream(connect.EventType.SEND_LOGS,t)}))},l.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush=function(e){t.setInterval(connect.hitch(this,this.pushOuterContextCCPserverBoundLogsUpstream,e),1e3)},l.prototype.scheduleUpstreamOuterContextCCPLogsPush=function(e){t.setInterval(connect.hitch(this,this.pushOuterContextCCPLogsUpstream,e),1e3)},l.prototype.pushOuterContextCCPserverBoundLogsUpstream=function(e){if(this._serverBoundInternalLogs.length>0){for(var t=0;t500?e=this._serverBoundInternalLogs.splice(0,500):(e=this._serverBoundInternalLogs,this._serverBoundInternalLogs=[]),connect.publishClientSideLogs(e))};var p=function e(n){l.call(this),this.conduit=n,t.setInterval(connect.hitch(this,this._pushLogsDownstream),e.LOG_PUSH_INTERVAL),t.clearInterval(this._logRollTimer),this._logRollTimer=null};p.LOG_PUSH_INTERVAL=1e3,(p.prototype=Object.create(l.prototype)).constructor=p,p.prototype.pushLogsDownstream=function(e){var t=this;e.forEach((function(e){t.conduit.sendDownstream(connect.EventType.LOG,e)}))},p.prototype._pushLogsDownstream=function(){var e=this;this._logs.forEach((function(t){e.conduit.sendDownstream(connect.EventType.LOG,t)})),this._logs=[];for(var t=0;t{!function(){connect=this.connect||{},this.connect=connect,connect.ChatMediaController=function(e,t){var n=connect.getLog(),o=connect.LogComponent.CHAT,r=function(t,n){connect.publishMetric({name:t,contactId:e.contactId,data:n||e})},i=function(e){e.onConnectionBroken((function(e){n.error(o,"Chat Session connection broken").withException(e).sendInternalLogToServer(),r("Chat Session connection broken",e)})),e.onConnectionEstablished((function(e){n.info(o,"Chat Session connection established").withObject(e).sendInternalLogToServer(),r("Chat Session connection established",e)}))};return{get:function(){return function(){r("Chat media controller init",e.contactId),n.info(o,"Chat media controller init").withObject(e).sendInternalLogToServer(),connect.ChatSession.setGlobalConfig({loggerConfig:{logger:n},region:t.region});var s=connect.ChatSession.create({chatDetails:e,type:"AGENT",websocketManager:connect.core.getWebSocketManager()});return i(s),s.connect().then((function(t){return n.info(o,"Chat Session Successfully established for contactId %s",e.contactId).sendInternalLogToServer(),r("Chat Session Successfully established",e.contactId),s})).catch((function(t){throw n.error(o,"Chat Session establishement failed for contact %s",e.contactId).withException(t).sendInternalLogToServer(),r("Chat Session establishement failed",e.contactId,t),t}))}()}}}}()},7:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.MediaFactory=function(e){var t={},n=new Set,o=connect.getLog(),r=connect.LogComponent.CHAT,i=connect.merge({},e)||{};i.region=i.region||"us-west-2";var s=function(e){t[e]&&!n.has(e)&&(o.info(r,"Destroying mediaController for %s",e),n.add(e),t[e].then((function(){"function"==typeof controller.cleanUp&&controller.cleanUp(),delete t[e],n.delete(e)})).catch((function(){delete t[e],n.delete(e)})))};return{get:function(e){return function(e){return e.isActive()}(e)?function(e){var n=e.getConnectionId();if(!e.getMediaInfo())return o.error(r,"Media info does not exist for a media type %s",e.getMediaType()).withObject(e).sendInternalLogToServer(),Promise.reject("Media info does not exist for this connection");if(t[n])return t[n];switch(o.info(r,"media controller of type %s init",e.getMediaType()).withObject(e).sendInternalLogToServer(),e.getMediaType()){case connect.MediaType.CHAT:return t[n]=new connect.ChatMediaController(e.getMediaInfo(),i).get();case connect.MediaType.SOFTPHONE:return t[n]=new connect.SoftphoneMediaController(e.getMediaInfo()).get();case connect.MediaType.TASK:return t[n]=new connect.TaskMediaController(e.getMediaInfo()).get();default:return o.error(r,"Unrecognized media type %s ",e.getMediaType()).sendInternalLogToServer(),Promise.reject()}}(e):(s(e.getConnectionId()),Promise.reject("Media Controller is no longer available for this connection"))},destroy:s}}}()},6:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.SoftphoneMediaController=function(e){return{get:function(){return Promise.resolve(e)}}}}()},487:()=>{!function(){connect=this.connect||{},this.connect=connect,connect.TaskMediaController=function(e){var t=connect.getLog(),n=connect.LogComponent.TASK,o=function(t,n){connect.publishMetric({name:t,contactId:e.contactId,data:n||e})},r=function(e){e.onConnectionBroken((function(e){t.error(n,"Task Session connection broken").withException(e),o("Task Session connection broken",e)})),e.onConnectionEstablished((function(e){t.info(n,"Task Session connection established").withObject(e),o("Task Session connection established",e)}))};return{get:function(){return function(){o("Task media controller init",e.contactId),t.info(n,"Task media controller init").withObject(e);var i=connect.TaskSession.create({contactId:e.contactId,initialContactId:e.initialContactId,websocketManager:connect.core.getWebSocketManager()});return r(i),i.connect().then((function(){return t.info(n,"Task Session Successfully established for contactId %s",e.contactId),o("Task Session Successfully established",e.contactId),i})).catch((function(r){throw t.error(n,"Task Session establishement failed for contact %s",e.contactId).withException(r),o("Chat Session establishement failed",e.contactId,r),r}))}()}}}}()},743:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}function t(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function n(e){for(var n=1;n2&&void 0!==arguments[2]?arguments[2]:{};t.assertNotNull(e,"ccpUrl"),t.assertNotNull(o,"container"),a=o,c=e,function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.custom=e.custom||{},(s=n(n(n({},i),e),{},{custom:n(n({},i.custom),e.custom)})).canRequest=!("false"===s.canRequest||!1===s.canRequest)}(r),t.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(e," - ").concat(s.canRequest?"Proceeding with requesting storage access":"user has opted out, skipping request storage access")).withObject(s)},setupRequestHandlers:function(e){var n=e.onGrant;o&&o.unsubscribe(),o=v({onInit:function(e){console.log("%c[INIT]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onInit] callback executed").withObject(null==e?void 0:e.data),null!=e&&e.data.hasAccess||!h()||p().show()},onDeny:function(){console.log("%c[DENIED]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onDeny] callback executed"),h()&&p().show()},onGrant:function(){console.log("%c[Granted]","background:lime; color: black; font-size:large"),t.getLog().info("[StorageAccess][onGrant] callback executed"),h()&&p().hide(),u||(n(),u=!0)}})},getRequestStorageAccessUrl:function(){if(!c)throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first");if(d(c))return f(c);if(g(c))return t.getLog().info("[StorageAccess] [CCP] Local testing"),"".concat(c).concat(r);if(s.instanceUrl&&d(s.instanceUrl))return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(s.instanceUrl)),f(s.instanceUrl);if(s.instanceUrl&&g(s.instanceUrl))return t.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"),"".concat(s.instanceUrl).concat(r);throw t.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"),new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL")},storageAccessEvents:l,resetStorageAccessState:function(){s={},c="",a=null},getStorageAccessParams:function(){return s},onRequest:v,request:function(){t.core._getCCPIframe().contentWindow.postMessage({event:l.REQUEST,data:n(n({},s),{},{landat:m()})},"*")}})}()},555:()=>{!function(){var e=this,t=e.connect||{};e.connect=t,e.lily=t;var n=function(n){var o=this;if(this._prevContactId=null,t.assertNotNull(n,"ringtoneConfig"),!n.ringtoneUrl)throw new Error("ringtoneUrl is required!");e.Audio&&void 0!==e.Promise?this._playableAudioPromise=new Promise((function(e,t){o._audio=new Audio(n.ringtoneUrl),o._audio.loop=!0,o._audio.addEventListener("canplay",(function(){o._audioPlayable=!0,e(o._audio)}))})):(this._audio=null,t.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer()),o._driveRingtone()};n.prototype._driveRingtone=function(){throw new Error("Not implemented.")},n.prototype._startRingtone=function(e){this._audio&&(this._audio.play().catch((function(n){this._publishTelemetryEvent("Ringtone Playback Failure",e),t.getLog().error("Ringtone Playback Failure").sendInternalLogToServer()})),this._publishTelemetryEvent("Ringtone Start",e),t.getLog().info("Ringtone Start").sendInternalLogToServer())},n.prototype._stopRingtone=function(e){this._audio&&(this._audio.pause(),this._audio.currentTime=0,this._publishTelemetryEvent("Ringtone Stop",e),t.getLog().info("Ringtone Stop").sendInternalLogToServer())},n.prototype.stopRingtone=function(){this._stopRingtone()},n.prototype._ringtoneSetup=function(e){var n=this;t.ifMaster(t.MasterTopics.RINGTONE,(function(){n._startRingtone(e),n._prevContactId=e.getContactId(),e.onConnected(lily.hitch(n,n._stopRingtone)),e.onAccepted(lily.hitch(n,n._stopRingtone)),e.onEnded(lily.hitch(n,n._stopRingtone)),e.onRefresh((function(e){e.getStatus().type!==t.ContactStatusType.CONNECTING&&e.getStatus().type!==t.ContactStatusType.INCOMING&&n._stopRingtone()}))}))},n.prototype._publishTelemetryEvent=function(e,n){n&&n.getContactId()&&t.publishMetric({name:e,contactId:n.getContactId()})},n.prototype.setOutputDevice=function(t){return this._playableAudioPromise?Promise.race([this._playableAudioPromise,new Promise((function(t,n){e.setTimeout((function(){n("Timed out waiting for playable audio")}),3e3)}))]).then((function(e){return e?e.setSinkId?Promise.resolve(e.setSinkId(t)):Promise.reject("Not supported"):Promise.reject("No audio found")})):e.Promise?Promise.reject("Not eligible ringtone owner"):void 0};var o=function(e){n.call(this,e)};(o.prototype=Object.create(n.prototype)).constructor=o,o.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.VOICE&&n.isSoftphoneCall()&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Ringtone Connecting",n),t.getLog().info("Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)})),(new t.Agent).getContacts().forEach((function(e){e.getStatus().type===t.ContactStatusType.CONNECTING&&n(e)}))};var r=function(e){n.call(this,e)};(r.prototype=Object.create(n.prototype)).constructor=r,r.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.CHAT&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Chat Ringtone Connecting",n),t.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var i=function(e){n.call(this,e)};(i.prototype=Object.create(n.prototype)).constructor=i,i.prototype._driveRingtone=function(){var e=this,n=function(n){n.getType()===lily.ContactType.TASK&&n.isInbound()&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Task Ringtone Connecting",n),t.getLog().info("Task Ringtone Connecting").sendInternalLogToServer())};t.contact((function(e){e.onConnecting(n)}))};var s=function(e){n.call(this,e)};(s.prototype=Object.create(n.prototype)).constructor=s,s.prototype._driveRingtone=function(){var e=this;t.contact((function(n){n.onIncoming((function(){n.getType()===lily.ContactType.QUEUE_CALLBACK&&(e._ringtoneSetup(n),e._publishTelemetryEvent("Callback Ringtone Connecting",n),t.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer())}))}))},t.VoiceRingtoneEngine=o,t.ChatRingtoneEngine=r,t.TaskRingtoneEngine=i,t.QueueCallbackRingtoneEngine=s}()},960:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect,t.ccpVersion="V2";var n={};n[connect.SoftphoneCallType.AUDIO_ONLY]="Audio",n[connect.SoftphoneCallType.VIDEO_ONLY]="Video",n[connect.SoftphoneCallType.AUDIO_VIDEO]="AudioVideo",n[connect.SoftphoneCallType.NONE]="None";var o="audio_input",r="audio_output";({})[connect.ContactType.VOICE]="Voice";var i=[],s={},c={},a=null,u=null,l=null,p=connect.SoftphoneErrorTypes,h={},d=connect.randomId(),f=function(e){return new Promise((function(t,n){connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT,e,{success:function(e){t(e.softphoneTransport.softphoneMediaConnections)},failure:function(e){e.message&&e.message.includes("SoftphoneConnectionLimitBreachedException")&&_("multiple_softphone_active_sessions","Number of active sessions are more then allowed limit.",""),n(Error("requestIceAccess failed"))},authFailure:function(){n(Error("Authentication failed while requestIceAccess"))},accessDenied:function(){n(Error("Access Denied while requestIceAccess"))}})}))},g=function(e){var t=connect.core.getUpstream(),n=e.getAgentConnection();if(n){var o=n.getSoftphoneMediaInfo();o?!0===o.autoAccept?(l.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(),t.sendUpstream(connect.EventType.BROADCAST,{event:connect.ContactEvents.ACCEPTED,data:new connect.Contact(e.contactId)}),t.sendUpstream(connect.EventType.BROADCAST,{event:connect.core.getContactEventName(connect.ContactEvents.ACCEPTED,e.contactId),data:new connect.Contact(e.contactId)})):l.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer():l.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer()}else l.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer()},m=function(){connect.core.getEventBus().subscribe(connect.EventType.MUTE,S)},v=function(){connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE,b)},y=function(){connect.core.getEventBus().subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE,C)},E=function(e){delete h[e],connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.MUTE_TOGGLE,data:{muted:!1}})},S=function(e){var t;if(0!==connect.keys(h).length){for(var n in e&&void 0!==e.mute&&(t=e.mute),h)if(h.hasOwnProperty(n)){var o=h[n].stream;if(o){var r=o.getAudioTracks()[0];void 0!==t?(r.enabled=!t,h[n].muted=t,t?l.info("Agent has muted the contact, connectionId - "+n).sendInternalLogToServer():l.info("Agent has unmuted the contact, connectionId - "+n).sendInternalLogToServer()):t=h[n].muted||!1}}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.MUTE_TOGGLE,data:{muted:t}})}},b=function(e){if(0!==connect.keys(h).length&&e&&e.deviceId){var t=e.deviceId,n=document.getElementById("remote-audio");try{l.info("Trying to set speaker to device "+t),n&&"function"==typeof n.setSinkId&&n.setSinkId(t)}catch(e){l.error("Failed to set speaker to device "+t)}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED,data:{deviceId:t}})}},C=function(e){if(0!==connect.keys(h).length&&e&&e.deviceId){var t=e.deviceId,n=connect.core.getSoftphoneManager();try{navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:t}}}).then((function(e){var t=e.getAudioTracks()[0];for(var o in h)h.hasOwnProperty(o)&&(h[o].stream,n.getSession(o)._pc.getSenders()[0].replaceTrack(t).then((function(){n.replaceLocalMediaTrack(o,t)})))}))}catch(e){l.error("Failed to set microphone device "+t)}connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED,data:{deviceId:t}})}},T=function(e,t){if(t===connect.RTCErrors.ICE_COLLECTION_TIMEOUT){for(var n="\n",o=0;o0?n.success(e):n.failure(p.MICROPHONE_NOT_SHARED)}),(function(e){n.failure(p.MICROPHONE_NOT_SHARED)})),r}n.failure(p.UNSUPPORTED_BROWSER)},_=function(e,t,n){l.error("Softphone error occurred : ",e,t||"").sendInternalLogToServer(),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.SOFTPHONE_ERROR,data:new connect.SoftphoneError(e,t,n)})},w=function(e,t){R("Softphone Session Failed",e,{failedReason:t})},R=function(e,t,n){t&&connect.publishMetric({name:e,contactId:t,data:n})},N=function(e,t,n){R(e,t,[{name:"AgentConnectionId",value:n}]),l.info("Publish multiple session error metrics",e,"contactId "+t,"agent connectionId "+n).sendInternalLogToServer()},k=function(){return!!(connect.isOperaBrowser()&&connect.getOperaBrowserVersion()>17)||!!(connect.isChromeBrowser()&&connect.getChromeBrowserVersion()>22)||!!(connect.isFirefoxBrowser()&&connect.getFirefoxBrowserVersion()>21)},O=function(e){var t=i.slice();i=[],t.length>0&&e.sendSoftphoneMetrics(t,{success:function(){l.info("sendSoftphoneMetrics success"+JSON.stringify(t)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneMetrics failed.").withObject(e).sendInternalLogToServer()}})},L=function(e){a=window.setInterval((function(){e.getUserAudioStats().then((function(e){var t=s;s=e,i.push(x(s,t,o))}),(function(e){l.debug("Failed to get user audio stats.",e).sendInternalLogToServer()})),e.getRemoteAudioStats().then((function(e){var t=c;c=e,i.push(x(c,t,r))}),(function(e){l.debug("Failed to get remote audio stats.",e).sendInternalLogToServer()}))}),1e3)},D=function(e){u=window.setInterval((function(){O(e)}),3e4)},P=function(){s=null,c=null,i=[],a=null,u=null},x=function(e,t,n){if(t&&e){var o=e.packetsLost>t.packetsLost?e.packetsLost-t.packetsLost:0,r=e.packetsCount>t.packetsCount?e.packetsCount-t.packetsCount:0;return new q(e.timestamp,o,r,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)}return new q(e.timestamp,e.packetsLost,e.packetsCount,n,e.audioLevel,e.jbMilliseconds,e.rttMilliseconds)},M=function(e){return null!==e&&window.clearInterval(e),null},U=function(e,t){a=M(a),u=M(u),function(e,t,n,i){t.streamStats=[F(n,o),F(i,r)];var s={callStartTime:t.sessionStartTime,callEndTime:t.sessionEndTime,gumTimeMillis:t.gumTimeMillis,initializationTimeMillis:t.initializationTimeMillis,iceCollectionTimeMillis:t.iceCollectionTimeMillis,signallingConnectTimeMillis:t.signallingConnectTimeMillis,handshakingTimeMillis:t.handshakingTimeMillis,preTalkingTimeMillis:t.preTalkingTimeMillis,talkingTimeMillis:t.talkingTimeMillis,cleanupTimeMillis:t.cleanupTimeMillis,iceCollectionFailure:t.iceCollectionFailure,signallingConnectionFailure:t.signallingConnectionFailure,handshakingFailure:t.handshakingFailure,gumOtherFailure:t.gumOtherFailure,gumTimeoutFailure:t.gumTimeoutFailure,createOfferFailure:t.createOfferFailure,setLocalDescriptionFailure:t.setLocalDescriptionFailure,userBusyFailure:t.userBusyFailure,invalidRemoteSDPFailure:t.invalidRemoteSDPFailure,noRemoteIceCandidateFailure:t.noRemoteIceCandidateFailure,setRemoteDescriptionFailure:t.setRemoteDescriptionFailure,softphoneStreamStatistics:t.streamStats};e.sendSoftphoneReport(s,{success:function(){l.info("sendSoftphoneReport success"+JSON.stringify(s)).sendInternalLogToServer()},failure:function(e){l.error("sendSoftphoneReport failed.").withObject(e).sendInternalLogToServer()}})}(e,t,F(s,o),F(c,r)),O(e)},q=function(e,t,n,o,r,i,s){this.softphoneStreamType=o,this.timestamp=e,this.packetsLost=t,this.packetsCount=n,this.audioLevel=r,this.jitterBufferMillis=i,this.roundTripTimeMillis=s},F=function(e,t){return new q((e=e||{}).timestamp,e.packetsLost,e.packetsCount,t,e.audioLevel)},j=function(e){this._originalLogger=e;var t=this;this._tee=function(e,n){return function(){var e=Array.prototype.slice.call(arguments[0]),o="";return e.forEach((function(){o+=" %s"})),n.apply(t._originalLogger,[connect.LogComponent.SOFTPHONE,o].concat(e))}}};j.prototype.debug=function(){return this._tee(1,this._originalLogger.debug)(arguments)},j.prototype.info=function(){return this._tee(2,this._originalLogger.info)(arguments)},j.prototype.log=function(){return this._tee(3,this._originalLogger.log)(arguments)},j.prototype.warn=function(){return this._tee(4,this._originalLogger.warn)(arguments)},j.prototype.error=function(){return this._tee(5,this._originalLogger.error)(arguments)},connect.SoftphoneManager=function(e){var t,n=this;(l=new j(connect.getLog())).info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(),connect.RtcPeerConnectionFactory&&(t=new connect.RtcPeerConnectionFactory(l,connect.core.getWebSocketManager(),d,connect.hitch(n,f,{transportType:"softphone",softphoneClientId:d}),connect.hitch(n,_))),k()||_(p.UNSUPPORTED_BROWSER,"Connect does not support this browser. Some functionality may not work. ",""),A({success:function(e){connect.core.setSoftphoneUserMediaStream(e)},failure:function(e){_(e,"Your microphone is not enabled in your browser. ","")}}),m(),v(),y(),this.ringtoneEngine=null;var o={},r={};this.onInitContactSub={},this.onInitContactSub.unsubscribe=function(){};var i=!1,s=null,c=null,a=function(){i=!1,s=null,c=null};this.getSession=function(e){return o[e]},this.replaceLocalMediaTrack=function(e,t){var n=h[e].stream;if(n){var o=n.getAudioTracks()[0];t.enabled=o.enabled,o.enabled=!1,n.removeTrack(o),n.addTrack(t)}};var u=function(e){if(o.hasOwnProperty(e)){var t=o[e];new Promise((function(n,i){delete o[e],delete r[e],t.hangup()})).catch((function(t){lily.getLog().warn("Clean up the session locally "+e,t.message).sendInternalLogToServer()}))}};this.startSession=function(e,n){var p=i?s:e,d=i?c:n;if(p&&d){a(),r[d]=!0,l.info("Softphone call detected:","contactId "+p.getContactId(),"agent connectionId "+d).sendInternalLogToServer(),function(e){if(Object.keys(e).length>0){for(var t in e)e.hasOwnProperty(t)&&(N("MultiSessionHangUp",e[t].callId,t),u(t));throw new Error("duplicate session detected, refusing to setup new connection")}}(o),p.getStatus().type===connect.ContactStatusType.CONNECTING&&R("Softphone Connecting",p.getContactId()),P();var f,m=p.getAgentConnection().getSoftphoneMediaInfo(),v=I(m.callConfigJson);v.useWebSocketProvider&&(f=connect.core.getWebSocketManager());var y=new connect.RTCSession(v.signalingEndpoint,v.iceServers,m.callContextToken,l,p.getContactId(),d,f);o[d]=y,connect.core.getSoftphoneUserMediaStream()&&(y.mediaStream=connect.core.getSoftphoneUserMediaStream()),connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.ConnectionEvents.SESSION_INIT,data:{connectionId:d}}),y.onSessionFailed=function(e,t){delete o[d],delete r[d],T(e,t),w(p.getContactId(),t),U(p,e.sessionReport)},y.onSessionConnected=function(e){R("Softphone Session Connected",p.getContactId()),connect.becomeMaster(connect.MasterTopics.SEND_LOGS),L(e),D(p),g(p)},y.onSessionCompleted=function(e){R("Softphone Session Completed",p.getContactId()),delete o[d],delete r[d],U(p,e.sessionReport),E(d)},y.onLocalStreamAdded=function(e,t){h[d]={stream:t},connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED,data:{connectionId:d}})},y.remoteAudioElement=document.getElementById("remote-audio"),t?y.connect(t.get(v.iceServers)):y.connect()}};var S=function(e,t){o[t]&&function(e){return e.getStatus().type===connect.ContactStatusType.ENDED||e.getStatus().type===connect.ContactStatusType.ERROR||e.getStatus().type===connect.ContactStatusType.MISSED}(e)&&(u(t),a()),!e.isSoftphoneCall()||r[t]||e.getStatus().type!==connect.ContactStatusType.CONNECTING&&e.getStatus().type!==connect.ContactStatusType.INCOMING||(connect.isFirefoxBrowser()&&connect.hasOtherConnectedCCPs()?function(e,t){i=!0,s=e,c=t}(e,t):n.startSession(e,t))},b=function(e){var t=e.getAgentConnection().connectionId;l.info("Contact detected:","contactId "+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),r[t]||e.onRefresh((function(){S(e,t)}))};n.onInitContactSub=connect.contact(b),(new connect.Agent).getContacts().forEach((function(e){var t=e.getAgentConnection().connectionId;l.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId"+e.getContactId(),"agent connectionId "+t).sendInternalLogToServer(),b(e),S(e,t)}))}}()},778:()=>{!function(){var e=function e(){return e.cache.hasOwnProperty(arguments[0])||(e.cache[arguments[0]]=e.parse(arguments[0])),e.format.call(null,e.cache[arguments[0]],arguments)};function t(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}function n(e,t){for(var n=[];t>0;n[--t]=e);return n.join("")}e.format=function(o,r){var i,s,c,a,u,l,p,h=1,d=o.length,f="",g=[];for(s=0;s>>=0;break;case"x":i=i.toString(16);break;case"X":i=i.toString(16).toUpperCase()}i=/[def]/.test(a[8])&&a[3]&&i>=0?"+"+i:i,l=a[4]?"0"==a[4]?"0":a[4].charAt(1):" ",p=a[6]-String(i).length,u=a[6]?n(l,p):"",g.push(a[5]?i+u:u+i)}return g.join("")},e.cache={},e.parse=function(e){for(var t=e,n=[],o=[],r=0;t;){if(null!==(n=/^[^\x25]+/.exec(t)))o.push(n[0]);else if(null!==(n=/^\x25{2}/.exec(t)))o.push("%");else{if(null===(n=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(t)))throw"[sprintf] huh?";if(n[2]){r|=1;var i=[],s=n[2],c=[];if(null===(c=/^([a-z_][a-z_\d]*)/i.exec(s)))throw"[sprintf] huh?";for(i.push(c[1]);""!==(s=s.substring(c[0].length));)if(null!==(c=/^\.([a-z_][a-z_\d]*)/i.exec(s)))i.push(c[1]);else{if(null===(c=/^\[(\d+)\]/.exec(s)))throw"[sprintf] huh?";i.push(c[1])}n[2]=i}else r|=2;if(3===r)throw"[sprintf] mixing positional and named placeholders is not (yet) supported";o.push(n)}t=t.substring(n[0].length)}return o},this.sprintf=e,this.vsprintf=function(t,n,o){return(o=n.slice(0)).splice(0,0,t),e.apply(null,o)}}()},768:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect;var t=function(){};t.prototype.send=function(e){throw new connect.NotImplementedError},t.prototype.onMessage=function(e){throw new connect.NotImplementedError};var n=function(){t.call(this)};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype.onMessage=function(e){},n.prototype.send=function(e){};var o=function(e,n){t.call(this),this.window=e,this.domain=n||"*"};(o.prototype=Object.create(t.prototype)).constructor=o,o.prototype.send=function(e){this.window.postMessage(e,this.domain)},o.prototype.onMessage=function(e){this.window.addEventListener("message",e)};var r=function(e,n,o){t.call(this),this.input=e,this.output=n,this.domain=o||"*"};(r.prototype=Object.create(t.prototype)).constructor=r,r.prototype.send=function(e){this.output.postMessage(e,this.domain)},r.prototype.onMessage=function(e){var t=this;this.input.addEventListener("message",(function(n){n.source===t.output&&e(n)}))};var i=function(e){t.call(this),this.port=e,this.id=connect.randomId()};(i.prototype=Object.create(t.prototype)).constructor=i,i.prototype.send=function(e){this.port.postMessage(e)},i.prototype.onMessage=function(e){this.port.addEventListener("message",e)},i.prototype.getId=function(){return this.id};var s=function(e){t.call(this),this.streamMap=e?connect.index(e,(function(e){return e.getId()})):{},this.messageListeners=[]};(s.prototype=Object.create(t.prototype)).constructor=s,s.prototype.send=function(e){this.getStreams().forEach((function(t){try{t.send(e)}catch(e){}}))},s.prototype.onMessage=function(e){this.messageListeners.push(e),this.getStreams().forEach((function(t){t.onMessage(e)}))},s.prototype.addStream=function(e){this.streamMap[e.getId()]=e,this.messageListeners.forEach((function(t){e.onMessage(t)}))},s.prototype.removeStream=function(e){delete this.streamMap[e.getId()]},s.prototype.getStreams=function(e){return connect.values(this.streamMap)},s.prototype.getStreamForPort=function(e){return connect.find(this.getStreams(),(function(t){return t.port===e}))};var c=function(e,t,o){this.name=e,this.upstream=t||new n,this.downstream=o||new n,this.downstreamBus=new connect.EventBus,this.upstreamBus=new connect.EventBus,this.upstream.onMessage(connect.hitch(this,this._dispatchEvent,this.upstreamBus)),this.downstream.onMessage(connect.hitch(this,this._dispatchEvent,this.downstreamBus))};c.prototype.onUpstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.upstreamBus.subscribe(e,t)},c.prototype.onAllUpstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.upstreamBus.subscribeAll(e)},c.prototype.onDownstream=function(e,t){return connect.assertNotNull(e,"eventName"),connect.assertNotNull(t,"f"),connect.assertTrue(connect.isFunction(t),"f must be a function"),this.downstreamBus.subscribe(e,t)},c.prototype.onAllDownstream=function(e){return connect.assertNotNull(e,"f"),connect.assertTrue(connect.isFunction(e),"f must be a function"),this.downstreamBus.subscribeAll(e)},c.prototype.sendUpstream=function(e,t){connect.assertNotNull(e,"eventName"),this.upstream.send({event:e,data:t})},c.prototype.sendDownstream=function(e,t){connect.assertNotNull(e,"eventName"),this.downstream.send({event:e,data:t})},c.prototype._dispatchEvent=function(e,t){var n=t.data;n.event&&e.trigger(n.event,n.data)},c.prototype.passUpstream=function(){var e=this;return function(t,n){e.upstream.send({event:n,data:t})}},c.prototype.passDownstream=function(){var e=this;return function(t,n){e.downstream.send({event:n,data:t})}},c.prototype.shutdown=function(){this.upstreamBus.unsubscribeAll(),this.downstreamBus.unsubscribeAll()};var a=function(e,t,n,o){c.call(this,e,new r(t,n.contentWindow,o||"*"),null)};(a.prototype=Object.create(c.prototype)).constructor=a,connect.Stream=t,connect.NullStream=n,connect.WindowStream=o,connect.WindowIOStream=r,connect.PortStream=i,connect.StreamMultiplexer=s,connect.Conduit=c,connect.IFrameConduit=a}()},738:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect;var t=function(e,t){connect.assertNotNull(e,"fromState"),connect.assertNotNull(t,"toState"),this.fromState=e,this.toState=t};t.prototype.getAssociations=function(e){throw connect.NotImplementedError()},t.prototype.getFromState=function(){return this.fromState},t.prototype.getToState=function(){return this.toState};var n=function(e,n,o){connect.assertNotNull(e,"fromState"),connect.assertNotNull(n,"toState"),connect.assertNotNull(o,"associations"),t.call(this,e,n),this.associations=o};(n.prototype=Object.create(t.prototype)).constructor=n,n.prototype.getAssociations=function(e){return this.associations};var o=function(e,n,o){connect.assertNotNull(e,"fromState"),connect.assertNotNull(n,"toState"),connect.assertNotNull(o,"closure"),connect.assertTrue(connect.isFunction(o),"closure must be a function"),t.call(this,e,n),this.closure=o};(o.prototype=Object.create(t.prototype)).constructor=o,o.prototype.getAssociations=function(e){return this.closure(e,this.getFromState(),this.getToState())};var r=function(){this.fromMap={}};r.ANY="<>",r.prototype.assoc=function(e,t,r){var i=this;if(!e)throw new Error("fromStateObj is not defined.");if(!t)throw new Error("toStateObj is not defined.");if(!r)throw new Error("assocObj is not defined.");return e instanceof Array?e.forEach((function(e){i.assoc(e,t,r)})):t instanceof Array?t.forEach((function(t){i.assoc(e,t,r)})):"function"==typeof r?this._addAssociation(new o(e,t,r)):r instanceof Array?this._addAssociation(new n(e,t,r)):this._addAssociation(new n(e,t,[r])),this},r.prototype.getAssociations=function(e,t,n){connect.assertNotNull(t,"fromState"),connect.assertNotNull(n,"toState");var o=[],i=this.fromMap[r.ANY]||{},s=this.fromMap[t]||{};return o=(o=o.concat(this._getAssociationsFromMap(i,e,t,n))).concat(this._getAssociationsFromMap(s,e,t,n))},r.prototype._addAssociation=function(e){var t=this.fromMap[e.getFromState()];t||(t=this.fromMap[e.getFromState()]={});var n=t[e.getToState()];n||(n=t[e.getToState()]=[]),n.push(e)},r.prototype._getAssociationsFromMap=function(e,t,n,o){return(e[r.ANY]||[]).concat(e[o]||[]).reduce((function(e,n){return e.concat(n.getAssociations(t))}),[])},connect.EventGraph=r}()},420:()=>{function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e(t)}!function(){var t=this;connect=t.connect||{},t.connect=connect,t.lily=connect;var n=navigator.userAgent,o=["bubbles","cancelBubble","cancelable","composed","data","defaultPrevented","eventPhase","isTrusted","lastEventId","origin","returnValue","timeStamp","type"];connect.sprintf=t.sprintf,connect.vsprintf=t.vsprintf,delete t.sprintf,delete t.vsprintf,connect.HTTP_STATUS_CODES={SUCCESS:200,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500},connect.TRANSPORT_TYPES={CHAT_TOKEN:"chat_token",WEB_SOCKET:"web_socket"},connect.hitch=function(){var e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift();return connect.assertNotNull(t,"scope"),connect.assertNotNull(n,"method"),connect.assertTrue(connect.isFunction(n),"method must be a function"),function(){var o=Array.prototype.slice.call(arguments);return n.apply(t,e.concat(o))}},connect.isFunction=function(e){return!!(e&&e.constructor&&e.call&&e.apply)},connect.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},connect.keys=function(e){var t=[];for(var n in connect.assertNotNull(e,"map"),e)t.push(n);return t},connect.values=function(e){var t=[];for(var n in connect.assertNotNull(e,"map"),e)t.push(e[n]);return t},connect.entries=function(e){var t=[];for(var n in e)t.push({key:n,value:e[n]});return t},connect.merge=function(){var e=Array.prototype.slice.call(arguments,0),t={};return e.forEach((function(e){connect.entries(e).forEach((function(e){t[e.key]=e.value}))})),t},connect.now=function(){return(new Date).getTime()},connect.find=function(e,t){for(var n=0;n1},connect.fetch=function(e,t,n,o){return o=o||5,n=n||1e3,t=t||{},new Promise((function(r,i){!function o(s){fetch(e,t).then((function(e){e.status===connect.HTTP_STATUS_CODES.SUCCESS?e.json().then((function(e){return r(e)})).catch((function(){return r({})})):1!==s&&(e.status>=connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR||e.status===connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)?setTimeout((function(){o(--s)}),n):i(e)})).catch((function(e){i(e)}))}(o)}))},connect.backoff=function(e,n,o,r){connect.assertTrue(connect.isFunction(e),"func must be a Function");var i=this;e({success:function(e){r&&r.success&&r.success(e)},failure:function(s,c){if(o>0){var a=2*n*Math.random();t.setTimeout((function(){i.backoff(e,2*a,--o,r)}),a)}else r&&r.failure&&r.failure(s,c)}})},connect.publishMetric=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.CLIENT_METRIC,data:e})},connect.publishSoftphoneStats=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.SOFTPHONE_STATS,data:e})},connect.publishSoftphoneReport=function(e){connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST,{event:connect.EventType.SOFTPHONE_REPORT,data:e})},connect.publishClientSideLogs=function(e){connect.core.getEventBus().trigger(connect.EventType.CLIENT_SIDE_LOGS,e)},connect.PopupManager=function(){},connect.PopupManager.prototype.open=function(e,t,n){var o=this._getLastOpenedTimestamp(t),r=(new Date).getTime(),i=null;if(r-o>864e5){if(n){var s=n.height||578,c=n.width||433,a=n.top||0,u=n.left||0;(i=window.open("",t,"width="+c+", height="+s+", top="+a+", left="+u)).location!==e&&(i=window.open(e,t,"width="+c+", height="+s+", top="+a+", left="+u))}else(i=window.open("",t)).location!==e&&(i=window.open(e,t));this._setLastOpenedTimestamp(t,r)}return i},connect.PopupManager.prototype.clear=function(e){var n=this._getLocalStorageKey(e);t.localStorage.removeItem(n)},connect.PopupManager.prototype._getLastOpenedTimestamp=function(e){var n=this._getLocalStorageKey(e),o=t.localStorage.getItem(n);return o?parseInt(o,10):0},connect.PopupManager.prototype._setLastOpenedTimestamp=function(e,n){var o=this._getLocalStorageKey(e);t.localStorage.setItem(o,""+n)},connect.PopupManager.prototype._getLocalStorageKey=function(e){return"connectPopupManager::"+e};var r=connect.makeEnum(["granted","denied","default"]);connect.NotificationManager=function(){this.queue=[],this.permission=r.DEFAULT},connect.NotificationManager.prototype.requestPermission=function(){var e=this;"Notification"in t?t.Notification.permission===r.DENIED?(connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(),this.permission=r.DENIED):this.permission!==r.GRANTED&&t.Notification.requestPermission().then((function(t){e.permission=t,t===r.GRANTED?e._showQueued():e.queue=[]})):(connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(),this.permission=r.DENIED)},connect.NotificationManager.prototype.show=function(e,t){if(this.permission===r.GRANTED)return this._showImpl({title:e,options:t});if(this.permission===r.DENIED)connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({title:e,options:t});else{var n={title:e,options:t};connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(n).sendInternalLogToServer(),this.queue.push(n)}},connect.NotificationManager.prototype._showQueued=function(){var e=this,t=this.queue.map((function(t){return e._showImpl(t)}));return this.queue=[],t},connect.NotificationManager.prototype._showImpl=function(e){var n=new t.Notification(e.title,e.options);return e.options.clicked&&(n.onclick=function(){e.options.clicked.call(n)}),n},connect.BaseError=function(e,n){t.Error.call(this,connect.vsprintf(e,n))},connect.BaseError.prototype=Object.create(Error.prototype),connect.BaseError.prototype.constructor=connect.BaseError,connect.ValueError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.ValueError.prototype=Object.create(connect.BaseError.prototype),connect.ValueError.prototype.constructor=connect.ValueError,connect.NotImplementedError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.NotImplementedError.prototype=Object.create(connect.BaseError.prototype),connect.NotImplementedError.prototype.constructor=connect.NotImplementedError,connect.StateError=function(){var e=Array.prototype.slice.call(arguments,0),t=e.shift();connect.BaseError.call(this,t,e)},connect.StateError.prototype=Object.create(connect.BaseError.prototype),connect.StateError.prototype.constructor=connect.StateError,connect.VoiceIdError=function(e,t,n){var o={};return o.type=e,o.message=t,o.stack=Error(t).stack,o.err=n,o},connect.isCCP=function(){return"ConnectSharedWorkerConduit"===connect.core.getUpstream().name}}()},744:()=>{!function(){var e=this;connect=e.connect||{},e.connect=connect,e.lily=connect,connect.worker={};var t=function(){this.topicMasterMap={}};t.prototype.getMaster=function(e){return connect.assertNotNull(e,"topic"),this.topicMasterMap[e]||null},t.prototype.setMaster=function(e,t){connect.assertNotNull(e,"topic"),connect.assertNotNull(t,"id"),this.topicMasterMap[e]=t},t.prototype.removeMaster=function(e){connect.assertNotNull(e,"id");var t=this;connect.entries(this.topicMasterMap).filter((function(t){return t.value===e})).forEach((function(e){delete t.topicMasterMap[e.key]}))};var n=function(e){connect.ClientBase.call(this),this.conduit=e};(n.prototype=Object.create(connect.ClientBase.prototype)).constructor=n,n.prototype._callImpl=function(e,t,n){var o=this,r=(new Date).getTime();connect.containsValue(connect.AgentAppClientMethods,e)?connect.core.getAgentAppClient()._callImpl(e,t,{success:function(t){o._recordAPILatency(e,r),n.success(t)},failure:function(t){o._recordAPILatency(e,r,t),n.failure(t)}}):connect.core.getClient()._callImpl(e,t,{success:function(t){o._recordAPILatency(e,r),n.success(t)},failure:function(t,i){o._recordAPILatency(e,r,t),n.failure(t,i)},authFailure:function(){o._recordAPILatency(e,r),n.authFailure()},accessDenied:function(){n.accessDenied&&n.accessDenied()}})},n.prototype._recordAPILatency=function(e,t,n){var o=(new Date).getTime()-t;this._sendAPIMetrics(e,o,n)},n.prototype._sendAPIMetrics=function(e,t,n){this.conduit.sendDownstream(connect.EventType.API_METRIC,{name:e,time:t,dimensions:[{name:"Category",value:"API"}],error:n})};var o=function(){var o=this;this.multiplexer=new connect.StreamMultiplexer,this.conduit=new connect.Conduit("AmazonConnectSharedWorker",null,this.multiplexer),this.client=new n(this.conduit),this.timeout=null,this.agent=null,this.nextToken=null,this.initData={},this.portConduitMap={},this.masterCoord=new t,this.logsBuffer=[],this.suppress=!1,this.forceOffline=!1;var r=null;connect.rootLogger=new connect.DownstreamConduitLogger(this.conduit),this.conduit.onDownstream(connect.EventType.SEND_LOGS,(function(e){connect.getLog().pushLogsDownstream(e),o.logsBuffer=o.logsBuffer.concat(e),o.logsBuffer.length>400&&o.handleSendLogsRequest(o.logsBuffer)})),this.conduit.onDownstream(connect.EventType.CONFIGURE,(function(t){t.authToken&&t.authToken!==o.initData.authToken&&(o.initData=t,connect.core.init(t),r?connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer():(connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(),connect.WebSocketManager.setGlobalConfig({loggerConfig:{logger:connect.getLog()}}),(r=connect.WebSocketManager.create()).onInitFailure((function(){o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE)})),r.onConnectionOpen((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN,e)})),r.onConnectionClose((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE,e)})),r.onConnectionGain((function(){o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED),o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN)})),r.onConnectionLost((function(e){o.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST,e),o.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST,e)})),r.onSubscriptionUpdate((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE,e)})),r.onSubscriptionFailure((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE,e)})),r.onAllMessage((function(e){o.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE,e)})),o.conduit.onDownstream(connect.WebSocketEvents.SEND,(function(e){r.sendMessage(e)})),o.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE,(function(e){r.subscribeTopics(e)})),r.init(connect.hitch(o,o.getWebSocketUrl)).then((function(t){t&&!t.webSocketConnectionFailed?(connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(),o.pollForAgent(),connect.getLog().info("Kicking off config polling").sendInternalLogToServer(),o.pollForAgentConfiguration({repeatForever:!0}),connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(),e.setInterval(connect.hitch(o,o.checkAuthToken),3e5)):connect.webSocketInitFailed||(o.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE),connect.webSocketInitFailed=!0)}))))})),this.conduit.onDownstream(connect.EventType.TERMINATE,(function(){o.handleSendLogsRequest(o.logsBuffer),connect.core.terminate(),o.conduit.sendDownstream(connect.EventType.TERMINATED)})),this.conduit.onDownstream(connect.EventType.SYNCHRONIZE,(function(){o.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE)})),this.conduit.onDownstream(connect.EventType.BROADCAST,(function(e){o.conduit.sendDownstream(e.event,e.data)})),e.onconnect=function(e){var t=e.ports[0],n=new connect.PortStream(t);o.multiplexer.addStream(n),t.start();var r=new connect.Conduit(n.getId(),null,n);r.sendDownstream(connect.EventType.ACKNOWLEDGE,{id:n.getId()}),o.portConduitMap[n.getId()]=r,o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length}),null!==o.agent&&o.updateAgent(),r.onDownstream(connect.EventType.API_REQUEST,connect.hitch(o,o.handleAPIRequest,r)),r.onDownstream(connect.EventType.MASTER_REQUEST,connect.hitch(o,o.handleMasterRequest,r,n.getId())),r.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION,connect.hitch(o,o.pollForAgentConfiguration)),r.onDownstream(connect.EventType.CLOSE,(function(){o.multiplexer.removeStream(n),delete o.portConduitMap[n.getId()],o.masterCoord.removeMaster(n.getId()),o.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS,{length:Object.keys(o.portConduitMap).length})}))}};o.prototype.pollForAgent=function(){var t=this,n=connect.hitch(t,t.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT,{nextToken:t.nextToken,timeout:3e4},{success:function(n){try{t.agent=t.agent||{},t.agent.snapshot=n.snapshot,t.agent.snapshot.localTimestamp=connect.now(),t.agent.snapshot.skew=t.agent.snapshot.snapshotTimestamp-t.agent.snapshot.localTimestamp,t.nextToken=n.nextToken,connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(n).sendInternalLogToServer(),t.updateAgent()}catch(e){connect.getLog().error("Long poll failed to update agent.").withObject(n).withException(e).sendInternalLogToServer()}finally{e.setTimeout(connect.hitch(t,t.pollForAgent),100)}},failure:function(n,o){try{connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({err:n,data:o})}finally{e.setTimeout(connect.hitch(t,t.pollForAgent),5e3)}},authFailure:function(){n()},accessDenied:connect.hitch(t,t.handleAccessDenied)})},o.prototype.pollForAgentConfiguration=function(t){var n=this,o=t||{},r=connect.hitch(n,n.handleAuthFail);this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION,{},{success:function(t){var r=t.configuration;n.pollForAgentPermissions(r),n.pollForAgentStates(r),n.pollForDialableCountryCodes(r),n.pollForRoutingProfileQueues(r),o.repeatForever&&e.setTimeout(connect.hitch(n,n.pollForAgentConfiguration,o),3e4)},failure:function(t,r){try{connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({err:t,data:r})}finally{o.repeatForever&&e.setTimeout(connect.hitch(n,n.pollForAgentConfiguration),3e4,o)}},authFailure:function(){r()},accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentStates=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_STATES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForAgentStates(e,{states:(o.states||[]).concat(t.states),nextToken:t.nextToken,maxResults:o.maxResults}):(e.agentStates=(o.states||[]).concat(t.states),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForAgentPermissions=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForAgentPermissions(e,{permissions:(o.permissions||[]).concat(t.permissions),nextToken:t.nextToken,maxResults:o.maxResults}):(e.permissions=(o.permissions||[]).concat(t.permissions),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForDialableCountryCodes=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES,{nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForDialableCountryCodes(e,{countryCodes:(o.countryCodes||[]).concat(t.countryCodes),nextToken:t.nextToken,maxResults:o.maxResults}):(e.dialableCountries=(o.countryCodes||[]).concat(t.countryCodes),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.pollForRoutingProfileQueues=function(e,t){var n=this,o=t||{};o.maxResults=o.maxResults||connect.DEFAULT_BATCH_SIZE,this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES,{routingProfileARN:e.routingProfile.routingProfileARN,nextToken:o.nextToken||null,maxResults:o.maxResults},{success:function(t){t.nextToken?n.pollForRoutingProfileQueues(e,{countryCodes:(o.queues||[]).concat(t.queues),nextToken:t.nextToken,maxResults:o.maxResults}):(e.routingProfile.queues=(o.queues||[]).concat(t.queues),n.updateAgentConfiguration(e))},failure:function(e,t){connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({err:e,data:t})},authFailure:connect.hitch(n,n.handleAuthFail),accessDenied:connect.hitch(n,n.handleAccessDenied)})},o.prototype.handleAPIRequest=function(e,t){var n=this;this.client.call(t.method,t.params,{success:function(n){var o=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,t,n);e.sendDownstream(o.event,o)},failure:function(o,r){var i=connect.EventFactory.createResponse(connect.EventType.API_RESPONSE,t,r,JSON.stringify(o));e.sendDownstream(i.event,i),connect.getLog().error("'%s' API request failed",t.method).withObject({request:n.filterAuthToken(t),response:i}).withException(o).sendInternalLogToServer()},authFailure:connect.hitch(n,n.handleAuthFail)})},o.prototype.handleMasterRequest=function(e,t,n){var o=this.conduit,r=null;switch(n.method){case connect.MasterMethods.BECOME_MASTER:var i=this.masterCoord.getMaster(n.params.topic),s=Boolean(i)&&i!==t;this.masterCoord.setMaster(n.params.topic,t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:t,takeOver:s,topic:n.params.topic}),s&&o.sendDownstream(r.event,r);break;case connect.MasterMethods.CHECK_MASTER:(i=this.masterCoord.getMaster(n.params.topic))||n.params.shouldNotBecomeMasterIfNone||(this.masterCoord.setMaster(n.params.topic,t),i=t),r=connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE,n,{masterId:i,isMaster:t===i,topic:n.params.topic});break;default:throw new Error("Unknown master method: "+n.method)}e.sendDownstream(r.event,r)},o.prototype.updateAgentConfiguration=function(e){e.permissions&&e.dialableCountries&&e.agentStates&&e.routingProfile.queues?(this.agent=this.agent||{},this.agent.configuration=e,this.updateAgent()):connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer()},o.prototype.updateAgent=function(){this.agent?this.agent.snapshot?this.agent.configuration?(this.agent.snapshot.status=this.agent.state,this.agent.snapshot.contacts&&this.agent.snapshot.contacts.length>1&&this.agent.snapshot.contacts.sort((function(e,t){return e.state.timestamp.getTime()-t.state.timestamp.getTime()})),this.agent.snapshot.contacts.forEach((function(e){e.status=e.state,e.connections.forEach((function(e){e.address=e.endpoint}))})),this.agent.configuration.routingProfile.defaultOutboundQueue.queueId=this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN,this.agent.configuration.routingProfile.queues.forEach((function(e){e.queueId=e.queueARN})),this.agent.snapshot.contacts.forEach((function(e){void 0!==e.queue&&(e.queue.queueId=e.queue.queueARN)})),this.agent.configuration.routingProfile.routingProfileId=this.agent.configuration.routingProfile.routingProfileARN,this.conduit.sendDownstream(connect.AgentEvents.UPDATE,this.agent)):connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer():connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer():connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer()},o.prototype.getWebSocketUrl=function(){var e=this,t=connect.core.getClient(),n=connect.hitch(e,e.handleAuthFail),o=connect.hitch(e,e.handleAccessDenied);return new Promise((function(e,r){t.call(connect.ClientMethods.CREATE_TRANSPORT,{transportType:connect.TRANSPORT_TYPES.WEB_SOCKET},{success:function(t){connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(),e(t)},failure:function(e,t){connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({err:e,data:t}),r({reason:"getWebSocketUrl failed",_debug:e})},authFailure:function(){connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(),r(Error("Authentication failed while getting getWebSocketUrl")),n()},accessDenied:function(){connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(),r(Error("Access Denied Failure while getting getWebSocketUrl")),o()}})}))},o.prototype.handleSendLogsRequest=function(){var e=this,t=[],n=e.logsBuffer.slice();e.logsBuffer=[],n.forEach((function(e){t.push({timestamp:e.time,component:e.component,message:e.text})})),this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS,{logEvents:t},{success:function(e){connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer()},failure:function(e,t){connect.getLog().error("SendLogs request failed.").withObject(t).withException(e).sendInternalLogToServer()},authFailure:connect.hitch(e,e.handleAuthFail)})},o.prototype.handleAuthFail=function(){this.conduit.sendDownstream(connect.EventType.AUTH_FAIL)},o.prototype.handleAccessDenied=function(){this.conduit.sendDownstream(connect.EventType.ACCESS_DENIED)},o.prototype.checkAuthToken=function(){var e=this,t=new Date(e.initData.authTokenExpiration),n=(new Date).getTime();t.getTime() { - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - connect.agentApp = {}; - var APP = { - CCP: 'ccp' - }; - connect.agentApp.initCCP = connect.core.initCCP; - connect.agentApp.isInitialized = function (instanceAlias) { }; - connect.agentApp.initAppCommunication = function (iframeId, endpoint) { - var iframe = document.getElementById(iframeId); - var iframeConduit = new connect.IFrameConduit(endpoint, window, iframe); - var BROADCAST_TYPE = [connect.AgentEvents.UPDATE, connect.ContactEvents.VIEW, connect.EventType.ACKNOWLEDGE, connect.EventType.TERMINATED, connect.TaskEvents.CREATED]; - iframe.addEventListener('load', function (e) { - BROADCAST_TYPE.forEach(function (type) { - connect.core.getUpstream().onUpstream(type, function (data) { - iframeConduit.sendUpstream(type, data); - }); - }); - }); - }; - var getConnectUrl = function getConnectUrl(ccpUrl) { - var pos = ccpUrl.indexOf('ccp-v2'); - return ccpUrl.slice(0, pos - 1); - }; - var signOutThroughCCP = function signOutThroughCCP(ccpUrl) { - var logoutUrl = getConnectUrl(ccpUrl) + '/logout'; - return connect.fetch(logoutUrl, { - credentials: 'include' - }).then(function () { - var eventBus = connect.core.getEventBus(); - eventBus.trigger(connect.EventType.TERMINATE); - return true; - })["catch"](function (e) { - connect.getLog().error('An error occured on logout.' + e).withException(e); - window.location.href = logoutUrl; - return false; - }); - }; - var signInThroughinitCCP = function signInThroughinitCCP(ccpUrl, container, config) { - var defaultParams = { - ccpUrl: ccpUrl, - ccpLoadTimeout: 10000, - loginPopup: true, - loginUrl: getConnectUrl(ccpUrl) + '/login', - softphone: { - allowFramedSoftphone: true, - disableRingtone: false - } - }; - var ccpParams = connect.merge(defaultParams, config.ccpParams); - connect.core.initCCP(container, ccpParams); - }; - connect.agentApp.initApp = function (name, containerId, appUrl, config) { - config = config ? config : {}; - var endpoint = appUrl.endsWith('/') ? appUrl : appUrl + '/'; - var onLoad = config.onLoad ? config.onLoad : null; - var registerConfig = { - endpoint: endpoint, - style: config.style, - onLoad: onLoad - }; - connect.agentApp.AppRegistry.register(name, registerConfig, document.getElementById(containerId)); - connect.agentApp.AppRegistry.start(name, function (moduleData) { - var endpoint = moduleData.endpoint; - var containerDOM = moduleData.containerDOM; - return { - init: function init() { - if (name === APP.CCP) return signInThroughinitCCP(endpoint, containerDOM, config); - return connect.agentApp.initAppCommunication(name, endpoint); - }, - destroy: function destroy() { - if (name === APP.CCP) return signOutThroughCCP(endpoint); - return null; - } - }; - }); - }; - connect.agentApp.stopApp = function (name) { - return connect.agentApp.AppRegistry.stop(name); - }; - })(); +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + connect.agentApp = {}; + var APP = { + CCP: 'ccp' + }; + connect.agentApp.initCCP = connect.core.initCCP; + connect.agentApp.isInitialized = function (instanceAlias) {}; + connect.agentApp.initAppCommunication = function (iframeId, endpoint) { + var iframe = document.getElementById(iframeId); + var iframeConduit = new connect.IFrameConduit(endpoint, window, iframe); + var BROADCAST_TYPE = [connect.AgentEvents.UPDATE, connect.ContactEvents.VIEW, connect.EventType.ACKNOWLEDGE, connect.EventType.TERMINATED, connect.TaskEvents.CREATED]; + iframe.addEventListener('load', function (e) { + BROADCAST_TYPE.forEach(function (type) { + connect.core.getUpstream().onUpstream(type, function (data) { + iframeConduit.sendUpstream(type, data); + }); + }); + }); + }; + var getConnectUrl = function getConnectUrl(ccpUrl) { + var pos = ccpUrl.indexOf('ccp-v2'); + return ccpUrl.slice(0, pos - 1); + }; + var signOutThroughCCP = function signOutThroughCCP(ccpUrl) { + var logoutUrl = getConnectUrl(ccpUrl) + '/logout'; + return connect.fetch(logoutUrl, { + credentials: 'include' + }).then(function () { + var eventBus = connect.core.getEventBus(); + eventBus.trigger(connect.EventType.TERMINATE); + return true; + })["catch"](function (e) { + connect.getLog().error('An error occured on logout.' + e).withException(e); + window.location.href = logoutUrl; + return false; + }); + }; + var signInThroughinitCCP = function signInThroughinitCCP(ccpUrl, container, config) { + var defaultParams = { + ccpUrl: ccpUrl, + ccpLoadTimeout: 10000, + loginPopup: true, + loginUrl: getConnectUrl(ccpUrl) + '/login', + softphone: { + allowFramedSoftphone: true, + disableRingtone: false + } + }; + var ccpParams = connect.merge(defaultParams, config.ccpParams); + connect.core.initCCP(container, ccpParams); + }; + connect.agentApp.initApp = function (name, containerId, appUrl, config) { + config = config ? config : {}; + var endpoint = appUrl.endsWith('/') ? appUrl : appUrl + '/'; + var onLoad = config.onLoad ? config.onLoad : null; + var registerConfig = { + endpoint: endpoint, + style: config.style, + onLoad: onLoad + }; + connect.agentApp.AppRegistry.register(name, registerConfig, document.getElementById(containerId)); + connect.agentApp.AppRegistry.start(name, function (moduleData) { + var endpoint = moduleData.endpoint; + var containerDOM = moduleData.containerDOM; + return { + init: function init() { + if (name === APP.CCP) return signInThroughinitCCP(endpoint, containerDOM, config); + return connect.agentApp.initAppCommunication(name, endpoint); + }, + destroy: function destroy() { + if (name === APP.CCP) return signOutThroughCCP(endpoint); + return null; + } + }; + }); + }; + connect.agentApp.stopApp = function (name) { + return connect.agentApp.AppRegistry.stop(name); + }; +})(); - /***/ -}), +/***/ }), /***/ 228: /***/ (() => { - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - var APP = { - CCP: 'ccp' - }; - function AppRegistry() { - var moduleData = {}; - var makeAppIframe = function makeAppIframe(appName, endpoint, style, onLoad) { - var iframe = document.createElement('iframe'); - iframe.src = endpoint; - iframe.style = style || 'width: 100%; height:100%;'; - iframe.id = appName; - iframe['aria-label'] = appName; - iframe.onload = onLoad; - iframe.setAttribute("sandbox", "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"); - // TODO: Update sandbox option for 3P widget - - return iframe; - }; - return { - register: function register(appName, config, containerDOM) { - moduleData[appName] = { - containerDOM: containerDOM, - endpoint: config.endpoint, - style: config.style, - instance: undefined, - onLoad: config.onLoad - }; - }, - start: function start(appName, creator) { - if (!moduleData[appName]) return; - var containerDOM = moduleData[appName].containerDOM; - var endpoint = moduleData[appName].endpoint; - var style = moduleData[appName].style; - var onLoad = moduleData[appName].onLoad; - if (appName !== APP.CCP) { - var app = makeAppIframe(appName, endpoint, style, onLoad); - containerDOM.appendChild(app); - } - moduleData[appName].instance = creator(moduleData[appName]); - return moduleData[appName].instance.init(); - }, - stop: function stop(appName) { - if (!moduleData[appName]) return; - var data = moduleData[appName]; - var app = data.containerDOM.querySelector('iframe'); - data.containerDOM.removeChild(app); - var result; - if (data.instance) { - result = data.instance.destroy(); - delete data.instance; - } - return result; - } - }; - } - global.connect.agentApp.AppRegistry = AppRegistry(); - })(); +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + var APP = { + CCP: 'ccp' + }; + function AppRegistry() { + var moduleData = {}; + var makeAppIframe = function makeAppIframe(appName, endpoint, style, onLoad) { + var iframe = document.createElement('iframe'); + iframe.src = endpoint; + iframe.style = style || 'width: 100%; height:100%;'; + iframe.id = appName; + iframe['aria-label'] = appName; + iframe.onload = onLoad; + iframe.setAttribute("sandbox", "allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"); + // TODO: Update sandbox option for 3P widget + + return iframe; + }; + return { + register: function register(appName, config, containerDOM) { + moduleData[appName] = { + containerDOM: containerDOM, + endpoint: config.endpoint, + style: config.style, + instance: undefined, + onLoad: config.onLoad + }; + }, + start: function start(appName, creator) { + if (!moduleData[appName]) return; + var containerDOM = moduleData[appName].containerDOM; + var endpoint = moduleData[appName].endpoint; + var style = moduleData[appName].style; + var onLoad = moduleData[appName].onLoad; + if (appName !== APP.CCP) { + var app = makeAppIframe(appName, endpoint, style, onLoad); + containerDOM.appendChild(app); + } + moduleData[appName].instance = creator(moduleData[appName]); + return moduleData[appName].instance.init(); + }, + stop: function stop(appName) { + if (!moduleData[appName]) return; + var data = moduleData[appName]; + var app = data.containerDOM.querySelector('iframe'); + data.containerDOM.removeChild(app); + var result; + if (data.instance) { + result = data.instance.destroy(); + delete data.instance; + } + return result; + } + }; + } + global.connect.agentApp.AppRegistry = AppRegistry(); +})(); - /***/ -}), +/***/ }), /***/ 35: /***/ (() => { - function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() { }; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /*---------------------------------------------------------------- - * enum AgentStateType - */ - connect.AgentStateType = connect.makeEnum(['init', 'routable', 'not_routable', 'offline']); - connect.AgentStatusType = connect.AgentStateType; - - /** - * enum AgentAvailStates - */ - connect.AgentAvailStates = connect.makeEnum(['Init', 'Busy', 'AfterCallWork', 'CallingCustomer', 'Dialing', 'Joining', 'PendingAvailable', 'PendingBusy']); - - /** - * enum AgentErrorStates - */ - connect.AgentErrorStates = connect.makeEnum(['Error', 'AgentHungUp', 'BadAddressAgent', 'BadAddressCustomer', 'Default', 'FailedConnectAgent', 'FailedConnectCustomer', 'InvalidLocale', 'LineEngagedAgent', 'LineEngagedCustomer', 'MissedCallAgent', 'MissedCallCustomer', 'MultipleCcpWindows', 'RealtimeCommunicationError']); - - /*---------------------------------------------------------------- - * enum AddressType - */ - connect.EndpointType = connect.makeEnum(['phone_number', 'agent', 'queue']); - connect.AddressType = connect.EndpointType; - - /*---------------------------------------------------------------- - * enum ConnectionType - */ - connect.ConnectionType = connect.makeEnum(['agent', 'inbound', 'outbound', 'monitoring']); - - /*---------------------------------------------------------------- - * enum ConnectionStateType - */ - connect.ConnectionStateType = connect.makeEnum(['init', 'connecting', 'connected', 'hold', 'disconnected']); - connect.ConnectionStatusType = connect.ConnectionStateType; - connect.CONNECTION_ACTIVE_STATES = connect.set([connect.ConnectionStateType.CONNECTING, connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.HOLD]); - - /*---------------------------------------------------------------- - * enum ContactStateType - */ - connect.ContactStateType = connect.makeEnum(['init', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'error', 'ended']); - connect.ContactStatusType = connect.ContactStateType; - connect.CONTACT_ACTIVE_STATES = connect.makeEnum(['incoming', 'pending', 'connecting', 'connected']); - - /*---------------------------------------------------------------- - * enum ContactType - */ - connect.ContactType = connect.makeEnum(['voice', 'queue_callback', 'chat', 'task']); - - /*---------------------------------------------------------------- - * enum ContactInitiationMethod - */ - connect.ContactInitiationMethod = connect.makeEnum(['inbound', 'outbound', 'transfer', 'queue_transfer', 'callback', 'api', 'disconnect']); - - /*---------------------------------------------------------------- - * enum ChannelType - */ - connect.ChannelType = connect.makeEnum(['VOICE', 'CHAT', 'TASK']); - - /*---------------------------------------------------------------- - * enum MediaType - */ - connect.MediaType = connect.makeEnum(['softphone', 'chat', 'task']); - - /*---------------------------------------------------------------- - * enum SoftphoneCallType - */ - connect.SoftphoneCallType = connect.makeEnum(['audio_video', 'video_only', 'audio_only', 'none']); - - /*---------------------------------------------------------------- - * enum for SoftphoneErrorTypes - */ - connect.SoftphoneErrorTypes = connect.makeEnum(['unsupported_browser', 'microphone_not_shared', 'signalling_handshake_failure', 'signalling_connection_failure', 'ice_collection_timeout', 'user_busy_error', 'webrtc_error', 'realtime_communication_error', 'other']); - - /*---------------------------------------------------------------- - * enum for VoiceIdErrorTypes - */ - connect.VoiceIdErrorTypes = connect.makeEnum(['no_speaker_id_found', 'speaker_id_not_enrolled', 'get_speaker_id_failed', 'get_speaker_status_failed', 'opt_out_speaker_failed', 'opt_out_speaker_in_lcms_failed', 'delete_speaker_failed', 'start_session_failed', 'evaluate_speaker_failed', 'session_not_exists', 'describe_session_failed', 'enroll_speaker_failed', 'update_speaker_id_failed', 'update_speaker_id_in_lcms_failed', 'not_supported_on_conference_calls', 'enroll_speaker_timeout', 'evaluate_speaker_timeout', 'get_domain_id_failed', 'no_domain_id_found']); - - /*---------------------------------------------------------------- - * enum for CTI exceptions - */ - connect.CTIExceptions = connect.makeEnum(["AccessDeniedException", "InvalidStateException", "BadEndpointException", "InvalidAgentARNException", "InvalidConfigurationException", "InvalidContactTypeException", "PaginationException", "RefreshTokenExpiredException", "SendDataFailedException", "UnauthorizedException", "QuotaExceededException"]); - /*---------------------------------------------------------------- - * enum for VoiceId streaming status - */ - connect.VoiceIdStreamingStatus = connect.makeEnum(["ONGOING", "ENDED", "PENDING_CONFIGURATION"]); - - /*---------------------------------------------------------------- - * enum for VoiceId authentication decision - */ - connect.VoiceIdAuthenticationDecision = connect.makeEnum(["ACCEPT", "REJECT", "NOT_ENOUGH_SPEECH", "SPEAKER_NOT_ENROLLED", "SPEAKER_OPTED_OUT", "SPEAKER_ID_NOT_PROVIDED", "SPEAKER_EXPIRED"]); - - /*---------------------------------------------------------------- - * enum for VoiceId fraud detection decision - */ - connect.VoiceIdFraudDetectionDecision = connect.makeEnum(["NOT_ENOUGH_SPEECH", "HIGH_RISK", "LOW_RISK"]); - - /*---------------------------------------------------------------- - * enum for contact flow authentication decision - */ - connect.ContactFlowAuthenticationDecision = connect.makeEnum(["Authenticated", "NotAuthenticated", "Inconclusive", "NotEnrolled", "OptedOut", "NotEnabled", "Error"]); - - /*---------------------------------------------------------------- - * enum for contact flow fraud detection decision - */ - connect.ContactFlowFraudDetectionDecision = connect.makeEnum(["HighRisk", "LowRisk", "Inconclusive", "NotEnabled", "Error"]); - - /*---------------------------------------------------------------- - * enum for VoiceId EnrollmentRequest Status - */ - connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum(["NOT_ENOUGH_SPEECH", "IN_PROGRESS", "COMPLETED", "FAILED"]); - - /*---------------------------------------------------------------- - * enum for VoiceId Speaker status - */ - connect.VoiceIdSpeakerStatus = connect.makeEnum(["OPTED_OUT", "ENROLLED", "PENDING"]); - connect.VoiceIdConstants = { - EVALUATE_SESSION_DELAY: 10000, - EVALUATION_MAX_POLL_TIMES: 24, - // EvaluateSpeaker is Polling for maximum 2 mins. - EVALUATION_POLLING_INTERVAL: 5000, - ENROLLMENT_MAX_POLL_TIMES: 120, - // EnrollmentSpeaker is Polling for maximum 10 mins. - ENROLLMENT_POLLING_INTERVAL: 5000, - START_SESSION_DELAY: 8000 - }; - - /*---------------------------------------------------------------- - * constants for AgentPermissions - */ - connect.AgentPermissions = { - OUTBOUND_CALL: 'outboundCall', - VOICE_ID: 'voiceId' - }; - - /*---------------------------------------------------------------- - * class Agent - */ - var Agent = function Agent() { - if (!connect.agent.initialized) { - throw new connect.StateError("The agent is not yet initialized!"); - } - }; - Agent.prototype._getData = function () { - return connect.core.getAgentDataProvider().getAgentData(); - }; - Agent.prototype._createContactAPI = function (contactData) { - return new connect.Contact(contactData.contactId); - }; - - /** - * @deprecated - * Use `contact.onPending` for any particular contact instead. - */ - Agent.prototype.onContactPending = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.CONTACT_PENDING, f); - }; - Agent.prototype.onRefresh = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.REFRESH, f); - }; - Agent.prototype.onRoutable = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ROUTABLE, f); - }; - Agent.prototype.onNotRoutable = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.NOT_ROUTABLE, f); - }; - Agent.prototype.onOffline = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.OFFLINE, f); - }; - Agent.prototype.onError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ERROR, f); - }; - Agent.prototype.onSoftphoneError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.SOFTPHONE_ERROR, f); - }; - Agent.prototype.onWebSocketConnectionLost = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, f); - }; - Agent.prototype.onWebSocketConnectionGained = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, f); - }; - Agent.prototype.onAfterCallWork = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ACW, f); - }; - Agent.prototype.onStateChange = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.STATE_CHANGE, f); - }; - Agent.prototype.onMuteToggle = function (f) { - connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE, f); - }; - Agent.prototype.onLocalMediaStreamCreated = function (f) { - connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, f); - }; - Agent.prototype.onSpeakerDeviceChanged = function (f) { - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, f); - }; - Agent.prototype.onMicrophoneDeviceChanged = function (f) { - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, f); - }; - Agent.prototype.onRingerDeviceChanged = function (f) { - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, f); - }; - Agent.prototype.mute = function () { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.MUTE, - data: { - mute: true - } - }); - }; - Agent.prototype.unmute = function () { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.MUTE, - data: { - mute: false - } - }); - }; - Agent.prototype.setSpeakerDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, - data: { - deviceId: deviceId - } - }); - }; - Agent.prototype.setMicrophoneDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, - data: { - deviceId: deviceId - } - }); - }; - Agent.prototype.setRingerDevice = function (deviceId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SET_RINGER_DEVICE, - data: { - deviceId: deviceId +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + /*---------------------------------------------------------------- + * enum AgentStateType + */ + connect.AgentStateType = connect.makeEnum(['init', 'routable', 'not_routable', 'offline']); + connect.AgentStatusType = connect.AgentStateType; + + /** + * enum AgentAvailStates + */ + connect.AgentAvailStates = connect.makeEnum(['Init', 'Busy', 'AfterCallWork', 'CallingCustomer', 'Dialing', 'Joining', 'PendingAvailable', 'PendingBusy']); + + /** + * enum AgentErrorStates + */ + connect.AgentErrorStates = connect.makeEnum(['Error', 'AgentHungUp', 'BadAddressAgent', 'BadAddressCustomer', 'Default', 'FailedConnectAgent', 'FailedConnectCustomer', 'InvalidLocale', 'LineEngagedAgent', 'LineEngagedCustomer', 'MissedCallAgent', 'MissedCallCustomer', 'MultipleCcpWindows', 'RealtimeCommunicationError']); + + /*---------------------------------------------------------------- + * enum AddressType + */ + connect.EndpointType = connect.makeEnum(['phone_number', 'agent', 'queue']); + connect.AddressType = connect.EndpointType; + + /*---------------------------------------------------------------- + * enum ConnectionType + */ + connect.ConnectionType = connect.makeEnum(['agent', 'inbound', 'outbound', 'monitoring']); + + /*---------------------------------------------------------------- + * enum ConnectionStateType + */ + connect.ConnectionStateType = connect.makeEnum(['init', 'connecting', 'connected', 'hold', 'disconnected']); + connect.ConnectionStatusType = connect.ConnectionStateType; + connect.CONNECTION_ACTIVE_STATES = connect.set([connect.ConnectionStateType.CONNECTING, connect.ConnectionStateType.CONNECTED, connect.ConnectionStateType.HOLD]); + + /*---------------------------------------------------------------- + * enum ContactStateType + */ + connect.ContactStateType = connect.makeEnum(['init', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'error', 'ended']); + connect.ContactStatusType = connect.ContactStateType; + connect.CONTACT_ACTIVE_STATES = connect.makeEnum(['incoming', 'pending', 'connecting', 'connected']); + + /*---------------------------------------------------------------- + * enum ContactType + */ + connect.ContactType = connect.makeEnum(['voice', 'queue_callback', 'chat', 'task']); + + /*---------------------------------------------------------------- + * enum ContactInitiationMethod + */ + connect.ContactInitiationMethod = connect.makeEnum(['inbound', 'outbound', 'transfer', 'queue_transfer', 'callback', 'api', 'disconnect']); + + /*---------------------------------------------------------------- + * enum ChannelType + */ + connect.ChannelType = connect.makeEnum(['VOICE', 'CHAT', 'TASK']); + + /*---------------------------------------------------------------- + * enum MediaType + */ + connect.MediaType = connect.makeEnum(['softphone', 'chat', 'task']); + + /*---------------------------------------------------------------- + * enum SoftphoneCallType + */ + connect.SoftphoneCallType = connect.makeEnum(['audio_video', 'video_only', 'audio_only', 'none']); + + /*---------------------------------------------------------------- + * enum for SoftphoneErrorTypes + */ + connect.SoftphoneErrorTypes = connect.makeEnum(['unsupported_browser', 'microphone_not_shared', 'signalling_handshake_failure', 'signalling_connection_failure', 'ice_collection_timeout', 'user_busy_error', 'webrtc_error', 'realtime_communication_error', 'other']); + + /*---------------------------------------------------------------- + * enum for VoiceIdErrorTypes + */ + connect.VoiceIdErrorTypes = connect.makeEnum(['no_speaker_id_found', 'speaker_id_not_enrolled', 'get_speaker_id_failed', 'get_speaker_status_failed', 'opt_out_speaker_failed', 'opt_out_speaker_in_lcms_failed', 'delete_speaker_failed', 'start_session_failed', 'evaluate_speaker_failed', 'session_not_exists', 'describe_session_failed', 'enroll_speaker_failed', 'update_speaker_id_failed', 'update_speaker_id_in_lcms_failed', 'not_supported_on_conference_calls', 'enroll_speaker_timeout', 'evaluate_speaker_timeout', 'get_domain_id_failed', 'no_domain_id_found']); + + /*---------------------------------------------------------------- + * enum for CTI exceptions + */ + connect.CTIExceptions = connect.makeEnum(["AccessDeniedException", "InvalidStateException", "BadEndpointException", "InvalidAgentARNException", "InvalidConfigurationException", "InvalidContactTypeException", "PaginationException", "RefreshTokenExpiredException", "SendDataFailedException", "UnauthorizedException", "QuotaExceededException"]); + /*---------------------------------------------------------------- + * enum for VoiceId streaming status + */ + connect.VoiceIdStreamingStatus = connect.makeEnum(["ONGOING", "ENDED", "PENDING_CONFIGURATION"]); + + /*---------------------------------------------------------------- + * enum for VoiceId authentication decision + */ + connect.VoiceIdAuthenticationDecision = connect.makeEnum(["ACCEPT", "REJECT", "NOT_ENOUGH_SPEECH", "SPEAKER_NOT_ENROLLED", "SPEAKER_OPTED_OUT", "SPEAKER_ID_NOT_PROVIDED", "SPEAKER_EXPIRED"]); + + /*---------------------------------------------------------------- + * enum for VoiceId fraud detection decision + */ + connect.VoiceIdFraudDetectionDecision = connect.makeEnum(["NOT_ENOUGH_SPEECH", "HIGH_RISK", "LOW_RISK"]); + + /*---------------------------------------------------------------- + * enum for contact flow authentication decision + */ + connect.ContactFlowAuthenticationDecision = connect.makeEnum(["Authenticated", "NotAuthenticated", "Inconclusive", "NotEnrolled", "OptedOut", "NotEnabled", "Error"]); + + /*---------------------------------------------------------------- + * enum for contact flow fraud detection decision + */ + connect.ContactFlowFraudDetectionDecision = connect.makeEnum(["HighRisk", "LowRisk", "Inconclusive", "NotEnabled", "Error"]); + + /*---------------------------------------------------------------- + * enum for VoiceId EnrollmentRequest Status + */ + connect.VoiceIdEnrollmentRequestStatus = connect.makeEnum(["NOT_ENOUGH_SPEECH", "IN_PROGRESS", "COMPLETED", "FAILED"]); + + /*---------------------------------------------------------------- + * enum for VoiceId Speaker status + */ + connect.VoiceIdSpeakerStatus = connect.makeEnum(["OPTED_OUT", "ENROLLED", "PENDING"]); + connect.VoiceIdConstants = { + EVALUATE_SESSION_DELAY: 10000, + EVALUATION_MAX_POLL_TIMES: 24, + // EvaluateSpeaker is Polling for maximum 2 mins. + EVALUATION_POLLING_INTERVAL: 5000, + ENROLLMENT_MAX_POLL_TIMES: 120, + // EnrollmentSpeaker is Polling for maximum 10 mins. + ENROLLMENT_POLLING_INTERVAL: 5000, + START_SESSION_DELAY: 8000 + }; + + /*---------------------------------------------------------------- + * constants for AgentPermissions + */ + connect.AgentPermissions = { + OUTBOUND_CALL: 'outboundCall', + VOICE_ID: 'voiceId' + }; + + /*---------------------------------------------------------------- + * class Agent + */ + var Agent = function Agent() { + if (!connect.agent.initialized) { + throw new connect.StateError("The agent is not yet initialized!"); + } + }; + Agent.prototype._getData = function () { + return connect.core.getAgentDataProvider().getAgentData(); + }; + Agent.prototype._createContactAPI = function (contactData) { + return new connect.Contact(contactData.contactId); + }; + + /** + * @deprecated + * Use `contact.onPending` for any particular contact instead. + */ + Agent.prototype.onContactPending = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.CONTACT_PENDING, f); + }; + Agent.prototype.onRefresh = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.REFRESH, f); + }; + Agent.prototype.onRoutable = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ROUTABLE, f); + }; + Agent.prototype.onNotRoutable = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.NOT_ROUTABLE, f); + }; + Agent.prototype.onOffline = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.OFFLINE, f); + }; + Agent.prototype.onError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ERROR, f); + }; + Agent.prototype.onSoftphoneError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.SOFTPHONE_ERROR, f); + }; + Agent.prototype.onWebSocketConnectionLost = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, f); + }; + Agent.prototype.onWebSocketConnectionGained = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED, f); + }; + Agent.prototype.onAfterCallWork = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ACW, f); + }; + Agent.prototype.onStateChange = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.STATE_CHANGE, f); + }; + Agent.prototype.onMuteToggle = function (f) { + connect.core.getUpstream().onUpstream(connect.AgentEvents.MUTE_TOGGLE, f); + }; + Agent.prototype.onLocalMediaStreamCreated = function (f) { + connect.core.getUpstream().onUpstream(connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, f); + }; + Agent.prototype.onSpeakerDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, f); + }; + Agent.prototype.onMicrophoneDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, f); + }; + Agent.prototype.onRingerDeviceChanged = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, f); + }; + Agent.prototype.mute = function () { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE, + data: { + mute: true + } + }); + }; + Agent.prototype.unmute = function () { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE, + data: { + mute: false + } + }); + }; + Agent.prototype.setSpeakerDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_SPEAKER_DEVICE, + data: { + deviceId: deviceId + } + }); + }; + Agent.prototype.setMicrophoneDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, + data: { + deviceId: deviceId + } + }); + }; + Agent.prototype.setRingerDevice = function (deviceId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SET_RINGER_DEVICE, + data: { + deviceId: deviceId + } + }); + }; + Agent.prototype.getState = function () { + return this._getData().snapshot.state; + }; + Agent.prototype.getNextState = function () { + return this._getData().snapshot.nextState; + }; + Agent.prototype.getAvailabilityState = function () { + return this._getData().snapshot.agentAvailabilityState; + }; + Agent.prototype.getStatus = Agent.prototype.getState; + Agent.prototype.getStateDuration = function () { + return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew(); + }; + Agent.prototype.getStatusDuration = Agent.prototype.getStateDuration; + Agent.prototype.getPermissions = function () { + return this.getConfiguration().permissions; + }; + Agent.prototype.getContacts = function (contactTypeFilter) { + var self = this; + return this._getData().snapshot.contacts.map(function (contactData) { + return self._createContactAPI(contactData); + }).filter(function (contact) { + return !contactTypeFilter || contact.getType() === contactTypeFilter; + }); + }; + Agent.prototype.getConfiguration = function () { + return this._getData().configuration; + }; + Agent.prototype.getAgentStates = function () { + return this.getConfiguration().agentStates; + }; + Agent.prototype.getRoutingProfile = function () { + return this.getConfiguration().routingProfile; + }; + Agent.prototype.getChannelConcurrency = function (channel) { + var channelConcurrencyMap = this.getRoutingProfile().channelConcurrencyMap; + if (!channelConcurrencyMap) { + channelConcurrencyMap = Object.keys(connect.ChannelType).reduce(function (acc, key) { + // Exclude TASK from default concurrency. + if (key !== 'TASK') { + acc[connect.ChannelType[key]] = 1; + } + return acc; + }, {}); + } + return channel ? channelConcurrencyMap[channel] || 0 : channelConcurrencyMap; + }; + Agent.prototype.getName = function () { + return this.getConfiguration().name; + }; + Agent.prototype.getExtension = function () { + return this.getConfiguration().extension; + }; + Agent.prototype.getDialableCountries = function () { + return this.getConfiguration().dialableCountries; + }; + Agent.prototype.isSoftphoneEnabled = function () { + return this.getConfiguration().softphoneEnabled; + }; + Agent.prototype.setConfiguration = function (configuration, callbacks) { + var client = connect.core.getClient(); + if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { + if (callbacks && callbacks.failure) { + callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); + } + } else { + client.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { + configuration: connect.assertNotNull(configuration, 'configuration') + }, { + success: function success(data) { + // We need to ask the shared worker to reload agent config + // once we change it so every tab has accurate config. + var conduit = connect.core.getUpstream(); + conduit.sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION); + if (callbacks.success) { + callbacks.success(data); + } + }, + failure: callbacks && callbacks.failure + }); + } + }; + Agent.prototype.setState = function (state, callbacks, options) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.PUT_AGENT_STATE, { + state: connect.assertNotNull(state, 'state'), + enqueueNextState: options && !!options.enqueueNextState + }, callbacks); + }; + Agent.prototype.onEnqueuedNextState = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, f); + }; + Agent.prototype.setStatus = Agent.prototype.setState; + Agent.prototype.connect = function (endpointIn, params) { + var client = connect.core.getClient(); + var endpoint = new connect.Endpoint(endpointIn); + // Have to remove the endpointId field or AWS JS SDK gets mad. + delete endpoint.endpointId; + client.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, { + endpoint: connect.assertNotNull(endpoint, 'endpoint'), + queueARN: params && (params.queueARN || params.queueId) || this.getRoutingProfile().defaultOutboundQueue.queueARN + }, params && { + success: params.success, + failure: params.failure + }); + }; + Agent.prototype.getAllQueueARNs = function () { + return this.getConfiguration().routingProfile.queues.map(function (queue) { + return queue.queueARN; + }); + }; + Agent.prototype.getEndpoints = function (queueARNs, callbacks, pageInfoIn) { + var self = this; + var client = connect.core.getClient(); + connect.assertNotNull(callbacks, "callbacks"); + connect.assertNotNull(callbacks.success, "callbacks.success"); + var pageInfo = pageInfoIn || {}; + pageInfo.endpoints = pageInfo.endpoints || []; + pageInfo.maxResults = pageInfo.maxResults || connect.DEFAULT_BATCH_SIZE; + + // Backwards compatibility allowing a single queueARN to be specified + // instead of an array. + if (!connect.isArray(queueARNs)) { + queueARNs = [queueARNs]; + } + client.call(connect.ClientMethods.GET_ENDPOINTS, { + queueARNs: queueARNs, + nextToken: pageInfo.nextToken || null, + maxResults: pageInfo.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.getEndpoints(queueARNs, callbacks, { + nextToken: data.nextToken, + maxResults: pageInfo.maxResults, + endpoints: pageInfo.endpoints.concat(data.endpoints) + }); + } else { + pageInfo.endpoints = pageInfo.endpoints.concat(data.endpoints); + var endpoints = pageInfo.endpoints.map(function (endpoint) { + return new connect.Endpoint(endpoint); + }); + callbacks.success({ + endpoints: endpoints, + addresses: endpoints + }); + } + }, + failure: callbacks.failure + }); + }; + Agent.prototype.getAddresses = Agent.prototype.getEndpoints; + + //Internal identifier. + Agent.prototype._getResourceId = function () { + queueArns = this.getAllQueueARNs(); + var _iterator = _createForOfIteratorHelper(queueArns), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var queueArn = _step.value; + var agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); + if (agentIdMatch) { + return agentIdMatch[1]; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns); + }; + Agent.prototype.toSnapshot = function () { + return new connect.AgentSnapshot(this._getData()); + }; + + /*---------------------------------------------------------------- + * class AgentSnapshot + */ + var AgentSnapshot = function AgentSnapshot(agentData) { + connect.Agent.call(this); + this.agentData = agentData; + }; + AgentSnapshot.prototype = Object.create(Agent.prototype); + AgentSnapshot.prototype.constructor = AgentSnapshot; + AgentSnapshot.prototype._getData = function () { + return this.agentData; + }; + AgentSnapshot.prototype._createContactAPI = function (contactData) { + return new connect.ContactSnapshot(contactData); + }; + + /*---------------------------------------------------------------- + * class Contact + */ + var Contact = function Contact(contactId) { + this.contactId = contactId; + }; + Contact.prototype._getData = function () { + return connect.core.getAgentDataProvider().getContactData(this.getContactId()); + }; + Contact.prototype._createConnectionAPI = function (connectionData) { + if (this.getType() === connect.ContactType.CHAT) { + return new connect.ChatConnection(this.contactId, connectionData.connectionId); + } else if (this.getType() === connect.ContactType.TASK) { + return new connect.TaskConnection(this.contactId, connectionData.connectionId); + } else { + return new connect.VoiceConnection(this.contactId, connectionData.connectionId); + } + }; + Contact.prototype.getEventName = function (eventName) { + return connect.core.getContactEventName(eventName, this.getContactId()); + }; + Contact.prototype.onRefresh = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.REFRESH), f); + }; + Contact.prototype.onIncoming = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.INCOMING), f); + }; + Contact.prototype.onConnecting = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTING), f); + }; + Contact.prototype.onPending = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.PENDING), f); + }; + Contact.prototype.onAccepted = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), f); + }; + Contact.prototype.onMissed = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.MISSED), f); + }; + Contact.prototype.onEnded = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ENDED), f); + bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + }; + Contact.prototype.onDestroy = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); + }; + Contact.prototype.onACW = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ACW), f); + }; + Contact.prototype.onConnected = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTED), f); + }; + Contact.prototype.onError = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(this.getEventName(connect.ContactEvents.ERROR), f); + }; + Contact.prototype.getContactId = function () { + return this.contactId; + }; + Contact.prototype.getOriginalContactId = function () { + return this._getData().initialContactId; + }; + Contact.prototype.getInitialContactId = Contact.prototype.getOriginalContactId; + Contact.prototype.getType = function () { + return this._getData().type; + }; + Contact.prototype.getContactDuration = function () { + return this._getData().contactDuration; + }; + Contact.prototype.getState = function () { + return this._getData().state; + }; + Contact.prototype.getStatus = Contact.prototype.getState; + Contact.prototype.getStateDuration = function () { + return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); + }; + Contact.prototype.getStatusDuration = Contact.prototype.getStateDuration; + Contact.prototype.getQueue = function () { + return this._getData().queue; + }; + Contact.prototype.getQueueTimestamp = function () { + return this._getData().queueTimestamp; + }; + Contact.prototype.getConnections = function () { + var self = this; + return this._getData().connections.map(function (connData) { + if (self.getType() === connect.ContactType.CHAT) { + return new connect.ChatConnection(self.contactId, connData.connectionId); + } else if (self.getType() === connect.ContactType.TASK) { + return new connect.TaskConnection(self.contactId, connData.connectionId); + } else { + return new connect.VoiceConnection(self.contactId, connData.connectionId); + } + }); + }; + Contact.prototype.getInitialConnection = function () { + return connect.find(this.getConnections(), function (conn) { + return conn.isInitialConnection(); + }) || null; + }; + Contact.prototype.getActiveInitialConnection = function () { + var initialConn = this.getInitialConnection(); + if (initialConn != null && initialConn.isActive()) { + return initialConn; + } else { + return null; + } + }; + Contact.prototype.getThirdPartyConnections = function () { + return this.getConnections().filter(function (conn) { + return !conn.isInitialConnection() && conn.getType() !== connect.ConnectionType.AGENT; + }); + }; + Contact.prototype.getSingleActiveThirdPartyConnection = function () { + return this.getThirdPartyConnections().filter(function (conn) { + return conn.isActive(); + })[0] || null; + }; + Contact.prototype.getAgentConnection = function () { + return connect.find(this.getConnections(), function (conn) { + var connType = conn.getType(); + return connType === connect.ConnectionType.AGENT || connType === connect.ConnectionType.MONITORING; + }); + }; + Contact.prototype.getName = function () { + return this._getData().name; + }; + Contact.prototype.getContactMetadata = function () { + return this._getData().contactMetadata; + }; + Contact.prototype.getDescription = function () { + return this._getData().description; + }; + Contact.prototype.getReferences = function () { + return this._getData().references; + }; + Contact.prototype.getAttributes = function () { + return this._getData().attributes; + }; + Contact.prototype.getContactFeatures = function () { + return this._getData().contactFeatures; + }; + Contact.prototype.isSoftphoneCall = function () { + return connect.find(this.getConnections(), function (conn) { + return conn.getSoftphoneMediaInfo() != null; + }) != null; + }; + Contact.prototype._isInbound = function () { + var initiationMethod = this._getData().initiationMethod; + return initiationMethod === connect.ContactInitiationMethod.OUTBOUND ? false : true; + }; + Contact.prototype.isInbound = function () { + var conn = this.getInitialConnection(); + + // We will gradually change checking inbound by relying on contact initiationMethod + if (conn.getMediaType() === connect.MediaType.TASK) { + return this._isInbound(); + } + return conn ? conn.getType() === connect.ConnectionType.INBOUND : false; + }; + Contact.prototype.isConnected = function () { + return this.getStatus().type === connect.ContactStateType.CONNECTED; + }; + Contact.prototype.accept = function (callbacks) { + var client = connect.core.getClient(); + var self = this; + var contactId = this.getContactId(); + client.call(connect.ClientMethods.ACCEPT_CONTACT, { + contactId: contactId + }, { + success: function success(data) { + var conduit = connect.core.getUpstream(); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.ACCEPTED, + data: new connect.Contact(contactId) + }); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, self.getContactId()), + data: new connect.Contact(contactId) + }); + + // In Firefox, there's a browser restriction that an unfocused browser tab is not allowed to access the user's microphone. + // The problem is that the restriction could cause a webrtc session creation timeout error when you get an incoming call while you are not on the primary tab. + // It was hard to workaround the issue especially when you have multiple tabs open because you needed to find the right tab and accept the contact before the timeout. + // To avoid the error, when multiple tabs are open in Firefox, a webrtc session is not immediately created as an incoming softphone contact is detected. + // Instead, it waits until contact.accept() is called on a tab and lets the tab become the new primary tab and start the web rtc session there + // because the tab should be focused at the moment and have access to the user's microphone. + var contact = new connect.Contact(contactId); + if (connect.isFirefoxBrowser() && contact.isSoftphoneCall()) { + connect.core.triggerReadyToStartSessionEvent(); + } + if (callbacks && callbacks.success) { + callbacks.success(data); + } + }, + failure: callbacks ? callbacks.failure : null + }); + }; + Contact.prototype.destroy = function () { + connect.getLog().warn("contact.destroy() has been deprecated."); + }; + Contact.prototype.reject = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.REJECT_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.complete = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.COMPLETE_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.clear = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.CLEAR_CONTACT, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.notifyIssue = function (issueCode, description, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { + contactId: this.getContactId(), + issueCode: issueCode, + description: description + }, callbacks); + }; + Contact.prototype.addConnection = function (endpointIn, callbacks) { + var client = connect.core.getClient(); + var endpoint = new connect.Endpoint(endpointIn); + // Have to remove the endpointId field or AWS JS SDK gets mad. + delete endpoint.endpointId; + client.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { + contactId: this.getContactId(), + endpoint: endpoint + }, callbacks); + }; + Contact.prototype.toggleActiveConnections = function (callbacks) { + var client = connect.core.getClient(); + var connectionId = null; + var holdingConn = connect.find(this.getConnections(), function (conn) { + return conn.getStatus().type === connect.ConnectionStateType.HOLD; + }); + if (holdingConn != null) { + connectionId = holdingConn.getConnectionId(); + } else { + var activeConns = this.getConnections().filter(function (conn) { + return conn.isActive(); + }); + if (activeConns.length > 0) { + connectionId = activeConns[0].getConnectionId(); + } + } + client.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { + contactId: this.getContactId(), + connectionId: connectionId + }, callbacks); + }; + Contact.prototype.sendSoftphoneMetrics = function (softphoneStreamStatistics, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + softphoneStreamStatistics: softphoneStreamStatistics + }, callbacks); + connect.publishSoftphoneStats({ + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + stats: softphoneStreamStatistics + }); + }; + Contact.prototype.sendSoftphoneReport = function (report, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + report: report + }, callbacks); + connect.publishSoftphoneReport({ + contactId: this.getContactId(), + ccpVersion: global.ccpVersion, + report: report + }); + }; + Contact.prototype.conferenceConnections = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { + contactId: this.getContactId() + }, callbacks); + }; + Contact.prototype.toSnapshot = function () { + return new connect.ContactSnapshot(this._getData()); + }; + + /*---------------------------------------------------------------- + * class ContactSnapshot + */ + var ContactSnapshot = function ContactSnapshot(contactData) { + connect.Contact.call(this, contactData.contactId); + this.contactData = contactData; + }; + ContactSnapshot.prototype = Object.create(Contact.prototype); + ContactSnapshot.prototype.constructor = ContactSnapshot; + ContactSnapshot.prototype._getData = function () { + return this.contactData; + }; + ContactSnapshot.prototype._createConnectionAPI = function (connectionData) { + return new connect.ConnectionSnapshot(connectionData); + }; + + /*---------------------------------------------------------------- + * class Connection + */ + var Connection = function Connection(contactId, connectionId) { + this.contactId = contactId; + this.connectionId = connectionId; + this._initMediaController(); + }; + Connection.prototype._getData = function () { + return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(), this.getConnectionId()); + }; + Connection.prototype.getContactId = function () { + return this.contactId; + }; + Connection.prototype.getConnectionId = function () { + return this.connectionId; + }; + Connection.prototype.getEndpoint = function () { + return new connect.Endpoint(this._getData().endpoint); + }; + Connection.prototype.getAddress = Connection.prototype.getEndpoint; + Connection.prototype.getState = function () { + return this._getData().state; + }; + Connection.prototype.getStatus = Connection.prototype.getState; + Connection.prototype.getStateDuration = function () { + return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); + }; + Connection.prototype.getStatusDuration = Connection.prototype.getStateDuration; + Connection.prototype.getType = function () { + return this._getData().type; + }; + Connection.prototype.isInitialConnection = function () { + return this._getData().initial; + }; + Connection.prototype.isActive = function () { + return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type); + }; + Connection.prototype.isConnected = function () { + return this.getStatus().type === connect.ConnectionStateType.CONNECTED; + }; + Connection.prototype.isConnecting = function () { + return this.getStatus().type === connect.ConnectionStateType.CONNECTING; + }; + Connection.prototype.isOnHold = function () { + return this.getStatus().type === connect.ConnectionStateType.HOLD; + }; + Connection.prototype.getSoftphoneMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; + + /** + * Gets the currently monitored contact info, Returns null if does not exists. + * @return {{agentName:string, customerName:string, joinTime:Date}} + */ + Connection.prototype.getMonitorInfo = function () { + return this._getData().monitoringInfo; + }; + Connection.prototype.destroy = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.DESTROY_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.sendDigits = function (digits, callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.SEND_DIGITS, { + contactId: this.getContactId(), + connectionId: this.getConnectionId(), + digits: digits + }, callbacks); + }; + Connection.prototype.hold = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.HOLD_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.resume = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.RESUME_CONNECTION, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + Connection.prototype.toSnapshot = function () { + return new connect.ConnectionSnapshot(this._getData()); + }; + Connection.prototype._initMediaController = function () { + if (this.getMediaInfo()) { + connect.core.mediaFactory.get(this)["catch"](function () {}); + } + }; + + // Method for checking whether this connection is an agent-side connection + // (type AGENT or MONITORING) + Connection.prototype._isAgentConnectionType = function () { + var connectionType = this.getType(); + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; + }; + + /** + * Utility method for checking whether this connection is an agent-side connection + * (type AGENT or MONITORING) + * @return {boolean} True if this connection is an agent-side connection. False otherwise. + */ + Connection.prototype._isAgentConnectionType = function () { + var connectionType = this.getType(); + return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; + }; + + /*---------------------------------------------------------------- + * Voice authenticator VoiceId + */ + + var VoiceId = function VoiceId(contactId) { + this.contactId = contactId; + }; + VoiceId.prototype.getSpeakerId = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.GET_CONTACT, { + "contactId": self.contactId, + "instanceId": connect.core.getAgentDataProvider().getInstanceId(), + "awsAccountId": connect.core.getAgentDataProvider().getAWSAccountId() + }, { + success: function success(data) { + if (data.contactData.customerId) { + var obj = { + speakerId: data.contactData.customerId + }; + connect.getLog().info("getSpeakerId succeeded").withObject(data).sendInternalLogToServer(); + resolve(obj); + } else { + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); + reject(error); + } + }, + failure: function failure(err) { + connect.getLog().error("Get SpeakerId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", err); + reject(error); + } + }); + }); + }; + VoiceId.prototype.getSpeakerStatus = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, { + "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("getSpeakerStatus succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + var data = parsedErr; + data.type = data.type ? data.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED; + connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(); + resolve(data); + break; + default: + connect.getLog().error("getSpeakerStatus failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", err); + reject(error); } - }); - }; - Agent.prototype.getState = function () { - return this._getData().snapshot.state; - }; - Agent.prototype.getNextState = function () { - return this._getData().snapshot.nextState; - }; - Agent.prototype.getAvailabilityState = function () { - return this._getData().snapshot.agentAvailabilityState; - }; - Agent.prototype.getStatus = Agent.prototype.getState; - Agent.prototype.getStateDuration = function () { - return connect.now() - this._getData().snapshot.state.startTimestamp.getTime() + connect.core.getSkew(); - }; - Agent.prototype.getStatusDuration = Agent.prototype.getStateDuration; - Agent.prototype.getPermissions = function () { - return this.getConfiguration().permissions; - }; - Agent.prototype.getContacts = function (contactTypeFilter) { - var self = this; - return this._getData().snapshot.contacts.map(function (contactData) { - return self._createContactAPI(contactData); - }).filter(function (contact) { - return !contactTypeFilter || contact.getType() === contactTypeFilter; - }); - }; - Agent.prototype.getConfiguration = function () { - return this._getData().configuration; - }; - Agent.prototype.getAgentStates = function () { - return this.getConfiguration().agentStates; - }; - Agent.prototype.getRoutingProfile = function () { - return this.getConfiguration().routingProfile; - }; - Agent.prototype.getChannelConcurrency = function (channel) { - var channelConcurrencyMap = this.getRoutingProfile().channelConcurrencyMap; - if (!channelConcurrencyMap) { - channelConcurrencyMap = Object.keys(connect.ChannelType).reduce(function (acc, key) { - // Exclude TASK from default concurrency. - if (key !== 'TASK') { - acc[connect.ChannelType[key]] = 1; - } - return acc; - }, {}); } - return channel ? channelConcurrencyMap[channel] || 0 : channelConcurrencyMap; - }; - Agent.prototype.getName = function () { - return this.getConfiguration().name; - }; - Agent.prototype.getExtension = function () { - return this.getConfiguration().extension; - }; - Agent.prototype.getDialableCountries = function () { - return this.getConfiguration().dialableCountries; - }; - Agent.prototype.isSoftphoneEnabled = function () { - return this.getConfiguration().softphoneEnabled; - }; - Agent.prototype.setConfiguration = function (configuration, callbacks) { - var client = connect.core.getClient(); - if (configuration && configuration.agentPreferences && !connect.isValidLocale(configuration.agentPreferences.locale)) { - if (callbacks && callbacks.failure) { - callbacks.failure(connect.AgentErrorStates.INVALID_LOCALE); - } - } else { - client.call(connect.ClientMethods.UPDATE_AGENT_CONFIGURATION, { - configuration: connect.assertNotNull(configuration, 'configuration') - }, { - success: function success(data) { - // We need to ask the shared worker to reload agent config - // once we change it so every tab has accurate config. - var conduit = connect.core.getUpstream(); - conduit.sendUpstream(connect.EventType.RELOAD_AGENT_CONFIGURATION); - if (callbacks.success) { - callbacks.success(data); - } - }, - failure: callbacks && callbacks.failure - }); + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + + // internal only + VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { + var self = this; + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { + "ContactId": self.contactId, + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), + "VoiceIdResult": { + "SpeakerOptedOut": true + } + }, { + success: function success(data) { + connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("optOutSpeakerInLcms failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", err); + reject(error); + } + }); + }); + }; + VoiceId.prototype.optOutSpeaker = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + var speakerId = data.speakerId; + client.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, { + "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + self._optOutSpeakerInLcms(speakerId)["catch"](function () {}); + connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("optOutSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", err); + reject(error); } - }; - Agent.prototype.setState = function (state, callbacks, options) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.PUT_AGENT_STATE, { - state: connect.assertNotNull(state, 'state'), - enqueueNextState: options && !!options.enqueueNextState - }, callbacks); - }; - Agent.prototype.onEnqueuedNextState = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.AgentEvents.ENQUEUED_NEXT_STATE, f); - }; - Agent.prototype.setStatus = Agent.prototype.setState; - Agent.prototype.connect = function (endpointIn, params) { - var client = connect.core.getClient(); - var endpoint = new connect.Endpoint(endpointIn); - // Have to remove the endpointId field or AWS JS SDK gets mad. - delete endpoint.endpointId; - client.call(connect.ClientMethods.CREATE_OUTBOUND_CONTACT, { - endpoint: connect.assertNotNull(endpoint, 'endpoint'), - queueARN: params && (params.queueARN || params.queueId) || this.getRoutingProfile().defaultOutboundQueue.queueARN - }, params && { - success: params.success, - failure: params.failure - }); - }; - Agent.prototype.getAllQueueARNs = function () { - return this.getConfiguration().routingProfile.queues.map(function (queue) { - return queue.queueARN; - }); - }; - Agent.prototype.getEndpoints = function (queueARNs, callbacks, pageInfoIn) { - var self = this; - var client = connect.core.getClient(); - connect.assertNotNull(callbacks, "callbacks"); - connect.assertNotNull(callbacks.success, "callbacks.success"); - var pageInfo = pageInfoIn || {}; - pageInfo.endpoints = pageInfo.endpoints || []; - pageInfo.maxResults = pageInfo.maxResults || connect.DEFAULT_BATCH_SIZE; - - // Backwards compatibility allowing a single queueARN to be specified - // instead of an array. - if (!connect.isArray(queueARNs)) { - queueARNs = [queueARNs]; + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.deleteSpeaker = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DELETE_SPEAKER, { + "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("deleteSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("deleteSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.startSession = function () { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, { + "contactId": self.contactId, + "instanceId": connect.core.getAgentDataProvider().getInstanceId(), + "customerAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "clientToken": AWS.util.uuid.v4(), + "domainId": domainId + }, { + success: function success(data) { + if (data.sessionId) { + resolve(data); + } else { + connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({ + data: data + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); + reject(error); } - client.call(connect.ClientMethods.GET_ENDPOINTS, { - queueARNs: queueARNs, - nextToken: pageInfo.nextToken || null, - maxResults: pageInfo.maxResults - }, { - success: function success(data) { - if (data.nextToken) { - self.getEndpoints(queueARNs, callbacks, { - nextToken: data.nextToken, - maxResults: pageInfo.maxResults, - endpoints: pageInfo.endpoints.concat(data.endpoints) - }); + }, + failure: function failure(err) { + connect.getLog().error("startVoiceIdSession failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.evaluateSpeaker = function (startNew) { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var pollTimes = 0; + return new Promise(function (resolve, reject) { + function evaluate() { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.EVALUATE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + if (++pollTimes < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) { + if (data.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); } else { - pageInfo.endpoints = pageInfo.endpoints.concat(data.endpoints); - var endpoints = pageInfo.endpoints.map(function (endpoint) { - return new connect.Endpoint(endpoint); - }); - callbacks.success({ - endpoints: endpoints, - addresses: endpoints - }); - } - }, - failure: callbacks.failure - }); - }; - Agent.prototype.getAddresses = Agent.prototype.getEndpoints; + if (!data.AuthenticationResult) { + data.AuthenticationResult = {}; + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED; + } + if (!data.FraudDetectionResult) { + data.FraudDetectionResult = {}; + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; + } - //Internal identifier. - Agent.prototype._getResourceId = function () { - queueArns = this.getAllQueueARNs(); - var _iterator = _createForOfIteratorHelper(queueArns), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var queueArn = _step.value; - var agentIdMatch = queueArn.match(/\/agent\/([^/]+)/); - if (agentIdMatch) { - return agentIdMatch[1]; + // Resolve if both authentication and fraud detection are not enabled. + if (!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } + if (data.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED) { + if (self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision)) { + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; + } + if (self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; + } + } + // Voice print is not long enough for both authentication and fraud detection + if (self.isAuthResultInconclusive(data.AuthenticationResult.Decision) && self.isFraudResultInconclusive(data.FraudDetectionResult.Decision)) { + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } + if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { + switch (data.AuthenticationResult.Decision) { + case connect.VoiceIdAuthenticationDecision.ACCEPT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; + break; + case connect.VoiceIdAuthenticationDecision.REJECT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; + break; + case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; + break; + case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; + break; + default: + data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR; + } + } + if (!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { + switch (data.FraudDetectionResult.Decision) { + case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; + break; + case connect.VoiceIdFraudDetectionDecision.LOW_RISK: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; + break; + default: + data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR; + } + } + if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && !self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { + // Resolve only when both authentication and fraud detection have results. Otherwise, keep polling. + connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + return; + } else { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); + } } + } else { + connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); + reject(error); } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", err); + connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ + err: err + }).sendInternalLogToServer(); + break; + default: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); + connect.getLog().error("evaluateSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + } + reject(error); } - return new Error("Agent.prototype._getResourceId: queueArns did not contain agentResourceId: ", queueArns); - }; - Agent.prototype.toSnapshot = function () { - return new connect.AgentSnapshot(this._getData()); - }; - - /*---------------------------------------------------------------- - * class AgentSnapshot - */ - var AgentSnapshot = function AgentSnapshot(agentData) { - connect.Agent.call(this); - this.agentData = agentData; - }; - AgentSnapshot.prototype = Object.create(Agent.prototype); - AgentSnapshot.prototype.constructor = AgentSnapshot; - AgentSnapshot.prototype._getData = function () { - return this.agentData; - }; - AgentSnapshot.prototype._createContactAPI = function (contactData) { - return new connect.ContactSnapshot(contactData); - }; - - /*---------------------------------------------------------------- - * class Contact - */ - var Contact = function Contact(contactId) { - this.contactId = contactId; - }; - Contact.prototype._getData = function () { - return connect.core.getAgentDataProvider().getContactData(this.getContactId()); - }; - Contact.prototype._createConnectionAPI = function (connectionData) { - if (this.getType() === connect.ContactType.CHAT) { - return new connect.ChatConnection(this.contactId, connectionData.connectionId); - } else if (this.getType() === connect.ContactType.TASK) { - return new connect.TaskConnection(this.contactId, connectionData.connectionId); - } else { - return new connect.VoiceConnection(this.contactId, connectionData.connectionId); + }); + })["catch"](function (err) { + reject(err); + }); + } + if (!startNew) { + self.syncSpeakerId().then(function () { + evaluate(); + })["catch"](function (err) { + connect.getLog().error("syncSpeakerId failed when session startNew=false").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + } else { + self.startSession().then(function (data) { + self.syncSpeakerId().then(function (data) { + setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); + })["catch"](function (err) { + connect.getLog().error("syncSpeakerId failed when session startNew=true").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + })["catch"](function (err) { + connect.getLog().error("startSession failed when session startNew=true").withObject({ + err: err + }).sendInternalLogToServer(); + reject(err); + }); + } + }); + }; + VoiceId.prototype.describeSession = function () { + var self = this; + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("describeSession failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.checkEnrollmentStatus = function () { + var self = this; + var pollingTimes = 0; + return new Promise(function (resolve, reject) { + function describe() { + if (++pollingTimes < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) { + self.describeSession().then(function (data) { + switch (data.Session.EnrollmentRequestDetails.Status) { + case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: + resolve(data); + break; + case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: + setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); + break; + case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: + if (data.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED) { + setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); + } else { + setTimeout(function () { + self.startSession().then(function (data) { + describe(); + })["catch"](function (err, data) { + reject(err); + }); + }, connect.VoiceIdConstants.START_SESSION_DELAY); + } + break; + default: + var message = data.Session.EnrollmentRequestDetails.Message ? data.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; + connect.getLog().error(message).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, message, data.Session.EnrollmentRequestDetails.Status); + reject(error); } - }; - Contact.prototype.getEventName = function (eventName) { - return connect.core.getContactEventName(eventName, this.getContactId()); - }; - Contact.prototype.onRefresh = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.REFRESH), f); - }; - Contact.prototype.onIncoming = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.INCOMING), f); - }; - Contact.prototype.onConnecting = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTING), f); - }; - Contact.prototype.onPending = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.PENDING), f); - }; - Contact.prototype.onAccepted = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ACCEPTED), f); - }; - Contact.prototype.onMissed = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.MISSED), f); - }; - Contact.prototype.onEnded = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ENDED), f); - bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); - }; - Contact.prototype.onDestroy = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.DESTROYED), f); - }; - Contact.prototype.onACW = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ACW), f); - }; - Contact.prototype.onConnected = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.CONNECTED), f); - }; - Contact.prototype.onError = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(this.getEventName(connect.ContactEvents.ERROR), f); - }; - Contact.prototype.getContactId = function () { - return this.contactId; - }; - Contact.prototype.getOriginalContactId = function () { - return this._getData().initialContactId; - }; - Contact.prototype.getInitialContactId = Contact.prototype.getOriginalContactId; - Contact.prototype.getType = function () { - return this._getData().type; - }; - Contact.prototype.getContactDuration = function () { - return this._getData().contactDuration; - }; - Contact.prototype.getState = function () { - return this._getData().state; - }; - Contact.prototype.getStatus = Contact.prototype.getState; - Contact.prototype.getStateDuration = function () { - return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); - }; - Contact.prototype.getStatusDuration = Contact.prototype.getStateDuration; - Contact.prototype.getQueue = function () { - return this._getData().queue; - }; - Contact.prototype.getQueueTimestamp = function () { - return this._getData().queueTimestamp; - }; - Contact.prototype.getConnections = function () { - var self = this; - return this._getData().connections.map(function (connData) { - if (self.getType() === connect.ContactType.CHAT) { - return new connect.ChatConnection(self.contactId, connData.connectionId); - } else if (self.getType() === connect.ContactType.TASK) { - return new connect.TaskConnection(self.contactId, connData.connectionId); - } else { - return new connect.VoiceConnection(self.contactId, connData.connectionId); - } + }); + } else { + connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); + reject(error); + } + } + describe(); + }); + }; + VoiceId.prototype.enrollSpeaker = function () { + var self = this; + self.checkConferenceCall(); + return new Promise(function (resolve, reject) { + self.syncSpeakerId().then(function () { + self.getSpeakerStatus().then(function (data) { + if (data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { + self.deleteSpeaker().then(function () { + self.enrollSpeakerHelper(resolve, reject); + })["catch"](function (err) { + reject(err); }); - }; - Contact.prototype.getInitialConnection = function () { - return connect.find(this.getConnections(), function (conn) { - return conn.isInitialConnection(); - }) || null; - }; - Contact.prototype.getActiveInitialConnection = function () { - var initialConn = this.getInitialConnection(); - if (initialConn != null && initialConn.isActive()) { - return initialConn; - } else { - return null; - } - }; - Contact.prototype.getThirdPartyConnections = function () { - return this.getConnections().filter(function (conn) { - return !conn.isInitialConnection() && conn.getType() !== connect.ConnectionType.AGENT; + } else { + self.enrollSpeakerHelper(resolve, reject); + } + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject) { + var self = this; + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "DomainId": domainId + }, { + success: function success(data) { + if (data.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED) { + connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + } else { + self.checkEnrollmentStatus().then(function (data) { + connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + })["catch"](function (err) { + reject(err); }); - }; - Contact.prototype.getSingleActiveThirdPartyConnection = function () { - return this.getThirdPartyConnections().filter(function (conn) { - return conn.isActive(); - })[0] || null; - }; - Contact.prototype.getAgentConnection = function () { - return connect.find(this.getConnections(), function (conn) { - var connType = conn.getType(); - return connType === connect.ConnectionType.AGENT || connType === connect.ConnectionType.MONITORING; + } + }, + failure: function failure(err) { + connect.getLog().error("enrollSpeaker failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", err); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }; + + // internal only + VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { + var self = this; + var client = connect.core.getClient(); + return new Promise(function (resolve, reject) { + client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { + "ContactId": self.contactId, + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), + "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), + "VoiceIdResult": { + "generatedSpeakerId": speakerId + } + }, { + success: function success(data) { + connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(data).sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err) { + connect.getLog().error("updateSpeakerIdInLcms failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", err); + reject(error); + } + }); + }); + }; + VoiceId.prototype.updateSpeakerIdInVoiceId = function (speakerId) { + var self = this; + self.checkConferenceCall(); + var client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + return new Promise(function (resolve, reject) { + self.getDomainId().then(function (domainId) { + client.call(connect.AgentAppClientMethods.UPDATE_SESSION, { + "SessionNameOrId": contactData.initialContactId || this.contactId, + "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), + "DomainId": domainId + }, { + success: function success(data) { + connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); + self._updateSpeakerIdInLcms(speakerId).then(function () { + resolve(data); + })["catch"](function (err) { + reject(err); }); - }; - Contact.prototype.getName = function () { - return this._getData().name; - }; - Contact.prototype.getContactMetadata = function () { - return this._getData().contactMetadata; - }; - Contact.prototype.getDescription = function () { - return this._getData().description; - }; - Contact.prototype.getReferences = function () { - return this._getData().references; - }; - Contact.prototype.getAttributes = function () { - return this._getData().attributes; - }; - Contact.prototype.getContactFeatures = function () { - return this._getData().contactFeatures; - }; - Contact.prototype.isSoftphoneCall = function () { - return connect.find(this.getConnections(), function (conn) { - return conn.getSoftphoneMediaInfo() != null; - }) != null; - }; - Contact.prototype._isInbound = function () { - var initiationMethod = this._getData().initiationMethod; - return initiationMethod === connect.ContactInitiationMethod.OUTBOUND ? false : true; - }; - Contact.prototype.isInbound = function () { - var conn = this.getInitialConnection(); - - // We will gradually change checking inbound by relying on contact initiationMethod - if (conn.getMediaType() === connect.MediaType.TASK) { - return this._isInbound(); + }, + failure: function failure(err) { + var error; + var parsedErr = JSON.parse(err); + switch (parsedErr.status) { + case 400: + case 404: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", err); + connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ + err: err + }).sendInternalLogToServer(); + break; + default: + error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); + connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ + err: err + }).sendInternalLogToServer(); } - return conn ? conn.getType() === connect.ConnectionType.INBOUND : false; - }; - Contact.prototype.isConnected = function () { - return this.getStatus().type === connect.ContactStateType.CONNECTED; - }; - Contact.prototype.accept = function (callbacks) { - var client = connect.core.getClient(); - var self = this; - var contactId = this.getContactId(); - client.call(connect.ClientMethods.ACCEPT_CONTACT, { - contactId: contactId - }, { - success: function success(data) { - var conduit = connect.core.getUpstream(); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.ACCEPTED, - data: new connect.Contact(contactId) - }); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, self.getContactId()), - data: new connect.Contact(contactId) - }); - - // In Firefox, there's a browser restriction that an unfocused browser tab is not allowed to access the user's microphone. - // The problem is that the restriction could cause a webrtc session creation timeout error when you get an incoming call while you are not on the primary tab. - // It was hard to workaround the issue especially when you have multiple tabs open because you needed to find the right tab and accept the contact before the timeout. - // To avoid the error, when multiple tabs are open in Firefox, a webrtc session is not immediately created as an incoming softphone contact is detected. - // Instead, it waits until contact.accept() is called on a tab and lets the tab become the new primary tab and start the web rtc session there - // because the tab should be focused at the moment and have access to the user's microphone. - var contact = new connect.Contact(contactId); - if (connect.isFirefoxBrowser() && contact.isSoftphoneCall()) { - connect.core.triggerReadyToStartSessionEvent(); - } - if (callbacks && callbacks.success) { - callbacks.success(data); + reject(error); + } + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.syncSpeakerId = function () { + var self = this; + return new Promise(function (resolve, reject) { + self.getSpeakerId().then(function (data) { + self.updateSpeakerIdInVoiceId(data.speakerId).then(function (data) { + resolve(data); + })["catch"](function (err) { + reject(err); + }); + })["catch"](function (err) { + reject(err); + }); + }); + }; + VoiceId.prototype.getDomainId = function () { + return new Promise(function (resolve, reject) { + var agent = new connect.Agent(); + if (!agent.getPermissions().includes(connect.AgentPermissions.VOICE_ID)) { + reject(new Error("Agent doesn't have the permission for Voice ID")); + } else if (connect.core.voiceIdDomainId) { + resolve(connect.core.voiceIdDomainId); + } else { + var client = connect.core.getClient(); + client.call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, { + "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), + "IntegrationType": "VOICE_ID" + }, { + success: function success(data) { + try { + var domainId; + if (data.IntegrationAssociationSummaryList.length >= 1) { + var integrationArn = data.IntegrationAssociationSummaryList[0].IntegrationArn; + domainId = integrationArn.replace(/^.*domain\//i, ''); + } + if (!domainId) { + connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); + reject(error); + return; + } + connect.getLog().info("getDomainId succeeded").withObject(data).sendInternalLogToServer(); + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, + data: { + domainId: domainId } - }, - failure: callbacks ? callbacks.failure : null - }); - }; - Contact.prototype.destroy = function () { - connect.getLog().warn("contact.destroy() has been deprecated."); - }; - Contact.prototype.reject = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.REJECT_CONTACT, { - contactId: this.getContactId() - }, callbacks); - }; - Contact.prototype.complete = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.COMPLETE_CONTACT, { - contactId: this.getContactId() - }, callbacks); - }; - Contact.prototype.clear = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.CLEAR_CONTACT, { - contactId: this.getContactId() - }, callbacks); - }; - Contact.prototype.notifyIssue = function (issueCode, description, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.NOTIFY_CONTACT_ISSUE, { - contactId: this.getContactId(), - issueCode: issueCode, - description: description - }, callbacks); - }; - Contact.prototype.addConnection = function (endpointIn, callbacks) { - var client = connect.core.getClient(); - var endpoint = new connect.Endpoint(endpointIn); - // Have to remove the endpointId field or AWS JS SDK gets mad. - delete endpoint.endpointId; - client.call(connect.ClientMethods.CREATE_ADDITIONAL_CONNECTION, { - contactId: this.getContactId(), - endpoint: endpoint - }, callbacks); - }; - Contact.prototype.toggleActiveConnections = function (callbacks) { - var client = connect.core.getClient(); - var connectionId = null; - var holdingConn = connect.find(this.getConnections(), function (conn) { - return conn.getStatus().type === connect.ConnectionStateType.HOLD; - }); - if (holdingConn != null) { - connectionId = holdingConn.getConnectionId(); - } else { - var activeConns = this.getConnections().filter(function (conn) { - return conn.isActive(); }); - if (activeConns.length > 0) { - connectionId = activeConns[0].getConnectionId(); - } + resolve(domainId); + } catch (err) { + connect.getLog().error("getDomainId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); + reject(error); } - client.call(connect.ClientMethods.TOGGLE_ACTIVE_CONNECTIONS, { - contactId: this.getContactId(), - connectionId: connectionId - }, callbacks); - }; - Contact.prototype.sendSoftphoneMetrics = function (softphoneStreamStatistics, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS, { - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - softphoneStreamStatistics: softphoneStreamStatistics - }, callbacks); - connect.publishSoftphoneStats({ - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - stats: softphoneStreamStatistics - }); - }; - Contact.prototype.sendSoftphoneReport = function (report, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT, { - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - report: report - }, callbacks); - connect.publishSoftphoneReport({ - contactId: this.getContactId(), - ccpVersion: global.ccpVersion, - report: report - }); - }; - Contact.prototype.conferenceConnections = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.CONFERENCE_CONNECTIONS, { - contactId: this.getContactId() - }, callbacks); - }; - Contact.prototype.toSnapshot = function () { - return new connect.ContactSnapshot(this._getData()); - }; - - /*---------------------------------------------------------------- - * class ContactSnapshot - */ - var ContactSnapshot = function ContactSnapshot(contactData) { - connect.Contact.call(this, contactData.contactId); - this.contactData = contactData; - }; - ContactSnapshot.prototype = Object.create(Contact.prototype); - ContactSnapshot.prototype.constructor = ContactSnapshot; - ContactSnapshot.prototype._getData = function () { - return this.contactData; - }; - ContactSnapshot.prototype._createConnectionAPI = function (connectionData) { - return new connect.ConnectionSnapshot(connectionData); - }; - - /*---------------------------------------------------------------- - * class Connection - */ - var Connection = function Connection(contactId, connectionId) { - this.contactId = contactId; - this.connectionId = connectionId; - this._initMediaController(); - }; - Connection.prototype._getData = function () { - return connect.core.getAgentDataProvider().getConnectionData(this.getContactId(), this.getConnectionId()); - }; - Connection.prototype.getContactId = function () { - return this.contactId; - }; - Connection.prototype.getConnectionId = function () { - return this.connectionId; - }; - Connection.prototype.getEndpoint = function () { - return new connect.Endpoint(this._getData().endpoint); - }; - Connection.prototype.getAddress = Connection.prototype.getEndpoint; - Connection.prototype.getState = function () { - return this._getData().state; - }; - Connection.prototype.getStatus = Connection.prototype.getState; - Connection.prototype.getStateDuration = function () { - return connect.now() - this._getData().state.timestamp.getTime() + connect.core.getSkew(); - }; - Connection.prototype.getStatusDuration = Connection.prototype.getStateDuration; - Connection.prototype.getType = function () { - return this._getData().type; - }; - Connection.prototype.isInitialConnection = function () { - return this._getData().initial; - }; - Connection.prototype.isActive = function () { - return connect.contains(connect.CONNECTION_ACTIVE_STATES, this.getStatus().type); - }; - Connection.prototype.isConnected = function () { - return this.getStatus().type === connect.ConnectionStateType.CONNECTED; - }; - Connection.prototype.isConnecting = function () { - return this.getStatus().type === connect.ConnectionStateType.CONNECTING; - }; - Connection.prototype.isOnHold = function () { - return this.getStatus().type === connect.ConnectionStateType.HOLD; - }; - Connection.prototype.getSoftphoneMediaInfo = function () { - return this._getData().softphoneMediaInfo; - }; - - /** - * Gets the currently monitored contact info, Returns null if does not exists. - * @return {{agentName:string, customerName:string, joinTime:Date}} - */ - Connection.prototype.getMonitorInfo = function () { - return this._getData().monitoringInfo; - }; - Connection.prototype.destroy = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.DESTROY_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); - }; - Connection.prototype.sendDigits = function (digits, callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.SEND_DIGITS, { - contactId: this.getContactId(), - connectionId: this.getConnectionId(), - digits: digits - }, callbacks); - }; - Connection.prototype.hold = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.HOLD_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); - }; - Connection.prototype.resume = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.RESUME_CONNECTION, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); - }; - Connection.prototype.toSnapshot = function () { - return new connect.ConnectionSnapshot(this._getData()); - }; - Connection.prototype._initMediaController = function () { - if (this.getMediaInfo()) { - connect.core.mediaFactory.get(this)["catch"](function () { }); - } - }; - - // Method for checking whether this connection is an agent-side connection - // (type AGENT or MONITORING) - Connection.prototype._isAgentConnectionType = function () { - var connectionType = this.getType(); - return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; - }; - - /** - * Utility method for checking whether this connection is an agent-side connection - * (type AGENT or MONITORING) - * @return {boolean} True if this connection is an agent-side connection. False otherwise. - */ - Connection.prototype._isAgentConnectionType = function () { - var connectionType = this.getType(); - return connectionType === connect.ConnectionType.AGENT || connectionType === connect.ConnectionType.MONITORING; - }; - - /*---------------------------------------------------------------- - * Voice authenticator VoiceId - */ - - var VoiceId = function VoiceId(contactId) { - this.contactId = contactId; - }; - VoiceId.prototype.getSpeakerId = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.GET_CONTACT, { - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId(), - "awsAccountId": connect.core.getAgentDataProvider().getAWSAccountId() - }, { - success: function success(data) { - if (data.contactData.customerId) { - var obj = { - speakerId: data.contactData.customerId - }; - connect.getLog().info("getSpeakerId succeeded").withObject(data).sendInternalLogToServer(); - resolve(obj); - } else { - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_SPEAKER_ID_FOUND, "No speakerId assotiated with this call"); - reject(error); - } - }, - failure: function failure(err) { - connect.getLog().error("Get SpeakerId failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_ID_FAILED, "Get SpeakerId failed", err); - reject(error); - } - }); - }); - }; - VoiceId.prototype.getSpeakerStatus = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function (data) { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.DESCRIBE_SPEAKER, { - "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), - "DomainId": domainId - }, { - success: function success(data) { - connect.getLog().info("getSpeakerStatus succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err) { - var error; - var parsedErr = JSON.parse(err); - switch (parsedErr.status) { - case 400: - case 404: - var data = parsedErr; - data.type = data.type ? data.type : connect.VoiceIdErrorTypes.SPEAKER_ID_NOT_ENROLLED; - connect.getLog().info("Speaker is not enrolled.").sendInternalLogToServer(); - resolve(data); - break; - default: - connect.getLog().error("getSpeakerStatus failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_SPEAKER_STATUS_FAILED, "Get SpeakerStatus failed", err); - reject(error); - } - } - }); - })["catch"](function (err) { - reject(err); - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - - // internal only - VoiceId.prototype._optOutSpeakerInLcms = function (speakerId) { - var self = this; - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { - "ContactId": self.contactId, - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), - "VoiceIdResult": { - "SpeakerOptedOut": true - } - }, { - success: function success(data) { - connect.getLog().info("optOutSpeakerInLcms succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err) { - connect.getLog().error("optOutSpeakerInLcms failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_IN_LCMS_FAILED, "optOutSpeakerInLcms failed", err); - reject(error); - } - }); - }); - }; - VoiceId.prototype.optOutSpeaker = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function (data) { - self.getDomainId().then(function (domainId) { - var speakerId = data.speakerId; - client.call(connect.AgentAppClientMethods.OPT_OUT_SPEAKER, { - "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), - "DomainId": domainId - }, { - success: function success(data) { - self._optOutSpeakerInLcms(speakerId)["catch"](function () { }); - connect.getLog().info("optOutSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err) { - connect.getLog().error("optOutSpeaker failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.OPT_OUT_SPEAKER_FAILED, "optOutSpeaker failed.", err); - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.deleteSpeaker = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function (data) { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.DELETE_SPEAKER, { - "SpeakerId": connect.assertNotNull(data.speakerId, 'speakerId'), - "DomainId": domainId - }, { - success: function success(data) { - connect.getLog().info("deleteSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err) { - connect.getLog().error("deleteSpeaker failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DELETE_SPEAKER_FAILED, "deleteSpeaker failed.", err); - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.startSession = function () { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.START_VOICE_ID_SESSION, { - "contactId": self.contactId, - "instanceId": connect.core.getAgentDataProvider().getInstanceId(), - "customerAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "clientToken": AWS.util.uuid.v4(), - "domainId": domainId - }, { - success: function success(data) { - if (data.sessionId) { - resolve(data); - } else { - connect.getLog().error("startVoiceIdSession failed, no session id returned").withObject({ - data: data - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "No session id returned from start session api"); - reject(error); - } - }, - failure: function failure(err) { - connect.getLog().error("startVoiceIdSession failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.START_SESSION_FAILED, "startVoiceIdSession failed", err); - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.evaluateSpeaker = function (startNew) { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var pollTimes = 0; - return new Promise(function (resolve, reject) { - function evaluate() { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.EVALUATE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId": domainId - }, { - success: function success(data) { - if (++pollTimes < connect.VoiceIdConstants.EVALUATION_MAX_POLL_TIMES) { - if (data.StreamingStatus === connect.VoiceIdStreamingStatus.PENDING_CONFIGURATION) { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); - } else { - if (!data.AuthenticationResult) { - data.AuthenticationResult = {}; - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENABLED; - } - if (!data.FraudDetectionResult) { - data.FraudDetectionResult = {}; - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; - } - - // Resolve if both authentication and fraud detection are not enabled. - if (!self.isAuthEnabled(data.AuthenticationResult.Decision) && !self.isFraudEnabled(data.FraudDetectionResult.Decision)) { - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } - if (data.StreamingStatus === connect.VoiceIdStreamingStatus.ENDED) { - if (self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision)) { - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; - } - if (self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; - } - } - // Voice print is not long enough for both authentication and fraud detection - if (self.isAuthResultInconclusive(data.AuthenticationResult.Decision) && self.isFraudResultInconclusive(data.FraudDetectionResult.Decision)) { - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } - if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && self.isAuthEnabled(data.AuthenticationResult.Decision)) { - switch (data.AuthenticationResult.Decision) { - case connect.VoiceIdAuthenticationDecision.ACCEPT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.AUTHENTICATED; - break; - case connect.VoiceIdAuthenticationDecision.REJECT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_AUTHENTICATED; - break; - case connect.VoiceIdAuthenticationDecision.SPEAKER_OPTED_OUT: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.OPTED_OUT; - break; - case connect.VoiceIdAuthenticationDecision.SPEAKER_NOT_ENROLLED: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.NOT_ENROLLED; - break; - default: - data.AuthenticationResult.Decision = connect.ContactFlowAuthenticationDecision.ERROR; - } - } - if (!self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision) && self.isFraudEnabled(data.FraudDetectionResult.Decision)) { - switch (data.FraudDetectionResult.Decision) { - case connect.VoiceIdFraudDetectionDecision.HIGH_RISK: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.HIGH_RISK; - break; - case connect.VoiceIdFraudDetectionDecision.LOW_RISK: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.LOW_RISK; - break; - default: - data.FraudDetectionResult.Decision = connect.ContactFlowFraudDetectionDecision.ERROR; - } - } - if (!self.isAuthResultNotEnoughSpeech(data.AuthenticationResult.Decision) && !self.isFraudResultNotEnoughSpeech(data.FraudDetectionResult.Decision)) { - // Resolve only when both authentication and fraud detection have results. Otherwise, keep polling. - connect.getLog().info("evaluateSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - return; - } else { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATION_POLLING_INTERVAL); - } - } - } else { - connect.getLog().error("evaluateSpeaker timeout").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_TIMEOUT, "evaluateSpeaker timeout"); - reject(error); - } - }, - failure: function failure(err) { - var error; - var parsedErr = JSON.parse(err); - switch (parsedErr.status) { - case 400: - case 404: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "evaluateSpeaker failed, session not exists", err); - connect.getLog().error("evaluateSpeaker failed, session not exists").withObject({ - err: err - }).sendInternalLogToServer(); - break; - default: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.EVALUATE_SPEAKER_FAILED, "evaluateSpeaker failed", err); - connect.getLog().error("evaluateSpeaker failed").withObject({ - err: err - }).sendInternalLogToServer(); - } - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - } - if (!startNew) { - self.syncSpeakerId().then(function () { - evaluate(); - })["catch"](function (err) { - connect.getLog().error("syncSpeakerId failed when session startNew=false").withObject({ - err: err - }).sendInternalLogToServer(); - reject(err); - }); - } else { - self.startSession().then(function (data) { - self.syncSpeakerId().then(function (data) { - setTimeout(evaluate, connect.VoiceIdConstants.EVALUATE_SESSION_DELAY); - })["catch"](function (err) { - connect.getLog().error("syncSpeakerId failed when session startNew=true").withObject({ - err: err - }).sendInternalLogToServer(); - reject(err); - }); - })["catch"](function (err) { - connect.getLog().error("startSession failed when session startNew=true").withObject({ - err: err - }).sendInternalLogToServer(); - reject(err); - }); - } - }); - }; - VoiceId.prototype.describeSession = function () { - var self = this; - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.DESCRIBE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId": domainId - }, { - success: function success(data) { - resolve(data); - }, - failure: function failure(err) { - connect.getLog().error("describeSession failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.DESCRIBE_SESSION_FAILED, "describeSession failed", err); - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.checkEnrollmentStatus = function () { - var self = this; - var pollingTimes = 0; - return new Promise(function (resolve, reject) { - function describe() { - if (++pollingTimes < connect.VoiceIdConstants.ENROLLMENT_MAX_POLL_TIMES) { - self.describeSession().then(function (data) { - switch (data.Session.EnrollmentRequestDetails.Status) { - case connect.VoiceIdEnrollmentRequestStatus.COMPLETED: - resolve(data); - break; - case connect.VoiceIdEnrollmentRequestStatus.IN_PROGRESS: - setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); - break; - case connect.VoiceIdEnrollmentRequestStatus.NOT_ENOUGH_SPEECH: - if (data.Session.StreamingStatus !== connect.VoiceIdStreamingStatus.ENDED) { - setTimeout(describe, connect.VoiceIdConstants.ENROLLMENT_POLLING_INTERVAL); - } else { - setTimeout(function () { - self.startSession().then(function (data) { - describe(); - })["catch"](function (err, data) { - reject(err); - }); - }, connect.VoiceIdConstants.START_SESSION_DELAY); - } - break; - default: - var message = data.Session.EnrollmentRequestDetails.Message ? data.Session.EnrollmentRequestDetails.Message : "enrollSpeaker failed. Unknown enrollment status has been received"; - connect.getLog().error(message).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, message, data.Session.EnrollmentRequestDetails.Status); - reject(error); - } - }); - } else { - connect.getLog().error("enrollSpeaker timeout").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_TIMEOUT, "enrollSpeaker timeout"); - reject(error); - } - } - describe(); - }); - }; - VoiceId.prototype.enrollSpeaker = function () { - var self = this; - self.checkConferenceCall(); - return new Promise(function (resolve, reject) { - self.syncSpeakerId().then(function () { - self.getSpeakerStatus().then(function (data) { - if (data.Speaker && data.Speaker.Status == connect.VoiceIdSpeakerStatus.OPTED_OUT) { - self.deleteSpeaker().then(function () { - self.enrollSpeakerHelper(resolve, reject); - })["catch"](function (err) { - reject(err); - }); - } else { - self.enrollSpeakerHelper(resolve, reject); - } - })["catch"](function (err) { - reject(err); - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.enrollSpeakerHelper = function (resolve, reject) { - var self = this; - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.ENROLL_BY_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "DomainId": domainId - }, { - success: function success(data) { - if (data.Status === connect.VoiceIdEnrollmentRequestStatus.COMPLETED) { - connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - } else { - self.checkEnrollmentStatus().then(function (data) { - connect.getLog().info("enrollSpeaker succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - })["catch"](function (err) { - reject(err); - }); - } - }, - failure: function failure(err) { - connect.getLog().error("enrollSpeaker failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.ENROLL_SPEAKER_FAILED, "enrollSpeaker failed", err); - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - }; - - // internal only - VoiceId.prototype._updateSpeakerIdInLcms = function (speakerId) { - var self = this; - var client = connect.core.getClient(); - return new Promise(function (resolve, reject) { - client.call(connect.AgentAppClientMethods.UPDATE_VOICE_ID_DATA, { - "ContactId": self.contactId, - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "AWSAccountId": connect.core.getAgentDataProvider().getAWSAccountId(), - "CustomerId": connect.assertNotNull(speakerId, 'speakerId'), - "VoiceIdResult": { - "generatedSpeakerId": speakerId - } - }, { - success: function success(data) { - connect.getLog().info("updateSpeakerIdInLcms succeeded").withObject(data).sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err) { - connect.getLog().error("updateSpeakerIdInLcms failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_IN_LCMS_FAILED, "updateSpeakerIdInLcms failed", err); - reject(error); - } - }); - }); - }; - VoiceId.prototype.updateSpeakerIdInVoiceId = function (speakerId) { - var self = this; - self.checkConferenceCall(); - var client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - return new Promise(function (resolve, reject) { - self.getDomainId().then(function (domainId) { - client.call(connect.AgentAppClientMethods.UPDATE_SESSION, { - "SessionNameOrId": contactData.initialContactId || this.contactId, - "SpeakerId": connect.assertNotNull(speakerId, 'speakerId'), - "DomainId": domainId - }, { - success: function success(data) { - connect.getLog().info("updateSpeakerIdInVoiceId succeeded").withObject(data).sendInternalLogToServer(); - self._updateSpeakerIdInLcms(speakerId).then(function () { - resolve(data); - })["catch"](function (err) { - reject(err); - }); - }, - failure: function failure(err) { - var error; - var parsedErr = JSON.parse(err); - switch (parsedErr.status) { - case 400: - case 404: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.SESSION_NOT_EXISTS, "updateSpeakerIdInVoiceId failed, session not exists", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed, session not exists").withObject({ - err: err - }).sendInternalLogToServer(); - break; - default: - error = connect.VoiceIdError(connect.VoiceIdErrorTypes.UPDATE_SPEAKER_ID_FAILED, "updateSpeakerIdInVoiceId failed", err); - connect.getLog().error("updateSpeakerIdInVoiceId failed").withObject({ - err: err - }).sendInternalLogToServer(); - } - reject(error); - } - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.syncSpeakerId = function () { - var self = this; - return new Promise(function (resolve, reject) { - self.getSpeakerId().then(function (data) { - self.updateSpeakerIdInVoiceId(data.speakerId).then(function (data) { - resolve(data); - })["catch"](function (err) { - reject(err); - }); - })["catch"](function (err) { - reject(err); - }); - }); - }; - VoiceId.prototype.getDomainId = function () { - return new Promise(function (resolve, reject) { - var agent = new connect.Agent(); - if (!agent.getPermissions().includes(connect.AgentPermissions.VOICE_ID)) { - reject(new Error("Agent doesn't have the permission for Voice ID")); - } else if (connect.core.voiceIdDomainId) { - resolve(connect.core.voiceIdDomainId); - } else { - var client = connect.core.getClient(); - client.call(connect.AgentAppClientMethods.LIST_INTEGRATION_ASSOCIATIONS, { - "InstanceId": connect.core.getAgentDataProvider().getInstanceId(), - "IntegrationType": "VOICE_ID" - }, { - success: function success(data) { - try { - var domainId; - if (data.IntegrationAssociationSummaryList.length >= 1) { - var integrationArn = data.IntegrationAssociationSummaryList[0].IntegrationArn; - domainId = integrationArn.replace(/^.*domain\//i, ''); - } - if (!domainId) { - connect.getLog().info("getDomainId: no domainId found").sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.NO_DOMAIN_ID_FOUND); - reject(error); - return; - } - connect.getLog().info("getDomainId succeeded").withObject(data).sendInternalLogToServer(); - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.VoiceIdEvents.UPDATE_DOMAIN_ID, - data: { - domainId: domainId - } - }); - resolve(domainId); - } catch (err) { - connect.getLog().error("getDomainId failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); - reject(error); - } - }, - failure: function failure(err) { - connect.getLog().error("getDomainId failed").withObject({ - err: err - }).sendInternalLogToServer(); - var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); - reject(error); - } - }); - } - }); - }; - VoiceId.prototype.checkConferenceCall = function () { - var self = this; - var isConferenceCall = connect.core.getAgentDataProvider().getContactData(self.contactId).connections.filter(function (conn) { - return connect.contains(connect.CONNECTION_ACTIVE_STATES, conn.state.type); - }).length > 2; - if (isConferenceCall) { - throw new connect.NotImplementedError("VoiceId is not supported for conference calls"); - } - }; - VoiceId.prototype.isAuthEnabled = function (authResult) { - return authResult !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED; - }; - VoiceId.prototype.isAuthResultNotEnoughSpeech = function (authResult) { - return authResult === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH; - }; - VoiceId.prototype.isAuthResultInconclusive = function (authResult) { - return authResult === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; - }; - VoiceId.prototype.isFraudEnabled = function (fraudResult) { - return fraudResult !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; - }; - VoiceId.prototype.isFraudResultNotEnoughSpeech = function (fraudResult) { - return fraudResult === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH; - }; - VoiceId.prototype.isFraudResultInconclusive = function (fraudResult) { - return fraudResult === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; - }; - - /** - * @class VoiceConnection - * @param {number} contactId - * @param {number} connectionId - * @description - Provides voice media specific operations - */ - var VoiceConnection = function VoiceConnection(contactId, connectionId) { - this._speakerAuthenticator = new VoiceId(contactId); - Connection.call(this, contactId, connectionId); - }; - VoiceConnection.prototype = Object.create(Connection.prototype); - VoiceConnection.prototype.constructor = VoiceConnection; - - /** - * @deprecated - * Please use getMediaInfo - */ - VoiceConnection.prototype.getSoftphoneMediaInfo = function () { - return this._getData().softphoneMediaInfo; - }; - VoiceConnection.prototype.getMediaInfo = function () { - return this._getData().softphoneMediaInfo; - }; - VoiceConnection.prototype.getMediaType = function () { - return connect.MediaType.SOFTPHONE; - }; - VoiceConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); - }; - VoiceConnection.prototype.getVoiceIdSpeakerId = function () { - return this._speakerAuthenticator.getSpeakerId(); - }; - VoiceConnection.prototype.getVoiceIdSpeakerStatus = function () { - return this._speakerAuthenticator.getSpeakerStatus(); - }; - VoiceConnection.prototype.optOutVoiceIdSpeaker = function () { - return this._speakerAuthenticator.optOutSpeaker(); - }; - VoiceConnection.prototype.deleteVoiceIdSpeaker = function () { - return this._speakerAuthenticator.deleteSpeaker(); - }; - VoiceConnection.prototype.evaluateSpeakerWithVoiceId = function (startNew) { - return this._speakerAuthenticator.evaluateSpeaker(startNew); - }; - VoiceConnection.prototype.enrollSpeakerInVoiceId = function () { - return this._speakerAuthenticator.enrollSpeaker(); - }; - VoiceConnection.prototype.updateVoiceIdSpeakerId = function (speakerId) { - return this._speakerAuthenticator.updateSpeakerIdInVoiceId(speakerId); - }; - VoiceConnection.prototype.getQuickConnectName = function () { - return this._getData().quickConnectName; - }; - VoiceConnection.prototype.isMute = function () { - return this._getData().mute; - }; - VoiceConnection.prototype.muteParticipant = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.MUTE_PARTICIPANT, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); - }; - VoiceConnection.prototype.unmuteParticipant = function (callbacks) { - var client = connect.core.getClient(); - client.call(connect.ClientMethods.UNMUTE_PARTICIPANT, { - contactId: this.getContactId(), - connectionId: this.getConnectionId() - }, callbacks); - }; - - /** - * @class ChatConnection - * @param {*} contactId - * @param {*} connectionId - * @description adds the chat media specific functionality - */ - var ChatConnection = function ChatConnection(contactId, connectionId) { - Connection.call(this, contactId, connectionId); - }; - ChatConnection.prototype = Object.create(Connection.prototype); - ChatConnection.prototype.constructor = ChatConnection; - ChatConnection.prototype.getMediaInfo = function () { - var data = this._getData().chatMediaInfo; - if (!data) { - return null; - } else { - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var mediaObject = { - contactId: this.contactId, - initialContactId: contactData.initialContactId || this.contactId, - participantId: this.connectionId, - getConnectionToken: connect.hitch(this, this.getConnectionToken) - }; - if (data.connectionData) { - try { - mediaObject.participantToken = JSON.parse(data.connectionData).ConnectionAuthenticationToken; - } catch (e) { - connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid").withObject(data).withException(e).sendInternalLogToServer(); - mediaObject.participantToken = null; - } - } - mediaObject.participantToken = mediaObject.participantToken || null; - /** Just to keep the data accessible */ - mediaObject.originalInfo = this._getData().chatMediaInfo; - return mediaObject; - } - }; - - /** - * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. - * @returns a promise which, upon success, returns the response from the createTransport API. - * Usage: - * connection.getConnectionToken() - * .then(response => {}) - * .catch(error => {}) - */ - ChatConnection.prototype.getConnectionToken = function () { - client = connect.core.getClient(); - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var transportDetails = { - transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, - participantId: this.connectionId, - contactId: contactData.initialContactId || this.contactId - }; - return new Promise(function (resolve, reject) { - client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { - success: function success(data) { - connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err, data) { - connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - reject(Error("getConnectionToken failed")); - } - }); - }); - }; - ChatConnection.prototype.getMediaType = function () { - return connect.MediaType.CHAT; - }; - ChatConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); - }; - ChatConnection.prototype._initMediaController = function () { - // Note that a chat media controller only needs to be produced for agent type connections. - if (this._isAgentConnectionType()) { - connect.core.mediaFactory.get(this)["catch"](function () { }); - } - }; - - /** - * @class TaskConnection - * @param {*} contactId - * @param {*} connectionId - * @description adds the task media specific functionality - */ - var TaskConnection = function TaskConnection(contactId, connectionId) { - Connection.call(this, contactId, connectionId); - }; - TaskConnection.prototype = Object.create(Connection.prototype); - TaskConnection.prototype.constructor = TaskConnection; - TaskConnection.prototype.getMediaType = function () { - return connect.MediaType.TASK; - }; - TaskConnection.prototype.getMediaInfo = function () { - var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); - var mediaObject = { - contactId: this.contactId, - initialContactId: contactData.initialContactId || this.contactId - }; - return mediaObject; - }; - TaskConnection.prototype.getMediaController = function () { - return connect.core.mediaFactory.get(this); - }; - - /*---------------------------------------------------------------- - * class ConnectionSnapshot - */ - var ConnectionSnapshot = function ConnectionSnapshot(connectionData) { - connect.Connection.call(this, connectionData.contactId, connectionData.connectionId); - this.connectionData = connectionData; - }; - ConnectionSnapshot.prototype = Object.create(Connection.prototype); - ConnectionSnapshot.prototype.constructor = ConnectionSnapshot; - ConnectionSnapshot.prototype._getData = function () { - return this.connectionData; - }; - ConnectionSnapshot.prototype._initMediaController = function () { }; - var Endpoint = function Endpoint(paramsIn) { - var params = paramsIn || {}; - this.endpointARN = params.endpointId || params.endpointARN || null; - this.endpointId = this.endpointARN; - this.type = params.type || null; - this.name = params.name || null; - this.phoneNumber = params.phoneNumber || null; - this.agentLogin = params.agentLogin || null; - this.queue = params.queue || null; - }; - - /** - * Strip the SIP endpoint components from the phoneNumber field. - */ - Endpoint.prototype.stripPhoneNumber = function () { - return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : ""; - }; - - /** - * Create an Endpoint object from the given phone number and name. - */ - Endpoint.byPhoneNumber = function (number, name) { - return new Endpoint({ - type: connect.EndpointType.PHONE_NUMBER, - phoneNumber: number, - name: name || null - }); - }; - - /*---------------------------------------------------------------- - * class SoftphoneError - */ - var SoftphoneError = function SoftphoneError(errorType, errorMessage, endPointUrl) { - this.errorType = errorType; - this.errorMessage = errorMessage; - this.endPointUrl = endPointUrl; - }; - SoftphoneError.prototype.getErrorType = function () { - return this.errorType; - }; - SoftphoneError.prototype.getErrorMessage = function () { - return this.errorMessage; - }; - SoftphoneError.prototype.getEndPointUrl = function () { - return this.endPointUrl; - }; - - /*---------------------------------------------------------------- - * Root Subscription APIs. - */ - connect.agent = function (f) { - var bus = connect.core.getEventBus(); - var sub = bus.subscribe(connect.AgentEvents.INIT, f); - if (connect.agent.initialized) { - f(new connect.Agent()); - } - return sub; - }; - connect.agent.initialized = false; - connect.contact = function (f) { - var bus = connect.core.getEventBus(); - return bus.subscribe(connect.ContactEvents.INIT, f); - }; - connect.onWebsocketInitFailure = function (f) { - var bus = connect.core.getEventBus(); - var sub = bus.subscribe(connect.WebSocketEvents.INIT_FAILURE, f); - if (connect.webSocketInitFailed) { - f(); - } - return sub; - }; - - /** - * Starts the given function asynchronously only if the shared worker - * says we are the master for the given topic. If there is no master for - * the given topic, we become the master and start the function unless - * shouldNotBecomeMasterIfNone is true. - * - * @param topic The master topic we are concerned about. - * @param f_true The callback to be invoked if we are the master. - * @param f_else [optional] A callback to be invoked if we are not the master. - * @param shouldNotBecomeMasterIfNone [optional] if true, this tab won't become master. - */ - connect.ifMaster = function (topic, f_true, f_else, shouldNotBecomeMasterIfNone) { - connect.assertNotNull(topic, "A topic must be provided."); - connect.assertNotNull(f_true, "A true callback must be provided."); - if (!connect.core.masterClient) { - // We can't be the master because there is no master client! - connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic).sendInternalLogToServer(); - if (f_else) { - f_else(); - } - return; - } - var masterClient = connect.core.getMasterClient(); - masterClient.call(connect.MasterMethods.CHECK_MASTER, { - topic: topic, - shouldNotBecomeMasterIfNone: shouldNotBecomeMasterIfNone - }, { - success: function success(data) { - if (data.isMaster) { - f_true(); - } else if (f_else) { - f_else(); - } - } - }); - }; + }, + failure: function failure(err) { + connect.getLog().error("getDomainId failed").withObject({ + err: err + }).sendInternalLogToServer(); + var error = connect.VoiceIdError(connect.VoiceIdErrorTypes.GET_DOMAIN_ID_FAILED, "getDomainId failed", err); + reject(error); + } + }); + } + }); + }; + VoiceId.prototype.checkConferenceCall = function () { + var self = this; + var isConferenceCall = connect.core.getAgentDataProvider().getContactData(self.contactId).connections.filter(function (conn) { + return connect.contains(connect.CONNECTION_ACTIVE_STATES, conn.state.type); + }).length > 2; + if (isConferenceCall) { + throw new connect.NotImplementedError("VoiceId is not supported for conference calls"); + } + }; + VoiceId.prototype.isAuthEnabled = function (authResult) { + return authResult !== connect.ContactFlowAuthenticationDecision.NOT_ENABLED; + }; + VoiceId.prototype.isAuthResultNotEnoughSpeech = function (authResult) { + return authResult === connect.VoiceIdAuthenticationDecision.NOT_ENOUGH_SPEECH; + }; + VoiceId.prototype.isAuthResultInconclusive = function (authResult) { + return authResult === connect.ContactFlowAuthenticationDecision.INCONCLUSIVE; + }; + VoiceId.prototype.isFraudEnabled = function (fraudResult) { + return fraudResult !== connect.ContactFlowFraudDetectionDecision.NOT_ENABLED; + }; + VoiceId.prototype.isFraudResultNotEnoughSpeech = function (fraudResult) { + return fraudResult === connect.VoiceIdFraudDetectionDecision.NOT_ENOUGH_SPEECH; + }; + VoiceId.prototype.isFraudResultInconclusive = function (fraudResult) { + return fraudResult === connect.ContactFlowFraudDetectionDecision.INCONCLUSIVE; + }; + + /** + * @class VoiceConnection + * @param {number} contactId + * @param {number} connectionId + * @description - Provides voice media specific operations + */ + var VoiceConnection = function VoiceConnection(contactId, connectionId) { + this._speakerAuthenticator = new VoiceId(contactId); + Connection.call(this, contactId, connectionId); + }; + VoiceConnection.prototype = Object.create(Connection.prototype); + VoiceConnection.prototype.constructor = VoiceConnection; + + /** + * @deprecated + * Please use getMediaInfo + */ + VoiceConnection.prototype.getSoftphoneMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; + VoiceConnection.prototype.getMediaInfo = function () { + return this._getData().softphoneMediaInfo; + }; + VoiceConnection.prototype.getMediaType = function () { + return connect.MediaType.SOFTPHONE; + }; + VoiceConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; + VoiceConnection.prototype.getVoiceIdSpeakerId = function () { + return this._speakerAuthenticator.getSpeakerId(); + }; + VoiceConnection.prototype.getVoiceIdSpeakerStatus = function () { + return this._speakerAuthenticator.getSpeakerStatus(); + }; + VoiceConnection.prototype.optOutVoiceIdSpeaker = function () { + return this._speakerAuthenticator.optOutSpeaker(); + }; + VoiceConnection.prototype.deleteVoiceIdSpeaker = function () { + return this._speakerAuthenticator.deleteSpeaker(); + }; + VoiceConnection.prototype.evaluateSpeakerWithVoiceId = function (startNew) { + return this._speakerAuthenticator.evaluateSpeaker(startNew); + }; + VoiceConnection.prototype.enrollSpeakerInVoiceId = function () { + return this._speakerAuthenticator.enrollSpeaker(); + }; + VoiceConnection.prototype.updateVoiceIdSpeakerId = function (speakerId) { + return this._speakerAuthenticator.updateSpeakerIdInVoiceId(speakerId); + }; + VoiceConnection.prototype.getQuickConnectName = function () { + return this._getData().quickConnectName; + }; + VoiceConnection.prototype.isMute = function () { + return this._getData().mute; + }; + VoiceConnection.prototype.muteParticipant = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.MUTE_PARTICIPANT, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + VoiceConnection.prototype.unmuteParticipant = function (callbacks) { + var client = connect.core.getClient(); + client.call(connect.ClientMethods.UNMUTE_PARTICIPANT, { + contactId: this.getContactId(), + connectionId: this.getConnectionId() + }, callbacks); + }; + + /** + * @class ChatConnection + * @param {*} contactId + * @param {*} connectionId + * @description adds the chat media specific functionality + */ + var ChatConnection = function ChatConnection(contactId, connectionId) { + Connection.call(this, contactId, connectionId); + }; + ChatConnection.prototype = Object.create(Connection.prototype); + ChatConnection.prototype.constructor = ChatConnection; + ChatConnection.prototype.getMediaInfo = function () { + var data = this._getData().chatMediaInfo; + if (!data) { + return null; + } else { + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var mediaObject = { + contactId: this.contactId, + initialContactId: contactData.initialContactId || this.contactId, + participantId: this.connectionId, + getConnectionToken: connect.hitch(this, this.getConnectionToken) + }; + if (data.connectionData) { + try { + mediaObject.participantToken = JSON.parse(data.connectionData).ConnectionAuthenticationToken; + } catch (e) { + connect.getLog().error(connect.LogComponent.CHAT, "Connection data is invalid").withObject(data).withException(e).sendInternalLogToServer(); + mediaObject.participantToken = null; + } + } + mediaObject.participantToken = mediaObject.participantToken || null; + /** Just to keep the data accessible */ + mediaObject.originalInfo = this._getData().chatMediaInfo; + return mediaObject; + } + }; + + /** + * Provides the chat connectionToken through the create_transport API for a specific contact and participant Id. + * @returns a promise which, upon success, returns the response from the createTransport API. + * Usage: + * connection.getConnectionToken() + * .then(response => {}) + * .catch(error => {}) + */ + ChatConnection.prototype.getConnectionToken = function () { + client = connect.core.getClient(); + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var transportDetails = { + transportType: connect.TRANSPORT_TYPES.CHAT_TOKEN, + participantId: this.connectionId, + contactId: contactData.initialContactId || this.contactId + }; + return new Promise(function (resolve, reject) { + client.call(connect.ClientMethods.CREATE_TRANSPORT, transportDetails, { + success: function success(data) { + connect.getLog().info("getConnectionToken succeeded").sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err, data) { + connect.getLog().error("getConnectionToken failed").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + reject(Error("getConnectionToken failed")); + } + }); + }); + }; + ChatConnection.prototype.getMediaType = function () { + return connect.MediaType.CHAT; + }; + ChatConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; + ChatConnection.prototype._initMediaController = function () { + // Note that a chat media controller only needs to be produced for agent type connections. + if (this._isAgentConnectionType()) { + connect.core.mediaFactory.get(this)["catch"](function () {}); + } + }; + + /** + * @class TaskConnection + * @param {*} contactId + * @param {*} connectionId + * @description adds the task media specific functionality + */ + var TaskConnection = function TaskConnection(contactId, connectionId) { + Connection.call(this, contactId, connectionId); + }; + TaskConnection.prototype = Object.create(Connection.prototype); + TaskConnection.prototype.constructor = TaskConnection; + TaskConnection.prototype.getMediaType = function () { + return connect.MediaType.TASK; + }; + TaskConnection.prototype.getMediaInfo = function () { + var contactData = connect.core.getAgentDataProvider().getContactData(this.contactId); + var mediaObject = { + contactId: this.contactId, + initialContactId: contactData.initialContactId || this.contactId + }; + return mediaObject; + }; + TaskConnection.prototype.getMediaController = function () { + return connect.core.mediaFactory.get(this); + }; + + /*---------------------------------------------------------------- + * class ConnectionSnapshot + */ + var ConnectionSnapshot = function ConnectionSnapshot(connectionData) { + connect.Connection.call(this, connectionData.contactId, connectionData.connectionId); + this.connectionData = connectionData; + }; + ConnectionSnapshot.prototype = Object.create(Connection.prototype); + ConnectionSnapshot.prototype.constructor = ConnectionSnapshot; + ConnectionSnapshot.prototype._getData = function () { + return this.connectionData; + }; + ConnectionSnapshot.prototype._initMediaController = function () {}; + var Endpoint = function Endpoint(paramsIn) { + var params = paramsIn || {}; + this.endpointARN = params.endpointId || params.endpointARN || null; + this.endpointId = this.endpointARN; + this.type = params.type || null; + this.name = params.name || null; + this.phoneNumber = params.phoneNumber || null; + this.agentLogin = params.agentLogin || null; + this.queue = params.queue || null; + }; + + /** + * Strip the SIP endpoint components from the phoneNumber field. + */ + Endpoint.prototype.stripPhoneNumber = function () { + return this.phoneNumber ? this.phoneNumber.replace(/sip:([^@]*)@.*/, "$1") : ""; + }; + + /** + * Create an Endpoint object from the given phone number and name. + */ + Endpoint.byPhoneNumber = function (number, name) { + return new Endpoint({ + type: connect.EndpointType.PHONE_NUMBER, + phoneNumber: number, + name: name || null + }); + }; + + /*---------------------------------------------------------------- + * class SoftphoneError + */ + var SoftphoneError = function SoftphoneError(errorType, errorMessage, endPointUrl) { + this.errorType = errorType; + this.errorMessage = errorMessage; + this.endPointUrl = endPointUrl; + }; + SoftphoneError.prototype.getErrorType = function () { + return this.errorType; + }; + SoftphoneError.prototype.getErrorMessage = function () { + return this.errorMessage; + }; + SoftphoneError.prototype.getEndPointUrl = function () { + return this.endPointUrl; + }; + + /*---------------------------------------------------------------- + * Root Subscription APIs. + */ + connect.agent = function (f) { + var bus = connect.core.getEventBus(); + var sub = bus.subscribe(connect.AgentEvents.INIT, f); + if (connect.agent.initialized) { + f(new connect.Agent()); + } + return sub; + }; + connect.agent.initialized = false; + connect.contact = function (f) { + var bus = connect.core.getEventBus(); + return bus.subscribe(connect.ContactEvents.INIT, f); + }; + connect.onWebsocketInitFailure = function (f) { + var bus = connect.core.getEventBus(); + var sub = bus.subscribe(connect.WebSocketEvents.INIT_FAILURE, f); + if (connect.webSocketInitFailed) { + f(); + } + return sub; + }; + + /** + * Starts the given function asynchronously only if the shared worker + * says we are the master for the given topic. If there is no master for + * the given topic, we become the master and start the function unless + * shouldNotBecomeMasterIfNone is true. + * + * @param topic The master topic we are concerned about. + * @param f_true The callback to be invoked if we are the master. + * @param f_else [optional] A callback to be invoked if we are not the master. + * @param shouldNotBecomeMasterIfNone [optional] if true, this tab won't become master. + */ + connect.ifMaster = function (topic, f_true, f_else, shouldNotBecomeMasterIfNone) { + connect.assertNotNull(topic, "A topic must be provided."); + connect.assertNotNull(f_true, "A true callback must be provided."); + if (!connect.core.masterClient) { + // We can't be the master because there is no master client! + connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic).sendInternalLogToServer(); + if (f_else) { + f_else(); + } + return; + } + var masterClient = connect.core.getMasterClient(); + masterClient.call(connect.MasterMethods.CHECK_MASTER, { + topic: topic, + shouldNotBecomeMasterIfNone: shouldNotBecomeMasterIfNone + }, { + success: function success(data) { + if (data.isMaster) { + f_true(); + } else if (f_else) { + f_else(); + } + } + }); + }; + + /** + * Notify the shared worker and other CCP tabs that we are now the master for the given topic. + */ + connect.becomeMaster = function (topic, successCallback, failureCallback) { + connect.assertNotNull(topic, "A topic must be provided."); + if (!connect.core.masterClient) { + // We can't be the master because there is no master client! + connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic); + if (failureCallback) { + failureCallback(); + } + } else { + var masterClient = connect.core.getMasterClient(); + masterClient.call(connect.MasterMethods.BECOME_MASTER, { + topic: topic + }, { + success: function success() { + if (successCallback) { + successCallback(); + } + } + }); + } + }; + connect.Agent = Agent; + connect.AgentSnapshot = AgentSnapshot; + connect.Contact = Contact; + connect.ContactSnapshot = ContactSnapshot; + /** Default will get the Voice connection */ + connect.Connection = VoiceConnection; + connect.BaseConnection = Connection; + connect.VoiceConnection = VoiceConnection; + connect.ChatConnection = ChatConnection; + connect.TaskConnection = TaskConnection; + connect.ConnectionSnapshot = ConnectionSnapshot; + connect.Endpoint = Endpoint; + connect.Address = Endpoint; + connect.SoftphoneError = SoftphoneError; + connect.VoiceId = VoiceId; +})(); - /** - * Notify the shared worker and other CCP tabs that we are now the master for the given topic. - */ - connect.becomeMaster = function (topic, successCallback, failureCallback) { - connect.assertNotNull(topic, "A topic must be provided."); - if (!connect.core.masterClient) { - // We can't be the master because there is no master client! - connect.getLog().warn("We can't be the master for topic '%s' because there is no master client!", topic); - if (failureCallback) { - failureCallback(); - } - } else { - var masterClient = connect.core.getMasterClient(); - masterClient.call(connect.MasterMethods.BECOME_MASTER, { - topic: topic - }, { - success: function success() { - if (successCallback) { - successCallback(); - } - } - }); - } - }; - connect.Agent = Agent; - connect.AgentSnapshot = AgentSnapshot; - connect.Contact = Contact; - connect.ContactSnapshot = ContactSnapshot; - /** Default will get the Voice connection */ - connect.Connection = VoiceConnection; - connect.BaseConnection = Connection; - connect.VoiceConnection = VoiceConnection; - connect.ChatConnection = ChatConnection; - connect.TaskConnection = TaskConnection; - connect.ConnectionSnapshot = ConnectionSnapshot; - connect.Endpoint = Endpoint; - connect.Address = Endpoint; - connect.SoftphoneError = SoftphoneError; - connect.VoiceId = VoiceId; - })(); - - /***/ -}), +/***/ }), /***/ 538: /***/ ((module, exports, __webpack_require__) => { - var __WEBPACK_AMD_DEFINE_RESULT__; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }// AWS SDK for JavaScript v2.553.0 - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt - (function () { function r(e, n, t) { function o(i, f) { if (!n[i]) { if (!e[i]) { var c = undefined; if (!f && c) return require(i, !0); if (u) return u(i, !0); var a = new Error("Cannot find module '" + i + "'"); throw a.code = "MODULE_NOT_FOUND", a; } var p = n[i] = { exports: {} }; e[i][0].call(p.exports, function (r) { var n = e[i][1][r]; return o(n || r); }, p, p.exports, r, e, n, t); } return n[i].exports; } for (var u = undefined, i = 0; i < t.length; i++)o(t[i]); return o; } return r; })()({ - 1: [function (require, module, exports) { module.exports = { "version": "2.0", "metadata": { "apiVersion": "2014-06-30", "endpointPrefix": "cognito-identity", "jsonVersion": "1.1", "protocol": "json", "serviceFullName": "Amazon Cognito Identity", "serviceId": "Cognito Identity", "signatureVersion": "v4", "targetPrefix": "AWSCognitoIdentityService", "uid": "cognito-identity-2014-06-30" }, "operations": { "CreateIdentityPool": { "input": { "type": "structure", "required": ["IdentityPoolName", "AllowUnauthenticatedIdentities"], "members": { "IdentityPoolName": {}, "AllowUnauthenticatedIdentities": { "type": "boolean" }, "SupportedLoginProviders": { "shape": "S4" }, "DeveloperProviderName": {}, "OpenIdConnectProviderARNs": { "shape": "S8" }, "CognitoIdentityProviders": { "shape": "Sa" }, "SamlProviderARNs": { "shape": "Sf" }, "IdentityPoolTags": { "shape": "Sg" } } }, "output": { "shape": "Sj" } }, "DeleteIdentities": { "input": { "type": "structure", "required": ["IdentityIdsToDelete"], "members": { "IdentityIdsToDelete": { "type": "list", "member": {} } } }, "output": { "type": "structure", "members": { "UnprocessedIdentityIds": { "type": "list", "member": { "type": "structure", "members": { "IdentityId": {}, "ErrorCode": {} } } } } } }, "DeleteIdentityPool": { "input": { "type": "structure", "required": ["IdentityPoolId"], "members": { "IdentityPoolId": {} } } }, "DescribeIdentity": { "input": { "type": "structure", "required": ["IdentityId"], "members": { "IdentityId": {} } }, "output": { "shape": "Su" } }, "DescribeIdentityPool": { "input": { "type": "structure", "required": ["IdentityPoolId"], "members": { "IdentityPoolId": {} } }, "output": { "shape": "Sj" } }, "GetCredentialsForIdentity": { "input": { "type": "structure", "required": ["IdentityId"], "members": { "IdentityId": {}, "Logins": { "shape": "Sz" }, "CustomRoleArn": {} } }, "output": { "type": "structure", "members": { "IdentityId": {}, "Credentials": { "type": "structure", "members": { "AccessKeyId": {}, "SecretKey": {}, "SessionToken": {}, "Expiration": { "type": "timestamp" } } } } } }, "GetId": { "input": { "type": "structure", "required": ["IdentityPoolId"], "members": { "AccountId": {}, "IdentityPoolId": {}, "Logins": { "shape": "Sz" } } }, "output": { "type": "structure", "members": { "IdentityId": {} } } }, "GetIdentityPoolRoles": { "input": { "type": "structure", "required": ["IdentityPoolId"], "members": { "IdentityPoolId": {} } }, "output": { "type": "structure", "members": { "IdentityPoolId": {}, "Roles": { "shape": "S1b" }, "RoleMappings": { "shape": "S1d" } } } }, "GetOpenIdToken": { "input": { "type": "structure", "required": ["IdentityId"], "members": { "IdentityId": {}, "Logins": { "shape": "Sz" } } }, "output": { "type": "structure", "members": { "IdentityId": {}, "Token": {} } } }, "GetOpenIdTokenForDeveloperIdentity": { "input": { "type": "structure", "required": ["IdentityPoolId", "Logins"], "members": { "IdentityPoolId": {}, "IdentityId": {}, "Logins": { "shape": "Sz" }, "TokenDuration": { "type": "long" } } }, "output": { "type": "structure", "members": { "IdentityId": {}, "Token": {} } } }, "ListIdentities": { "input": { "type": "structure", "required": ["IdentityPoolId", "MaxResults"], "members": { "IdentityPoolId": {}, "MaxResults": { "type": "integer" }, "NextToken": {}, "HideDisabled": { "type": "boolean" } } }, "output": { "type": "structure", "members": { "IdentityPoolId": {}, "Identities": { "type": "list", "member": { "shape": "Su" } }, "NextToken": {} } } }, "ListIdentityPools": { "input": { "type": "structure", "required": ["MaxResults"], "members": { "MaxResults": { "type": "integer" }, "NextToken": {} } }, "output": { "type": "structure", "members": { "IdentityPools": { "type": "list", "member": { "type": "structure", "members": { "IdentityPoolId": {}, "IdentityPoolName": {} } } }, "NextToken": {} } } }, "ListTagsForResource": { "input": { "type": "structure", "required": ["ResourceArn"], "members": { "ResourceArn": {} } }, "output": { "type": "structure", "members": { "Tags": { "shape": "Sg" } } } }, "LookupDeveloperIdentity": { "input": { "type": "structure", "required": ["IdentityPoolId"], "members": { "IdentityPoolId": {}, "IdentityId": {}, "DeveloperUserIdentifier": {}, "MaxResults": { "type": "integer" }, "NextToken": {} } }, "output": { "type": "structure", "members": { "IdentityId": {}, "DeveloperUserIdentifierList": { "type": "list", "member": {} }, "NextToken": {} } } }, "MergeDeveloperIdentities": { "input": { "type": "structure", "required": ["SourceUserIdentifier", "DestinationUserIdentifier", "DeveloperProviderName", "IdentityPoolId"], "members": { "SourceUserIdentifier": {}, "DestinationUserIdentifier": {}, "DeveloperProviderName": {}, "IdentityPoolId": {} } }, "output": { "type": "structure", "members": { "IdentityId": {} } } }, "SetIdentityPoolRoles": { "input": { "type": "structure", "required": ["IdentityPoolId", "Roles"], "members": { "IdentityPoolId": {}, "Roles": { "shape": "S1b" }, "RoleMappings": { "shape": "S1d" } } } }, "TagResource": { "input": { "type": "structure", "required": ["ResourceArn"], "members": { "ResourceArn": {}, "Tags": { "shape": "Sg" } } }, "output": { "type": "structure", "members": {} } }, "UnlinkDeveloperIdentity": { "input": { "type": "structure", "required": ["IdentityId", "IdentityPoolId", "DeveloperProviderName", "DeveloperUserIdentifier"], "members": { "IdentityId": {}, "IdentityPoolId": {}, "DeveloperProviderName": {}, "DeveloperUserIdentifier": {} } } }, "UnlinkIdentity": { "input": { "type": "structure", "required": ["IdentityId", "Logins", "LoginsToRemove"], "members": { "IdentityId": {}, "Logins": { "shape": "Sz" }, "LoginsToRemove": { "shape": "Sv" } } } }, "UntagResource": { "input": { "type": "structure", "required": ["ResourceArn"], "members": { "ResourceArn": {}, "TagKeys": { "type": "list", "member": {} } } }, "output": { "type": "structure", "members": {} } }, "UpdateIdentityPool": { "input": { "shape": "Sj" }, "output": { "shape": "Sj" } } }, "shapes": { "S4": { "type": "map", "key": {}, "value": {} }, "S8": { "type": "list", "member": {} }, "Sa": { "type": "list", "member": { "type": "structure", "members": { "ProviderName": {}, "ClientId": {}, "ServerSideTokenCheck": { "type": "boolean" } } } }, "Sf": { "type": "list", "member": {} }, "Sg": { "type": "map", "key": {}, "value": {} }, "Sj": { "type": "structure", "required": ["IdentityPoolId", "IdentityPoolName", "AllowUnauthenticatedIdentities"], "members": { "IdentityPoolId": {}, "IdentityPoolName": {}, "AllowUnauthenticatedIdentities": { "type": "boolean" }, "SupportedLoginProviders": { "shape": "S4" }, "DeveloperProviderName": {}, "OpenIdConnectProviderARNs": { "shape": "S8" }, "CognitoIdentityProviders": { "shape": "Sa" }, "SamlProviderARNs": { "shape": "Sf" }, "IdentityPoolTags": { "shape": "Sg" } } }, "Su": { "type": "structure", "members": { "IdentityId": {}, "Logins": { "shape": "Sv" }, "CreationDate": { "type": "timestamp" }, "LastModifiedDate": { "type": "timestamp" } } }, "Sv": { "type": "list", "member": {} }, "Sz": { "type": "map", "key": {}, "value": {} }, "S1b": { "type": "map", "key": {}, "value": {} }, "S1d": { "type": "map", "key": {}, "value": { "type": "structure", "required": ["Type"], "members": { "Type": {}, "AmbiguousRoleResolution": {}, "RulesConfiguration": { "type": "structure", "required": ["Rules"], "members": { "Rules": { "type": "list", "member": { "type": "structure", "required": ["Claim", "MatchType", "Value", "RoleARN"], "members": { "Claim": {}, "MatchType": {}, "Value": {}, "RoleARN": {} } } } } } } } } } }; }, {}], 2: [function (require, module, exports) { module.exports = { "pagination": {} }; }, {}], 3: [function (require, module, exports) { module.exports = { "version": "2.0", "metadata": { "apiVersion": "2017-02-15", "endpointPrefix": "connect", "jsonVersion": "1.0", "protocol": "json", "serviceAbbreviation": "Connect", "serviceFullName": "AmazonConnectCTIService", "signatureVersion": "", "targetPrefix": "AmazonConnectCTIService", "uid": "connect-2017-02-15" }, "operations": { "AcceptContact": { "input": { "type": "structure", "required": ["authentication", "contactId"], "members": { "authentication": { "shape": "S2" }, "contactId": {} } }, "output": { "type": "structure", "members": {} } }, "ClearContact": { "input": { "type": "structure", "required": ["contactId"], "members": { "contactId": {} } }, "output": { "type": "structure", "members": {} } }, "CompleteContact": { "input": { "type": "structure", "required": ["contactId"], "members": { "contactId": {} } }, "output": { "type": "structure", "members": {} } }, "ConferenceConnections": { "input": { "type": "structure", "required": ["authentication", "contactId"], "members": { "authentication": { "shape": "S2" }, "contactId": {} } }, "output": { "type": "structure", "members": {} } }, "CreateAdditionalConnection": { "input": { "type": "structure", "required": ["authentication", "contactId", "endpoint"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "endpoint": { "shape": "Se" } } }, "output": { "type": "structure", "members": {} } }, "CreateOutboundContact": { "input": { "type": "structure", "required": ["authentication", "endpoint"], "members": { "authentication": { "shape": "S2" }, "endpoint": { "shape": "Se" }, "queueARN": {} } }, "output": { "type": "structure", "members": {} } }, "CreateTaskContact": { "input": { "type": "structure", "required": ["endpoint", "name"], "members": { "endpoint": { "shape": "Se" }, "previousContactId": {}, "name": {}, "description": {}, "references": { "shape": "Sr" }, "idempotencyToken": {}, "scheduledTime": { "type": "long" } } }, "output": { "type": "structure", "members": { "contactId": {} } } }, "CreateTransport": { "input": { "type": "structure", "required": ["transportType", "authentication"], "members": { "transportType": {}, "participantId": {}, "contactId": {}, "softphoneClientId": {}, "authentication": { "shape": "S2" } } }, "output": { "type": "structure", "members": { "webSocketTransport": { "type": "structure", "required": ["url", "transportLifeTimeInSeconds"], "members": { "url": {}, "transportLifeTimeInSeconds": { "type": "long" }, "expiry": {} } }, "chatTokenTransport": { "type": "structure", "required": ["participantToken", "expiry"], "members": { "participantToken": {}, "expiry": {} } }, "softphoneTransport": { "type": "structure", "required": ["softphoneMediaConnections"], "members": { "softphoneMediaConnections": { "type": "list", "member": { "type": "structure", "required": ["username", "credential", "urls"], "members": { "username": {}, "credential": {}, "urls": { "type": "list", "member": {} } } } } } } } } }, "DestroyConnection": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "GetAgentConfiguration": { "input": { "type": "structure", "required": ["authentication"], "members": { "authentication": { "shape": "S2" } } }, "output": { "type": "structure", "required": ["configuration"], "members": { "configuration": { "shape": "S1h" } } } }, "GetAgentPermissions": { "input": { "type": "structure", "required": ["authentication"], "members": { "authentication": { "shape": "S2" }, "nextToken": {}, "maxResults": { "type": "integer" } } }, "output": { "type": "structure", "required": ["permissions"], "members": { "permissions": { "type": "list", "member": {} }, "nextToken": {} } } }, "GetAgentSnapshot": { "input": { "type": "structure", "required": ["authentication"], "members": { "authentication": { "shape": "S2" }, "nextToken": {}, "timeout": { "type": "long" } } }, "output": { "type": "structure", "required": ["snapshot", "nextToken"], "members": { "snapshot": { "type": "structure", "required": ["state", "contacts", "snapshotTimestamp"], "members": { "state": { "shape": "S20" }, "nextState": { "shape": "S20" }, "agentAvailabilityState": { "type": "structure", "members": { "state": {}, "timeStamp": { "type": "timestamp" } } }, "contacts": { "type": "list", "member": { "type": "structure", "required": ["contactId", "type", "state", "connections", "attributes"], "members": { "contactId": {}, "initialContactId": {}, "type": {}, "state": { "type": "structure", "required": ["type", "timestamp"], "members": { "type": {}, "timestamp": { "type": "timestamp" } } }, "queue": { "shape": "Sk" }, "queueTimestamp": { "type": "timestamp" }, "connections": { "type": "list", "member": { "type": "structure", "required": ["connectionId", "state", "type", "initial"], "members": { "connectionId": {}, "endpoint": { "shape": "Se" }, "state": { "type": "structure", "required": ["type", "timestamp"], "members": { "type": {}, "timestamp": { "type": "timestamp" } } }, "type": {}, "initial": { "type": "boolean" }, "softphoneMediaInfo": { "type": "structure", "members": { "callType": {}, "autoAccept": { "type": "boolean" }, "mediaLegContextToken": {}, "callContextToken": {}, "callConfigJson": {} } }, "chatMediaInfo": { "type": "structure", "members": { "chatAutoAccept": { "type": "boolean" }, "connectionData": {}, "customerName": {} } }, "monitoringInfo": { "type": "structure", "members": { "agent": { "type": "structure", "members": { "agentName": {} } }, "joinTimeStamp": { "type": "timestamp" } } }, "mute": { "type": "boolean" }, "quickConnectName": {} } } }, "attributes": { "type": "map", "key": {}, "value": { "type": "structure", "required": ["name"], "members": { "name": {}, "value": {} } } }, "contactDuration": {}, "name": {}, "description": {}, "references": { "shape": "Sr" }, "initiationMethod": {}, "contactFeatures": { "type": "structure", "members": { "attachmentsEnabled": { "type": "boolean" } } } } } }, "snapshotTimestamp": { "type": "timestamp" } } }, "nextToken": {} } } }, "GetAgentStates": { "input": { "type": "structure", "required": ["authentication"], "members": { "authentication": { "shape": "S2" }, "nextToken": {}, "maxResults": { "type": "integer" } } }, "output": { "type": "structure", "required": ["states"], "members": { "states": { "type": "list", "member": { "shape": "S20" } }, "nextToken": {} } } }, "GetDialableCountryCodes": { "input": { "type": "structure", "required": ["authentication"], "members": { "authentication": { "shape": "S2" }, "nextToken": {}, "maxResults": { "type": "integer" } } }, "output": { "type": "structure", "required": ["countryCodes"], "members": { "countryCodes": { "type": "list", "member": {} }, "nextToken": {} } } }, "GetEndpoints": { "input": { "type": "structure", "required": ["authentication", "queueARNs"], "members": { "authentication": { "shape": "S2" }, "queueARNs": { "type": "list", "member": {} }, "nextToken": {}, "maxResults": { "type": "integer" } } }, "output": { "type": "structure", "members": { "endpoints": { "type": "list", "member": { "shape": "Se" } }, "nextToken": {} } } }, "GetNewAuthToken": { "input": { "type": "structure", "required": ["authentication", "refreshToken"], "members": { "authentication": { "shape": "S2" }, "refreshToken": {} } }, "output": { "type": "structure", "members": { "newAuthToken": {}, "expirationDateTime": { "type": "timestamp" } } } }, "GetRoutingProfileQueues": { "input": { "type": "structure", "required": ["authentication", "routingProfileARN"], "members": { "authentication": { "shape": "S2" }, "routingProfileARN": {}, "nextToken": {}, "maxResults": { "type": "integer" } } }, "output": { "type": "structure", "required": ["queues"], "members": { "queues": { "type": "list", "member": { "shape": "Sk" } }, "nextToken": {} } } }, "HoldConnection": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "MuteParticipant": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "NotifyContactIssue": { "input": { "type": "structure", "required": ["authentication", "contactId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "issueCode": {}, "description": {}, "clientLogs": {} } }, "output": { "type": "structure", "members": {} } }, "PutAgentState": { "input": { "type": "structure", "required": ["authentication", "state"], "members": { "authentication": { "shape": "S2" }, "state": { "shape": "S20" }, "enqueueNextState": { "type": "boolean" } } }, "output": { "type": "structure", "members": {} } }, "RejectContact": { "input": { "type": "structure", "required": ["contactId"], "members": { "contactId": {} } }, "output": { "type": "structure", "members": {} } }, "ResumeConnection": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "SendClientLogs": { "input": { "type": "structure", "required": ["authentication", "logEvents"], "members": { "authentication": { "shape": "S2" }, "logEvents": { "type": "list", "member": { "type": "structure", "members": { "timestamp": { "type": "timestamp" }, "component": {}, "message": {} } } } } }, "output": { "type": "structure", "members": {} } }, "SendDigits": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId", "digits"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {}, "digits": {} } }, "output": { "type": "structure", "members": {} } }, "SendSoftphoneCallMetrics": { "input": { "type": "structure", "required": ["authentication", "contactId", "softphoneStreamStatistics"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "ccpVersion": {}, "softphoneStreamStatistics": { "shape": "S3r" } } }, "output": { "type": "structure", "members": {} } }, "SendSoftphoneCallReport": { "input": { "type": "structure", "required": ["authentication", "contactId", "report"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "ccpVersion": {}, "report": { "type": "structure", "members": { "callStartTime": { "type": "timestamp" }, "callEndTime": { "type": "timestamp" }, "softphoneStreamStatistics": { "shape": "S3r" }, "gumTimeMillis": { "type": "long" }, "initializationTimeMillis": { "type": "long" }, "iceCollectionTimeMillis": { "type": "long" }, "signallingConnectTimeMillis": { "type": "long" }, "handshakeTimeMillis": { "type": "long" }, "preTalkTimeMillis": { "type": "long" }, "talkTimeMillis": { "type": "long" }, "cleanupTimeMillis": { "type": "long" }, "iceCollectionFailure": { "type": "boolean" }, "signallingConnectionFailure": { "type": "boolean" }, "handshakeFailure": { "type": "boolean" }, "gumOtherFailure": { "type": "boolean" }, "gumTimeoutFailure": { "type": "boolean" }, "createOfferFailure": { "type": "boolean" }, "setLocalDescriptionFailure": { "type": "boolean" }, "userBusyFailure": { "type": "boolean" }, "invalidRemoteSDPFailure": { "type": "boolean" }, "noRemoteIceCandidateFailure": { "type": "boolean" }, "setRemoteDescriptionFailure": { "type": "boolean" } } } } }, "output": { "type": "structure", "members": {} } }, "ToggleActiveConnections": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "UnmuteParticipant": { "input": { "type": "structure", "required": ["authentication", "contactId", "connectionId"], "members": { "authentication": { "shape": "S2" }, "contactId": {}, "connectionId": {} } }, "output": { "type": "structure", "members": {} } }, "UpdateAgentConfiguration": { "input": { "type": "structure", "required": ["authentication", "configuration"], "members": { "authentication": { "shape": "S2" }, "configuration": { "shape": "S1h" } } }, "output": { "type": "structure", "members": {} } } }, "shapes": { "S2": { "type": "structure", "members": { "agentARN": {}, "authToken": {} } }, "Se": { "type": "structure", "required": ["type"], "members": { "endpointARN": {}, "type": {}, "name": {}, "phoneNumber": {}, "agentLogin": {}, "queue": { "shape": "Sk" } } }, "Sk": { "type": "structure", "members": { "queueARN": {}, "name": {} } }, "Sr": { "type": "map", "key": {}, "value": { "type": "structure", "required": ["value", "type"], "members": { "value": {}, "type": {} } } }, "S1h": { "type": "structure", "required": ["name", "softphoneEnabled", "softphoneAutoAccept", "extension", "routingProfile"], "members": { "name": {}, "username": {}, "softphoneEnabled": { "type": "boolean" }, "softphoneAutoAccept": { "type": "boolean" }, "extension": {}, "routingProfile": { "type": "structure", "members": { "name": {}, "routingProfileARN": {}, "defaultOutboundQueue": { "shape": "Sk" }, "channelConcurrencyMap": { "type": "map", "key": {}, "value": { "type": "long" } } } }, "agentPreferences": { "type": "map", "key": {}, "value": {} } } }, "S20": { "type": "structure", "required": ["type", "name"], "members": { "agentStateARN": {}, "type": {}, "name": {}, "startTimestamp": { "type": "timestamp" } } }, "S3r": { "type": "list", "member": { "type": "structure", "members": { "timestamp": { "type": "timestamp" }, "softphoneStreamType": {}, "packetCount": { "type": "long" }, "packetsLost": { "type": "long" }, "audioLevel": { "type": "double" }, "jitterBufferMillis": { "type": "long" }, "roundTripTimeMillis": { "type": "long" } } } } } }; }, {}], 4: [function (require, module, exports) { module.exports = { "acm": { "name": "ACM", "cors": true }, "apigateway": { "name": "APIGateway", "cors": true }, "applicationautoscaling": { "prefix": "application-autoscaling", "name": "ApplicationAutoScaling", "cors": true }, "appstream": { "name": "AppStream" }, "autoscaling": { "name": "AutoScaling", "cors": true }, "batch": { "name": "Batch" }, "budgets": { "name": "Budgets" }, "clouddirectory": { "name": "CloudDirectory", "versions": ["2016-05-10*"] }, "cloudformation": { "name": "CloudFormation", "cors": true }, "cloudfront": { "name": "CloudFront", "versions": ["2013-05-12*", "2013-11-11*", "2014-05-31*", "2014-10-21*", "2014-11-06*", "2015-04-17*", "2015-07-27*", "2015-09-17*", "2016-01-13*", "2016-01-28*", "2016-08-01*", "2016-08-20*", "2016-09-07*", "2016-09-29*", "2016-11-25*", "2017-03-25*", "2017-10-30*", "2018-06-18*", "2018-11-05*"], "cors": true }, "cloudhsm": { "name": "CloudHSM", "cors": true }, "cloudsearch": { "name": "CloudSearch" }, "cloudsearchdomain": { "name": "CloudSearchDomain" }, "cloudtrail": { "name": "CloudTrail", "cors": true }, "cloudwatch": { "prefix": "monitoring", "name": "CloudWatch", "cors": true }, "cloudwatchevents": { "prefix": "events", "name": "CloudWatchEvents", "versions": ["2014-02-03*"], "cors": true }, "cloudwatchlogs": { "prefix": "logs", "name": "CloudWatchLogs", "cors": true }, "codebuild": { "name": "CodeBuild", "cors": true }, "codecommit": { "name": "CodeCommit", "cors": true }, "codedeploy": { "name": "CodeDeploy", "cors": true }, "codepipeline": { "name": "CodePipeline", "cors": true }, "cognitoidentity": { "prefix": "cognito-identity", "name": "CognitoIdentity", "cors": true }, "cognitoidentityserviceprovider": { "prefix": "cognito-idp", "name": "CognitoIdentityServiceProvider", "cors": true }, "cognitosync": { "prefix": "cognito-sync", "name": "CognitoSync", "cors": true }, "configservice": { "prefix": "config", "name": "ConfigService", "cors": true }, "connect": { "name": "Connect", "cors": true }, "cur": { "name": "CUR", "cors": true }, "datapipeline": { "name": "DataPipeline" }, "devicefarm": { "name": "DeviceFarm", "cors": true }, "directconnect": { "name": "DirectConnect", "cors": true }, "directoryservice": { "prefix": "ds", "name": "DirectoryService" }, "discovery": { "name": "Discovery" }, "dms": { "name": "DMS" }, "dynamodb": { "name": "DynamoDB", "cors": true }, "dynamodbstreams": { "prefix": "streams.dynamodb", "name": "DynamoDBStreams", "cors": true }, "ec2": { "name": "EC2", "versions": ["2013-06-15*", "2013-10-15*", "2014-02-01*", "2014-05-01*", "2014-06-15*", "2014-09-01*", "2014-10-01*", "2015-03-01*", "2015-04-15*", "2015-10-01*", "2016-04-01*", "2016-09-15*"], "cors": true }, "ecr": { "name": "ECR", "cors": true }, "ecs": { "name": "ECS", "cors": true }, "efs": { "prefix": "elasticfilesystem", "name": "EFS", "cors": true }, "elasticache": { "name": "ElastiCache", "versions": ["2012-11-15*", "2014-03-24*", "2014-07-15*", "2014-09-30*"], "cors": true }, "elasticbeanstalk": { "name": "ElasticBeanstalk", "cors": true }, "elb": { "prefix": "elasticloadbalancing", "name": "ELB", "cors": true }, "elbv2": { "prefix": "elasticloadbalancingv2", "name": "ELBv2", "cors": true }, "emr": { "prefix": "elasticmapreduce", "name": "EMR", "cors": true }, "es": { "name": "ES" }, "elastictranscoder": { "name": "ElasticTranscoder", "cors": true }, "firehose": { "name": "Firehose", "cors": true }, "gamelift": { "name": "GameLift", "cors": true }, "glacier": { "name": "Glacier" }, "health": { "name": "Health" }, "iam": { "name": "IAM", "cors": true }, "importexport": { "name": "ImportExport" }, "inspector": { "name": "Inspector", "versions": ["2015-08-18*"], "cors": true }, "iot": { "name": "Iot", "cors": true }, "iotdata": { "prefix": "iot-data", "name": "IotData", "cors": true }, "kinesis": { "name": "Kinesis", "cors": true }, "kinesisanalytics": { "name": "KinesisAnalytics" }, "kms": { "name": "KMS", "cors": true }, "lambda": { "name": "Lambda", "cors": true }, "lexruntime": { "prefix": "runtime.lex", "name": "LexRuntime", "cors": true }, "lightsail": { "name": "Lightsail" }, "machinelearning": { "name": "MachineLearning", "cors": true }, "marketplacecommerceanalytics": { "name": "MarketplaceCommerceAnalytics", "cors": true }, "marketplacemetering": { "prefix": "meteringmarketplace", "name": "MarketplaceMetering" }, "mturk": { "prefix": "mturk-requester", "name": "MTurk", "cors": true }, "mobileanalytics": { "name": "MobileAnalytics", "cors": true }, "opsworks": { "name": "OpsWorks", "cors": true }, "opsworkscm": { "name": "OpsWorksCM" }, "organizations": { "name": "Organizations" }, "pinpoint": { "name": "Pinpoint" }, "polly": { "name": "Polly", "cors": true }, "rds": { "name": "RDS", "versions": ["2014-09-01*"], "cors": true }, "redshift": { "name": "Redshift", "cors": true }, "rekognition": { "name": "Rekognition", "cors": true }, "resourcegroupstaggingapi": { "name": "ResourceGroupsTaggingAPI" }, "route53": { "name": "Route53", "cors": true }, "route53domains": { "name": "Route53Domains", "cors": true }, "s3": { "name": "S3", "dualstackAvailable": true, "cors": true }, "s3control": { "name": "S3Control", "dualstackAvailable": true }, "servicecatalog": { "name": "ServiceCatalog", "cors": true }, "ses": { "prefix": "email", "name": "SES", "cors": true }, "shield": { "name": "Shield" }, "simpledb": { "prefix": "sdb", "name": "SimpleDB" }, "sms": { "name": "SMS" }, "snowball": { "name": "Snowball" }, "sns": { "name": "SNS", "cors": true }, "sqs": { "name": "SQS", "cors": true }, "ssm": { "name": "SSM", "cors": true }, "storagegateway": { "name": "StorageGateway", "cors": true }, "stepfunctions": { "prefix": "states", "name": "StepFunctions" }, "sts": { "name": "STS", "cors": true }, "support": { "name": "Support" }, "swf": { "name": "SWF" }, "xray": { "name": "XRay", "cors": true }, "waf": { "name": "WAF", "cors": true }, "wafregional": { "prefix": "waf-regional", "name": "WAFRegional" }, "workdocs": { "name": "WorkDocs", "cors": true }, "workspaces": { "name": "WorkSpaces" }, "codestar": { "name": "CodeStar" }, "lexmodelbuildingservice": { "prefix": "lex-models", "name": "LexModelBuildingService", "cors": true }, "marketplaceentitlementservice": { "prefix": "entitlement.marketplace", "name": "MarketplaceEntitlementService" }, "athena": { "name": "Athena" }, "greengrass": { "name": "Greengrass" }, "dax": { "name": "DAX" }, "migrationhub": { "prefix": "AWSMigrationHub", "name": "MigrationHub" }, "cloudhsmv2": { "name": "CloudHSMV2" }, "glue": { "name": "Glue" }, "mobile": { "name": "Mobile" }, "pricing": { "name": "Pricing", "cors": true }, "costexplorer": { "prefix": "ce", "name": "CostExplorer", "cors": true }, "mediaconvert": { "name": "MediaConvert" }, "medialive": { "name": "MediaLive" }, "mediapackage": { "name": "MediaPackage" }, "mediastore": { "name": "MediaStore" }, "mediastoredata": { "prefix": "mediastore-data", "name": "MediaStoreData", "cors": true }, "appsync": { "name": "AppSync" }, "guardduty": { "name": "GuardDuty" }, "mq": { "name": "MQ" }, "comprehend": { "name": "Comprehend", "cors": true }, "iotjobsdataplane": { "prefix": "iot-jobs-data", "name": "IoTJobsDataPlane" }, "kinesisvideoarchivedmedia": { "prefix": "kinesis-video-archived-media", "name": "KinesisVideoArchivedMedia", "cors": true }, "kinesisvideomedia": { "prefix": "kinesis-video-media", "name": "KinesisVideoMedia", "cors": true }, "kinesisvideo": { "name": "KinesisVideo", "cors": true }, "sagemakerruntime": { "prefix": "runtime.sagemaker", "name": "SageMakerRuntime" }, "sagemaker": { "name": "SageMaker" }, "translate": { "name": "Translate", "cors": true }, "resourcegroups": { "prefix": "resource-groups", "name": "ResourceGroups", "cors": true }, "alexaforbusiness": { "name": "AlexaForBusiness" }, "cloud9": { "name": "Cloud9" }, "serverlessapplicationrepository": { "prefix": "serverlessrepo", "name": "ServerlessApplicationRepository" }, "servicediscovery": { "name": "ServiceDiscovery" }, "workmail": { "name": "WorkMail" }, "autoscalingplans": { "prefix": "autoscaling-plans", "name": "AutoScalingPlans" }, "transcribeservice": { "prefix": "transcribe", "name": "TranscribeService" }, "acmpca": { "prefix": "acm-pca", "name": "ACMPCA" }, "fms": { "name": "FMS" }, "secretsmanager": { "name": "SecretsManager", "cors": true }, "iotanalytics": { "name": "IoTAnalytics", "cors": true }, "iot1clickdevicesservice": { "prefix": "iot1click-devices", "name": "IoT1ClickDevicesService" }, "iot1clickprojects": { "prefix": "iot1click-projects", "name": "IoT1ClickProjects" }, "pi": { "name": "PI" }, "neptune": { "name": "Neptune" }, "mediatailor": { "name": "MediaTailor" }, "eks": { "name": "EKS" }, "macie": { "name": "Macie" }, "dlm": { "name": "DLM" }, "signer": { "name": "Signer" }, "chime": { "name": "Chime" }, "pinpointemail": { "prefix": "pinpoint-email", "name": "PinpointEmail" }, "ram": { "name": "RAM" }, "route53resolver": { "name": "Route53Resolver" }, "pinpointsmsvoice": { "prefix": "sms-voice", "name": "PinpointSMSVoice" }, "quicksight": { "name": "QuickSight" }, "rdsdataservice": { "prefix": "rds-data", "name": "RDSDataService" }, "amplify": { "name": "Amplify" }, "datasync": { "name": "DataSync" }, "robomaker": { "name": "RoboMaker" }, "transfer": { "name": "Transfer" }, "globalaccelerator": { "name": "GlobalAccelerator" }, "comprehendmedical": { "name": "ComprehendMedical", "cors": true }, "kinesisanalyticsv2": { "name": "KinesisAnalyticsV2" }, "mediaconnect": { "name": "MediaConnect" }, "fsx": { "name": "FSx" }, "securityhub": { "name": "SecurityHub" }, "appmesh": { "name": "AppMesh", "versions": ["2018-10-01*"] }, "licensemanager": { "prefix": "license-manager", "name": "LicenseManager" }, "kafka": { "name": "Kafka" }, "apigatewaymanagementapi": { "name": "ApiGatewayManagementApi" }, "apigatewayv2": { "name": "ApiGatewayV2" }, "docdb": { "name": "DocDB" }, "backup": { "name": "Backup" }, "worklink": { "name": "WorkLink" }, "textract": { "name": "Textract" }, "managedblockchain": { "name": "ManagedBlockchain" }, "mediapackagevod": { "prefix": "mediapackage-vod", "name": "MediaPackageVod" }, "groundstation": { "name": "GroundStation" }, "iotthingsgraph": { "name": "IoTThingsGraph" }, "iotevents": { "name": "IoTEvents" }, "ioteventsdata": { "prefix": "iotevents-data", "name": "IoTEventsData" }, "personalize": { "name": "Personalize", "cors": true }, "personalizeevents": { "prefix": "personalize-events", "name": "PersonalizeEvents", "cors": true }, "personalizeruntime": { "prefix": "personalize-runtime", "name": "PersonalizeRuntime", "cors": true }, "applicationinsights": { "prefix": "application-insights", "name": "ApplicationInsights" }, "servicequotas": { "prefix": "service-quotas", "name": "ServiceQuotas" }, "ec2instanceconnect": { "prefix": "ec2-instance-connect", "name": "EC2InstanceConnect" }, "eventbridge": { "name": "EventBridge" }, "lakeformation": { "name": "LakeFormation" }, "forecastservice": { "prefix": "forecast", "name": "ForecastService", "cors": true }, "forecastqueryservice": { "prefix": "forecastquery", "name": "ForecastQueryService", "cors": true }, "qldb": { "name": "QLDB" }, "qldbsession": { "prefix": "qldb-session", "name": "QLDBSession" }, "workmailmessageflow": { "name": "WorkMailMessageFlow" } }; }, {}], 5: [function (require, module, exports) { module.exports = { "version": "2.0", "metadata": { "apiVersion": "2011-06-15", "endpointPrefix": "sts", "globalEndpoint": "sts.amazonaws.com", "protocol": "query", "serviceAbbreviation": "AWS STS", "serviceFullName": "AWS Security Token Service", "serviceId": "STS", "signatureVersion": "v4", "uid": "sts-2011-06-15", "xmlNamespace": "https://sts.amazonaws.com/doc/2011-06-15/" }, "operations": { "AssumeRole": { "input": { "type": "structure", "required": ["RoleArn", "RoleSessionName"], "members": { "RoleArn": {}, "RoleSessionName": {}, "PolicyArns": { "shape": "S4" }, "Policy": {}, "DurationSeconds": { "type": "integer" }, "ExternalId": {}, "SerialNumber": {}, "TokenCode": {} } }, "output": { "resultWrapper": "AssumeRoleResult", "type": "structure", "members": { "Credentials": { "shape": "Sc" }, "AssumedRoleUser": { "shape": "Sh" }, "PackedPolicySize": { "type": "integer" } } } }, "AssumeRoleWithSAML": { "input": { "type": "structure", "required": ["RoleArn", "PrincipalArn", "SAMLAssertion"], "members": { "RoleArn": {}, "PrincipalArn": {}, "SAMLAssertion": {}, "PolicyArns": { "shape": "S4" }, "Policy": {}, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "AssumeRoleWithSAMLResult", "type": "structure", "members": { "Credentials": { "shape": "Sc" }, "AssumedRoleUser": { "shape": "Sh" }, "PackedPolicySize": { "type": "integer" }, "Subject": {}, "SubjectType": {}, "Issuer": {}, "Audience": {}, "NameQualifier": {} } } }, "AssumeRoleWithWebIdentity": { "input": { "type": "structure", "required": ["RoleArn", "RoleSessionName", "WebIdentityToken"], "members": { "RoleArn": {}, "RoleSessionName": {}, "WebIdentityToken": {}, "ProviderId": {}, "PolicyArns": { "shape": "S4" }, "Policy": {}, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "AssumeRoleWithWebIdentityResult", "type": "structure", "members": { "Credentials": { "shape": "Sc" }, "SubjectFromWebIdentityToken": {}, "AssumedRoleUser": { "shape": "Sh" }, "PackedPolicySize": { "type": "integer" }, "Provider": {}, "Audience": {} } } }, "DecodeAuthorizationMessage": { "input": { "type": "structure", "required": ["EncodedMessage"], "members": { "EncodedMessage": {} } }, "output": { "resultWrapper": "DecodeAuthorizationMessageResult", "type": "structure", "members": { "DecodedMessage": {} } } }, "GetAccessKeyInfo": { "input": { "type": "structure", "required": ["AccessKeyId"], "members": { "AccessKeyId": {} } }, "output": { "resultWrapper": "GetAccessKeyInfoResult", "type": "structure", "members": { "Account": {} } } }, "GetCallerIdentity": { "input": { "type": "structure", "members": {} }, "output": { "resultWrapper": "GetCallerIdentityResult", "type": "structure", "members": { "UserId": {}, "Account": {}, "Arn": {} } } }, "GetFederationToken": { "input": { "type": "structure", "required": ["Name"], "members": { "Name": {}, "Policy": {}, "PolicyArns": { "shape": "S4" }, "DurationSeconds": { "type": "integer" } } }, "output": { "resultWrapper": "GetFederationTokenResult", "type": "structure", "members": { "Credentials": { "shape": "Sc" }, "FederatedUser": { "type": "structure", "required": ["FederatedUserId", "Arn"], "members": { "FederatedUserId": {}, "Arn": {} } }, "PackedPolicySize": { "type": "integer" } } } }, "GetSessionToken": { "input": { "type": "structure", "members": { "DurationSeconds": { "type": "integer" }, "SerialNumber": {}, "TokenCode": {} } }, "output": { "resultWrapper": "GetSessionTokenResult", "type": "structure", "members": { "Credentials": { "shape": "Sc" } } } } }, "shapes": { "S4": { "type": "list", "member": { "type": "structure", "members": { "arn": {} } } }, "Sc": { "type": "structure", "required": ["AccessKeyId", "SecretAccessKey", "SessionToken", "Expiration"], "members": { "AccessKeyId": {}, "SecretAccessKey": {}, "SessionToken": {}, "Expiration": { "type": "timestamp" } } }, "Sh": { "type": "structure", "required": ["AssumedRoleId", "Arn"], "members": { "AssumedRoleId": {}, "Arn": {} } } } }; }, {}], 6: [function (require, module, exports) { arguments[4][2][0].apply(exports, arguments); }, { "dup": 2 }], 7: [function (require, module, exports) { require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = AWS.Service; var apiLoader = AWS.apiLoader; apiLoader.services['cognitoidentity'] = {}; AWS.CognitoIdentity = Service.defineService('cognitoidentity', ['2014-06-30']); require('../lib/services/cognitoidentity'); Object.defineProperty(apiLoader.services['cognitoidentity'], '2014-06-30', { get: function get() { var model = require('../apis/cognito-identity-2014-06-30.min.json'); model.paginators = require('../apis/cognito-identity-2014-06-30.paginators.json').pagination; return model; }, enumerable: true, configurable: true }); module.exports = AWS.CognitoIdentity; }, { "../apis/cognito-identity-2014-06-30.min.json": 1, "../apis/cognito-identity-2014-06-30.paginators.json": 2, "../lib/core": 18, "../lib/node_loader": 16, "../lib/services/cognitoidentity": 60 }], 8: [function (require, module, exports) { require('../lib/node_loader'); var AWS = require('../lib/core'); var Service = AWS.Service; var apiLoader = AWS.apiLoader; apiLoader.services['sts'] = {}; AWS.STS = Service.defineService('sts', ['2011-06-15']); require('../lib/services/sts'); Object.defineProperty(apiLoader.services['sts'], '2011-06-15', { get: function get() { var model = require('../apis/sts-2011-06-15.min.json'); model.paginators = require('../apis/sts-2011-06-15.paginators.json').pagination; return model; }, enumerable: true, configurable: true }); module.exports = AWS.STS; }, { "../apis/sts-2011-06-15.min.json": 5, "../apis/sts-2011-06-15.paginators.json": 6, "../lib/core": 18, "../lib/node_loader": 16, "../lib/services/sts": 61 }], 9: [function (require, module, exports) { - function apiLoader(svc, version) { if (!apiLoader.services.hasOwnProperty(svc)) { throw new Error('InvalidService: Failed to load api for ' + svc); } return apiLoader.services[svc][version]; }/** +var __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o;}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o;},_typeof(o);}// AWS SDK for JavaScript v2.553.0 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c=undefined;if(!f&&c)return require(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a;}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r);},p,p.exports,r,e,n,t);}return n[i].exports;}for(var u=undefined,i=0;i -1; }; }/** + */if(typeof ArrayBuffer!=='undefined'&&typeof ArrayBuffer.isView==='undefined'){ArrayBuffer.isView=function(arg){return viewStrings.indexOf(Object.prototype.toString.call(arg))>-1;};}/** * @api private - */var viewStrings = ['[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]', '[object DataView]'];/** + */var viewStrings=['[object Int8Array]','[object Uint8Array]','[object Uint8ClampedArray]','[object Int16Array]','[object Uint16Array]','[object Int32Array]','[object Uint32Array]','[object Float32Array]','[object Float64Array]','[object DataView]'];/** * @api private - */function isEmptyData(data) { if (typeof data === 'string') { return data.length === 0; } return data.byteLength === 0; }/** + */function isEmptyData(data){if(typeof data==='string'){return data.length===0;}return data.byteLength===0;}/** * @api private - */function convertToBuffer(data) { if (typeof data === 'string') { data = new Buffer(data, 'utf8'); } if (ArrayBuffer.isView(data)) { return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); } return new Uint8Array(data); }/** + */function convertToBuffer(data){if(typeof data==='string'){data=new Buffer(data,'utf8');}if(ArrayBuffer.isView(data)){return new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT);}return new Uint8Array(data);}/** * @api private - */module.exports = exports = { isEmptyData: isEmptyData, convertToBuffer: convertToBuffer }; - }, { "buffer/": 81 }], 12: [function (require, module, exports) { - var hashUtils = require('./browserHashUtils');/** + */module.exports=exports={isEmptyData:isEmptyData,convertToBuffer:convertToBuffer};},{"buffer/":81}],12:[function(require,module,exports){var hashUtils=require('./browserHashUtils');/** * @api private - */function Hmac(hashCtor, secret) { - this.hash = new hashCtor(); this.outer = new hashCtor(); var inner = bufferFromSecret(hashCtor, secret); var outer = new Uint8Array(hashCtor.BLOCK_SIZE); outer.set(inner); for (var i = 0; i < hashCtor.BLOCK_SIZE; i++) { inner[i] ^= 0x36; outer[i] ^= 0x5c; } this.hash.update(inner); this.outer.update(outer);// Zero out the copied key buffer. - for (var i = 0; i < inner.byteLength; i++) { inner[i] = 0; } - }/** + */function Hmac(hashCtor,secret){this.hash=new hashCtor();this.outer=new hashCtor();var inner=bufferFromSecret(hashCtor,secret);var outer=new Uint8Array(hashCtor.BLOCK_SIZE);outer.set(inner);for(var i=0;i hashCtor.BLOCK_SIZE) { var bufferHash = new hashCtor(); bufferHash.update(input); input = bufferHash.digest(); } var buffer = new Uint8Array(hashCtor.BLOCK_SIZE); buffer.set(input); return buffer; } - }, { "./browserHashUtils": 11 }], 13: [function (require, module, exports) { - var hashUtils = require('./browserHashUtils'); var Buffer = require('buffer/').Buffer; var BLOCK_SIZE = 64; var DIGEST_LENGTH = 16; var INIT = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];/** + */module.exports=exports=Hmac;Hmac.prototype.update=function(toHash){if(hashUtils.isEmptyData(toHash)||this.error){return this;}try{this.hash.update(hashUtils.convertToBuffer(toHash));}catch(e){this.error=e;}return this;};Hmac.prototype.digest=function(encoding){if(!this.outer.finished){this.outer.update(this.hash.digest());}return this.outer.digest(encoding);};function bufferFromSecret(hashCtor,secret){var input=hashUtils.convertToBuffer(secret);if(input.byteLength>hashCtor.BLOCK_SIZE){var bufferHash=new hashCtor();bufferHash.update(input);input=bufferHash.digest();}var buffer=new Uint8Array(hashCtor.BLOCK_SIZE);buffer.set(input);return buffer;}},{"./browserHashUtils":11}],13:[function(require,module,exports){var hashUtils=require('./browserHashUtils');var Buffer=require('buffer/').Buffer;var BLOCK_SIZE=64;var DIGEST_LENGTH=16;var INIT=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];/** * @api private - */function Md5() { this.state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]; this.buffer = new DataView(new ArrayBuffer(BLOCK_SIZE)); this.bufferLength = 0; this.bytesHashed = 0; this.finished = false; }/** + */function Md5(){this.state=[0x67452301,0xefcdab89,0x98badcfe,0x10325476];this.buffer=new DataView(new ArrayBuffer(BLOCK_SIZE));this.bufferLength=0;this.bytesHashed=0;this.finished=false;}/** * @api private - */module.exports = exports = Md5; Md5.BLOCK_SIZE = BLOCK_SIZE; Md5.prototype.update = function (sourceData) { if (hashUtils.isEmptyData(sourceData)) { return this; } else if (this.finished) { throw new Error('Attempted to update an already finished hash.'); } var data = hashUtils.convertToBuffer(sourceData); var position = 0; var byteLength = data.byteLength; this.bytesHashed += byteLength; while (byteLength > 0) { this.buffer.setUint8(this.bufferLength++, data[position++]); byteLength--; if (this.bufferLength === BLOCK_SIZE) { this.hashBuffer(); this.bufferLength = 0; } } return this; }; Md5.prototype.digest = function (encoding) { - if (!this.finished) { - var _a = this, buffer = _a.buffer, undecoratedLength = _a.bufferLength, bytesHashed = _a.bytesHashed; var bitsHashed = bytesHashed * 8; buffer.setUint8(this.bufferLength++, 128);// Ensure the final block has enough room for the hashed length - if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) { for (var i = this.bufferLength; i < BLOCK_SIZE; i++) { buffer.setUint8(i, 0); } this.hashBuffer(); this.bufferLength = 0; } for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) { buffer.setUint8(i, 0); } buffer.setUint32(BLOCK_SIZE - 8, bitsHashed >>> 0, true); buffer.setUint32(BLOCK_SIZE - 4, Math.floor(bitsHashed / 0x100000000), true); this.hashBuffer(); this.finished = true; - } var out = new DataView(new ArrayBuffer(DIGEST_LENGTH)); for (var i = 0; i < 4; i++) { out.setUint32(i * 4, this.state[i], true); } var buff = new Buffer(out.buffer, out.byteOffset, out.byteLength); return encoding ? buff.toString(encoding) : buff; - }; Md5.prototype.hashBuffer = function () { var _a = this, buffer = _a.buffer, state = _a.state; var a = state[0], b = state[1], c = state[2], d = state[3]; a = ff(a, b, c, d, buffer.getUint32(0, true), 7, 0xd76aa478); d = ff(d, a, b, c, buffer.getUint32(4, true), 12, 0xe8c7b756); c = ff(c, d, a, b, buffer.getUint32(8, true), 17, 0x242070db); b = ff(b, c, d, a, buffer.getUint32(12, true), 22, 0xc1bdceee); a = ff(a, b, c, d, buffer.getUint32(16, true), 7, 0xf57c0faf); d = ff(d, a, b, c, buffer.getUint32(20, true), 12, 0x4787c62a); c = ff(c, d, a, b, buffer.getUint32(24, true), 17, 0xa8304613); b = ff(b, c, d, a, buffer.getUint32(28, true), 22, 0xfd469501); a = ff(a, b, c, d, buffer.getUint32(32, true), 7, 0x698098d8); d = ff(d, a, b, c, buffer.getUint32(36, true), 12, 0x8b44f7af); c = ff(c, d, a, b, buffer.getUint32(40, true), 17, 0xffff5bb1); b = ff(b, c, d, a, buffer.getUint32(44, true), 22, 0x895cd7be); a = ff(a, b, c, d, buffer.getUint32(48, true), 7, 0x6b901122); d = ff(d, a, b, c, buffer.getUint32(52, true), 12, 0xfd987193); c = ff(c, d, a, b, buffer.getUint32(56, true), 17, 0xa679438e); b = ff(b, c, d, a, buffer.getUint32(60, true), 22, 0x49b40821); a = gg(a, b, c, d, buffer.getUint32(4, true), 5, 0xf61e2562); d = gg(d, a, b, c, buffer.getUint32(24, true), 9, 0xc040b340); c = gg(c, d, a, b, buffer.getUint32(44, true), 14, 0x265e5a51); b = gg(b, c, d, a, buffer.getUint32(0, true), 20, 0xe9b6c7aa); a = gg(a, b, c, d, buffer.getUint32(20, true), 5, 0xd62f105d); d = gg(d, a, b, c, buffer.getUint32(40, true), 9, 0x02441453); c = gg(c, d, a, b, buffer.getUint32(60, true), 14, 0xd8a1e681); b = gg(b, c, d, a, buffer.getUint32(16, true), 20, 0xe7d3fbc8); a = gg(a, b, c, d, buffer.getUint32(36, true), 5, 0x21e1cde6); d = gg(d, a, b, c, buffer.getUint32(56, true), 9, 0xc33707d6); c = gg(c, d, a, b, buffer.getUint32(12, true), 14, 0xf4d50d87); b = gg(b, c, d, a, buffer.getUint32(32, true), 20, 0x455a14ed); a = gg(a, b, c, d, buffer.getUint32(52, true), 5, 0xa9e3e905); d = gg(d, a, b, c, buffer.getUint32(8, true), 9, 0xfcefa3f8); c = gg(c, d, a, b, buffer.getUint32(28, true), 14, 0x676f02d9); b = gg(b, c, d, a, buffer.getUint32(48, true), 20, 0x8d2a4c8a); a = hh(a, b, c, d, buffer.getUint32(20, true), 4, 0xfffa3942); d = hh(d, a, b, c, buffer.getUint32(32, true), 11, 0x8771f681); c = hh(c, d, a, b, buffer.getUint32(44, true), 16, 0x6d9d6122); b = hh(b, c, d, a, buffer.getUint32(56, true), 23, 0xfde5380c); a = hh(a, b, c, d, buffer.getUint32(4, true), 4, 0xa4beea44); d = hh(d, a, b, c, buffer.getUint32(16, true), 11, 0x4bdecfa9); c = hh(c, d, a, b, buffer.getUint32(28, true), 16, 0xf6bb4b60); b = hh(b, c, d, a, buffer.getUint32(40, true), 23, 0xbebfbc70); a = hh(a, b, c, d, buffer.getUint32(52, true), 4, 0x289b7ec6); d = hh(d, a, b, c, buffer.getUint32(0, true), 11, 0xeaa127fa); c = hh(c, d, a, b, buffer.getUint32(12, true), 16, 0xd4ef3085); b = hh(b, c, d, a, buffer.getUint32(24, true), 23, 0x04881d05); a = hh(a, b, c, d, buffer.getUint32(36, true), 4, 0xd9d4d039); d = hh(d, a, b, c, buffer.getUint32(48, true), 11, 0xe6db99e5); c = hh(c, d, a, b, buffer.getUint32(60, true), 16, 0x1fa27cf8); b = hh(b, c, d, a, buffer.getUint32(8, true), 23, 0xc4ac5665); a = ii(a, b, c, d, buffer.getUint32(0, true), 6, 0xf4292244); d = ii(d, a, b, c, buffer.getUint32(28, true), 10, 0x432aff97); c = ii(c, d, a, b, buffer.getUint32(56, true), 15, 0xab9423a7); b = ii(b, c, d, a, buffer.getUint32(20, true), 21, 0xfc93a039); a = ii(a, b, c, d, buffer.getUint32(48, true), 6, 0x655b59c3); d = ii(d, a, b, c, buffer.getUint32(12, true), 10, 0x8f0ccc92); c = ii(c, d, a, b, buffer.getUint32(40, true), 15, 0xffeff47d); b = ii(b, c, d, a, buffer.getUint32(4, true), 21, 0x85845dd1); a = ii(a, b, c, d, buffer.getUint32(32, true), 6, 0x6fa87e4f); d = ii(d, a, b, c, buffer.getUint32(60, true), 10, 0xfe2ce6e0); c = ii(c, d, a, b, buffer.getUint32(24, true), 15, 0xa3014314); b = ii(b, c, d, a, buffer.getUint32(52, true), 21, 0x4e0811a1); a = ii(a, b, c, d, buffer.getUint32(16, true), 6, 0xf7537e82); d = ii(d, a, b, c, buffer.getUint32(44, true), 10, 0xbd3af235); c = ii(c, d, a, b, buffer.getUint32(8, true), 15, 0x2ad7d2bb); b = ii(b, c, d, a, buffer.getUint32(36, true), 21, 0xeb86d391); state[0] = a + state[0] & 0xFFFFFFFF; state[1] = b + state[1] & 0xFFFFFFFF; state[2] = c + state[2] & 0xFFFFFFFF; state[3] = d + state[3] & 0xFFFFFFFF; }; function cmn(q, a, b, x, s, t) { a = (a + q & 0xFFFFFFFF) + (x + t & 0xFFFFFFFF) & 0xFFFFFFFF; return (a << s | a >>> 32 - s) + b & 0xFFFFFFFF; } function ff(a, b, c, d, x, s, t) { return cmn(b & c | ~b & d, a, b, x, s, t); } function gg(a, b, c, d, x, s, t) { return cmn(b & d | c & ~d, a, b, x, s, t); } function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); } function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | ~d), a, b, x, s, t); } - }, { "./browserHashUtils": 11, "buffer/": 81 }], 14: [function (require, module, exports) { - var Buffer = require('buffer/').Buffer; var hashUtils = require('./browserHashUtils'); var BLOCK_SIZE = 64; var DIGEST_LENGTH = 20; var KEY = new Uint32Array([0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]); var INIT = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;/** + */module.exports=exports=Md5;Md5.BLOCK_SIZE=BLOCK_SIZE;Md5.prototype.update=function(sourceData){if(hashUtils.isEmptyData(sourceData)){return this;}else if(this.finished){throw new Error('Attempted to update an already finished hash.');}var data=hashUtils.convertToBuffer(sourceData);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;while(byteLength>0){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Md5.prototype.digest=function(encoding){if(!this.finished){var _a=this,buffer=_a.buffer,undecoratedLength=_a.bufferLength,bytesHashed=_a.bytesHashed;var bitsHashed=bytesHashed*8;buffer.setUint8(this.bufferLength++,128);// Ensure the final block has enough room for the hashed length +if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>0,true);buffer.setUint32(BLOCK_SIZE-4,Math.floor(bitsHashed/0x100000000),true);this.hashBuffer();this.finished=true;}var out=new DataView(new ArrayBuffer(DIGEST_LENGTH));for(var i=0;i<4;i++){out.setUint32(i*4,this.state[i],true);}var buff=new Buffer(out.buffer,out.byteOffset,out.byteLength);return encoding?buff.toString(encoding):buff;};Md5.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var a=state[0],b=state[1],c=state[2],d=state[3];a=ff(a,b,c,d,buffer.getUint32(0,true),7,0xd76aa478);d=ff(d,a,b,c,buffer.getUint32(4,true),12,0xe8c7b756);c=ff(c,d,a,b,buffer.getUint32(8,true),17,0x242070db);b=ff(b,c,d,a,buffer.getUint32(12,true),22,0xc1bdceee);a=ff(a,b,c,d,buffer.getUint32(16,true),7,0xf57c0faf);d=ff(d,a,b,c,buffer.getUint32(20,true),12,0x4787c62a);c=ff(c,d,a,b,buffer.getUint32(24,true),17,0xa8304613);b=ff(b,c,d,a,buffer.getUint32(28,true),22,0xfd469501);a=ff(a,b,c,d,buffer.getUint32(32,true),7,0x698098d8);d=ff(d,a,b,c,buffer.getUint32(36,true),12,0x8b44f7af);c=ff(c,d,a,b,buffer.getUint32(40,true),17,0xffff5bb1);b=ff(b,c,d,a,buffer.getUint32(44,true),22,0x895cd7be);a=ff(a,b,c,d,buffer.getUint32(48,true),7,0x6b901122);d=ff(d,a,b,c,buffer.getUint32(52,true),12,0xfd987193);c=ff(c,d,a,b,buffer.getUint32(56,true),17,0xa679438e);b=ff(b,c,d,a,buffer.getUint32(60,true),22,0x49b40821);a=gg(a,b,c,d,buffer.getUint32(4,true),5,0xf61e2562);d=gg(d,a,b,c,buffer.getUint32(24,true),9,0xc040b340);c=gg(c,d,a,b,buffer.getUint32(44,true),14,0x265e5a51);b=gg(b,c,d,a,buffer.getUint32(0,true),20,0xe9b6c7aa);a=gg(a,b,c,d,buffer.getUint32(20,true),5,0xd62f105d);d=gg(d,a,b,c,buffer.getUint32(40,true),9,0x02441453);c=gg(c,d,a,b,buffer.getUint32(60,true),14,0xd8a1e681);b=gg(b,c,d,a,buffer.getUint32(16,true),20,0xe7d3fbc8);a=gg(a,b,c,d,buffer.getUint32(36,true),5,0x21e1cde6);d=gg(d,a,b,c,buffer.getUint32(56,true),9,0xc33707d6);c=gg(c,d,a,b,buffer.getUint32(12,true),14,0xf4d50d87);b=gg(b,c,d,a,buffer.getUint32(32,true),20,0x455a14ed);a=gg(a,b,c,d,buffer.getUint32(52,true),5,0xa9e3e905);d=gg(d,a,b,c,buffer.getUint32(8,true),9,0xfcefa3f8);c=gg(c,d,a,b,buffer.getUint32(28,true),14,0x676f02d9);b=gg(b,c,d,a,buffer.getUint32(48,true),20,0x8d2a4c8a);a=hh(a,b,c,d,buffer.getUint32(20,true),4,0xfffa3942);d=hh(d,a,b,c,buffer.getUint32(32,true),11,0x8771f681);c=hh(c,d,a,b,buffer.getUint32(44,true),16,0x6d9d6122);b=hh(b,c,d,a,buffer.getUint32(56,true),23,0xfde5380c);a=hh(a,b,c,d,buffer.getUint32(4,true),4,0xa4beea44);d=hh(d,a,b,c,buffer.getUint32(16,true),11,0x4bdecfa9);c=hh(c,d,a,b,buffer.getUint32(28,true),16,0xf6bb4b60);b=hh(b,c,d,a,buffer.getUint32(40,true),23,0xbebfbc70);a=hh(a,b,c,d,buffer.getUint32(52,true),4,0x289b7ec6);d=hh(d,a,b,c,buffer.getUint32(0,true),11,0xeaa127fa);c=hh(c,d,a,b,buffer.getUint32(12,true),16,0xd4ef3085);b=hh(b,c,d,a,buffer.getUint32(24,true),23,0x04881d05);a=hh(a,b,c,d,buffer.getUint32(36,true),4,0xd9d4d039);d=hh(d,a,b,c,buffer.getUint32(48,true),11,0xe6db99e5);c=hh(c,d,a,b,buffer.getUint32(60,true),16,0x1fa27cf8);b=hh(b,c,d,a,buffer.getUint32(8,true),23,0xc4ac5665);a=ii(a,b,c,d,buffer.getUint32(0,true),6,0xf4292244);d=ii(d,a,b,c,buffer.getUint32(28,true),10,0x432aff97);c=ii(c,d,a,b,buffer.getUint32(56,true),15,0xab9423a7);b=ii(b,c,d,a,buffer.getUint32(20,true),21,0xfc93a039);a=ii(a,b,c,d,buffer.getUint32(48,true),6,0x655b59c3);d=ii(d,a,b,c,buffer.getUint32(12,true),10,0x8f0ccc92);c=ii(c,d,a,b,buffer.getUint32(40,true),15,0xffeff47d);b=ii(b,c,d,a,buffer.getUint32(4,true),21,0x85845dd1);a=ii(a,b,c,d,buffer.getUint32(32,true),6,0x6fa87e4f);d=ii(d,a,b,c,buffer.getUint32(60,true),10,0xfe2ce6e0);c=ii(c,d,a,b,buffer.getUint32(24,true),15,0xa3014314);b=ii(b,c,d,a,buffer.getUint32(52,true),21,0x4e0811a1);a=ii(a,b,c,d,buffer.getUint32(16,true),6,0xf7537e82);d=ii(d,a,b,c,buffer.getUint32(44,true),10,0xbd3af235);c=ii(c,d,a,b,buffer.getUint32(8,true),15,0x2ad7d2bb);b=ii(b,c,d,a,buffer.getUint32(36,true),21,0xeb86d391);state[0]=a+state[0]&0xFFFFFFFF;state[1]=b+state[1]&0xFFFFFFFF;state[2]=c+state[2]&0xFFFFFFFF;state[3]=d+state[3]&0xFFFFFFFF;};function cmn(q,a,b,x,s,t){a=(a+q&0xFFFFFFFF)+(x+t&0xFFFFFFFF)&0xFFFFFFFF;return(a<>>32-s)+b&0xFFFFFFFF;}function ff(a,b,c,d,x,s,t){return cmn(b&c|~b&d,a,b,x,s,t);}function gg(a,b,c,d,x,s,t){return cmn(b&d|c&~d,a,b,x,s,t);}function hh(a,b,c,d,x,s,t){return cmn(b^c^d,a,b,x,s,t);}function ii(a,b,c,d,x,s,t){return cmn(c^(b|~d),a,b,x,s,t);}},{"./browserHashUtils":11,"buffer/":81}],14:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=20;var KEY=new Uint32Array([0x5a827999,0x6ed9eba1,0x8f1bbcdc|0,0xca62c1d6|0]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** * @api private - */function Sha1() { - this.h0 = 0x67452301; this.h1 = 0xEFCDAB89; this.h2 = 0x98BADCFE; this.h3 = 0x10325476; this.h4 = 0xC3D2E1F0;// The first 64 bytes (16 words) is the data chunk - this.block = new Uint32Array(80); this.offset = 0; this.shift = 24; this.totalLength = 0; - }/** + */function Sha1(){this.h0=0x67452301;this.h1=0xEFCDAB89;this.h2=0x98BADCFE;this.h3=0x10325476;this.h4=0xC3D2E1F0;// The first 64 bytes (16 words) is the data chunk +this.block=new Uint32Array(80);this.offset=0;this.shift=24;this.totalLength=0;}/** * @api private - */module.exports = exports = Sha1; Sha1.BLOCK_SIZE = BLOCK_SIZE; Sha1.prototype.update = function (data) { if (this.finished) { throw new Error('Attempted to update an already finished hash.'); } if (hashUtils.isEmptyData(data)) { return this; } data = hashUtils.convertToBuffer(data); var length = data.length; this.totalLength += length * 8; for (var i = 0; i < length; i++) { this.write(data[i]); } return this; }; Sha1.prototype.write = function write(_byte) { this.block[this.offset] |= (_byte & 0xff) << this.shift; if (this.shift) { this.shift -= 8; } else { this.offset++; this.shift = 24; } if (this.offset === 16) this.processBlock(); }; Sha1.prototype.digest = function (encoding) {// Pad - this.write(0x80); if (this.offset > 14 || this.offset === 14 && this.shift < 24) { this.processBlock(); } this.offset = 14; this.shift = 24;// 64-bit length big-endian - this.write(0x00);// numbers this big aren't accurate in javascript anyway - this.write(0x00);// ..So just hard-code to zero. - this.write(this.totalLength > 0xffffffffff ? this.totalLength / 0x10000000000 : 0x00); this.write(this.totalLength > 0xffffffff ? this.totalLength / 0x100000000 : 0x00); for (var s = 24; s >= 0; s -= 8) { this.write(this.totalLength >> s); }// The value in state is little-endian rather than big-endian, so flip - // each word into a new Uint8Array - var out = new Buffer(DIGEST_LENGTH); var outView = new DataView(out.buffer); outView.setUint32(0, this.h0, false); outView.setUint32(4, this.h1, false); outView.setUint32(8, this.h2, false); outView.setUint32(12, this.h3, false); outView.setUint32(16, this.h4, false); return encoding ? out.toString(encoding) : out; - }; Sha1.prototype.processBlock = function processBlock() {// Extend the sixteen 32-bit words into eighty 32-bit words: - for (var i = 16; i < 80; i++) { var w = this.block[i - 3] ^ this.block[i - 8] ^ this.block[i - 14] ^ this.block[i - 16]; this.block[i] = w << 1 | w >>> 31; }// Initialize hash value for this chunk: - var a = this.h0; var b = this.h1; var c = this.h2; var d = this.h3; var e = this.h4; var f, k;// Main loop: - for (i = 0; i < 80; i++) { if (i < 20) { f = d ^ b & (c ^ d); k = 0x5A827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if (i < 60) { f = b & c | d & (b | c); k = 0x8F1BBCDC; } else { f = b ^ c ^ d; k = 0xCA62C1D6; } var temp = (a << 5 | a >>> 27) + f + e + k + (this.block[i] | 0); e = d; d = c; c = b << 30 | b >>> 2; b = a; a = temp; }// Add this chunk's hash to result so far: - this.h0 = this.h0 + a | 0; this.h1 = this.h1 + b | 0; this.h2 = this.h2 + c | 0; this.h3 = this.h3 + d | 0; this.h4 = this.h4 + e | 0;// The block is now reusable. - this.offset = 0; for (i = 0; i < 16; i++) { this.block[i] = 0; } - }; - }, { "./browserHashUtils": 11, "buffer/": 81 }], 15: [function (require, module, exports) { - var Buffer = require('buffer/').Buffer; var hashUtils = require('./browserHashUtils'); var BLOCK_SIZE = 64; var DIGEST_LENGTH = 32; var KEY = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]); var INIT = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;/** + */module.exports=exports=Sha1;Sha1.BLOCK_SIZE=BLOCK_SIZE;Sha1.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var length=data.length;this.totalLength+=length*8;for(var i=0;i14||this.offset===14&&this.shift<24){this.processBlock();}this.offset=14;this.shift=24;// 64-bit length big-endian +this.write(0x00);// numbers this big aren't accurate in javascript anyway +this.write(0x00);// ..So just hard-code to zero. +this.write(this.totalLength>0xffffffffff?this.totalLength/0x10000000000:0x00);this.write(this.totalLength>0xffffffff?this.totalLength/0x100000000:0x00);for(var s=24;s>=0;s-=8){this.write(this.totalLength>>s);}// The value in state is little-endian rather than big-endian, so flip +// each word into a new Uint8Array +var out=new Buffer(DIGEST_LENGTH);var outView=new DataView(out.buffer);outView.setUint32(0,this.h0,false);outView.setUint32(4,this.h1,false);outView.setUint32(8,this.h2,false);outView.setUint32(12,this.h3,false);outView.setUint32(16,this.h4,false);return encoding?out.toString(encoding):out;};Sha1.prototype.processBlock=function processBlock(){// Extend the sixteen 32-bit words into eighty 32-bit words: +for(var i=16;i<80;i++){var w=this.block[i-3]^this.block[i-8]^this.block[i-14]^this.block[i-16];this.block[i]=w<<1|w>>>31;}// Initialize hash value for this chunk: +var a=this.h0;var b=this.h1;var c=this.h2;var d=this.h3;var e=this.h4;var f,k;// Main loop: +for(i=0;i<80;i++){if(i<20){f=d^b&(c^d);k=0x5A827999;}else if(i<40){f=b^c^d;k=0x6ED9EBA1;}else if(i<60){f=b&c|d&(b|c);k=0x8F1BBCDC;}else{f=b^c^d;k=0xCA62C1D6;}var temp=(a<<5|a>>>27)+f+e+k+(this.block[i]|0);e=d;d=c;c=b<<30|b>>>2;b=a;a=temp;}// Add this chunk's hash to result so far: +this.h0=this.h0+a|0;this.h1=this.h1+b|0;this.h2=this.h2+c|0;this.h3=this.h3+d|0;this.h4=this.h4+e|0;// The block is now reusable. +this.offset=0;for(i=0;i<16;i++){this.block[i]=0;}};},{"./browserHashUtils":11,"buffer/":81}],15:[function(require,module,exports){var Buffer=require('buffer/').Buffer;var hashUtils=require('./browserHashUtils');var BLOCK_SIZE=64;var DIGEST_LENGTH=32;var KEY=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]);var INIT=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];var MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;/** * @private - */function Sha256() { - this.state = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; this.temp = new Int32Array(64); this.buffer = new Uint8Array(64); this.bufferLength = 0; this.bytesHashed = 0;/** + */function Sha256(){this.state=[0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19];this.temp=new Int32Array(64);this.buffer=new Uint8Array(64);this.bufferLength=0;this.bytesHashed=0;/** * @private - */this.finished = false; - }/** + */this.finished=false;}/** * @api private - */module.exports = exports = Sha256; Sha256.BLOCK_SIZE = BLOCK_SIZE; Sha256.prototype.update = function (data) { if (this.finished) { throw new Error('Attempted to update an already finished hash.'); } if (hashUtils.isEmptyData(data)) { return this; } data = hashUtils.convertToBuffer(data); var position = 0; var byteLength = data.byteLength; this.bytesHashed += byteLength; if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) { throw new Error('Cannot hash more than 2^53 - 1 bits'); } while (byteLength > 0) { this.buffer[this.bufferLength++] = data[position++]; byteLength--; if (this.bufferLength === BLOCK_SIZE) { this.hashBuffer(); this.bufferLength = 0; } } return this; }; Sha256.prototype.digest = function (encoding) { - if (!this.finished) { - var bitsHashed = this.bytesHashed * 8; var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); var undecoratedLength = this.bufferLength; bufferView.setUint8(this.bufferLength++, 0x80);// Ensure the final block has enough room for the hashed length - if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) { for (var i = this.bufferLength; i < BLOCK_SIZE; i++) { bufferView.setUint8(i, 0); } this.hashBuffer(); this.bufferLength = 0; } for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) { bufferView.setUint8(i, 0); } bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true); bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed); this.hashBuffer(); this.finished = true; - }// The value in state is little-endian rather than big-endian, so flip - // each word into a new Uint8Array - var out = new Buffer(DIGEST_LENGTH); for (var i = 0; i < 8; i++) { out[i * 4] = this.state[i] >>> 24 & 0xff; out[i * 4 + 1] = this.state[i] >>> 16 & 0xff; out[i * 4 + 2] = this.state[i] >>> 8 & 0xff; out[i * 4 + 3] = this.state[i] >>> 0 & 0xff; } return encoding ? out.toString(encoding) : out; - }; Sha256.prototype.hashBuffer = function () { var _a = this, buffer = _a.buffer, state = _a.state; var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7]; for (var i = 0; i < BLOCK_SIZE; i++) { if (i < 16) { this.temp[i] = (buffer[i * 4] & 0xff) << 24 | (buffer[i * 4 + 1] & 0xff) << 16 | (buffer[i * 4 + 2] & 0xff) << 8 | buffer[i * 4 + 3] & 0xff; } else { var u = this.temp[i - 2]; var t1_1 = (u >>> 17 | u << 15) ^ (u >>> 19 | u << 13) ^ u >>> 10; u = this.temp[i - 15]; var t2_1 = (u >>> 7 | u << 25) ^ (u >>> 18 | u << 14) ^ u >>> 3; this.temp[i] = (t1_1 + this.temp[i - 7] | 0) + (t2_1 + this.temp[i - 16] | 0); } var t1 = (((state4 >>> 6 | state4 << 26) ^ (state4 >>> 11 | state4 << 21) ^ (state4 >>> 25 | state4 << 7)) + (state4 & state5 ^ ~state4 & state6) | 0) + (state7 + (KEY[i] + this.temp[i] | 0) | 0) | 0; var t2 = ((state0 >>> 2 | state0 << 30) ^ (state0 >>> 13 | state0 << 19) ^ (state0 >>> 22 | state0 << 10)) + (state0 & state1 ^ state0 & state2 ^ state1 & state2) | 0; state7 = state6; state6 = state5; state5 = state4; state4 = state3 + t1 | 0; state3 = state2; state2 = state1; state1 = state0; state0 = t1 + t2 | 0; } state[0] += state0; state[1] += state1; state[2] += state2; state[3] += state3; state[4] += state4; state[5] += state5; state[6] += state6; state[7] += state7; }; - }, { "./browserHashUtils": 11, "buffer/": 81 }], 16: [function (require, module, exports) { - (function (process) { - (function () { - var util = require('./util');// browser specific modules - util.crypto.lib = require('./browserCryptoLib'); util.Buffer = require('buffer/').Buffer; util.url = require('url/'); util.querystring = require('querystring/'); util.realClock = require('./realclock/browserClock'); util.environment = 'js'; util.createEventStream = require('./event-stream/buffered-create-event-stream').createEventStream; util.isBrowser = function () { return true; }; util.isNode = function () { return false; }; var AWS = require('./core');/** + */module.exports=exports=Sha256;Sha256.BLOCK_SIZE=BLOCK_SIZE;Sha256.prototype.update=function(data){if(this.finished){throw new Error('Attempted to update an already finished hash.');}if(hashUtils.isEmptyData(data)){return this;}data=hashUtils.convertToBuffer(data);var position=0;var byteLength=data.byteLength;this.bytesHashed+=byteLength;if(this.bytesHashed*8>MAX_HASHABLE_LENGTH){throw new Error('Cannot hash more than 2^53 - 1 bits');}while(byteLength>0){this.buffer[this.bufferLength++]=data[position++];byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0;}}return this;};Sha256.prototype.digest=function(encoding){if(!this.finished){var bitsHashed=this.bytesHashed*8;var bufferView=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength);var undecoratedLength=this.bufferLength;bufferView.setUint8(this.bufferLength++,0x80);// Ensure the final block has enough room for the hashed length +if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(var i=this.bufferLength;i>>24&0xff;out[i*4+1]=this.state[i]>>>16&0xff;out[i*4+2]=this.state[i]>>>8&0xff;out[i*4+3]=this.state[i]>>>0&0xff;}return encoding?out.toString(encoding):out;};Sha256.prototype.hashBuffer=function(){var _a=this,buffer=_a.buffer,state=_a.state;var state0=state[0],state1=state[1],state2=state[2],state3=state[3],state4=state[4],state5=state[5],state6=state[6],state7=state[7];for(var i=0;i>>17|u<<15)^(u>>>19|u<<13)^u>>>10;u=this.temp[i-15];var t2_1=(u>>>7|u<<25)^(u>>>18|u<<14)^u>>>3;this.temp[i]=(t1_1+this.temp[i-7]|0)+(t2_1+this.temp[i-16]|0);}var t1=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i]+this.temp[i]|0)|0)|0;var t2=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state2^state1&state2)|0;state7=state6;state6=state5;state5=state4;state4=state3+t1|0;state3=state2;state2=state1;state1=state0;state0=t1+t2|0;}state[0]+=state0;state[1]+=state1;state[2]+=state2;state[3]+=state3;state[4]+=state4;state[5]+=state5;state[6]+=state6;state[7]+=state7;};},{"./browserHashUtils":11,"buffer/":81}],16:[function(require,module,exports){(function(process){(function(){var util=require('./util');// browser specific modules +util.crypto.lib=require('./browserCryptoLib');util.Buffer=require('buffer/').Buffer;util.url=require('url/');util.querystring=require('querystring/');util.realClock=require('./realclock/browserClock');util.environment='js';util.createEventStream=require('./event-stream/buffered-create-event-stream').createEventStream;util.isBrowser=function(){return true;};util.isNode=function(){return false;};var AWS=require('./core');/** * @api private - */module.exports = AWS; require('./credentials'); require('./credentials/credential_provider_chain'); require('./credentials/temporary_credentials'); require('./credentials/chainable_temporary_credentials'); require('./credentials/web_identity_credentials'); require('./credentials/cognito_identity_credentials'); require('./credentials/saml_credentials');// Load the DOMParser XML parser - AWS.XML.Parser = require('./xml/browser_parser');// Load the XHR HttpClient - require('./http/xhr'); if (typeof process === 'undefined') { var process = { browser: true }; } - }).call(this); - }).call(this, require('_process')); - }, { "./browserCryptoLib": 10, "./core": 18, "./credentials": 19, "./credentials/chainable_temporary_credentials": 20, "./credentials/cognito_identity_credentials": 21, "./credentials/credential_provider_chain": 22, "./credentials/saml_credentials": 23, "./credentials/temporary_credentials": 24, "./credentials/web_identity_credentials": 25, "./event-stream/buffered-create-event-stream": 27, "./http/xhr": 35, "./realclock/browserClock": 52, "./util": 71, "./xml/browser_parser": 72, "_process": 86, "buffer/": 81, "querystring/": 92, "url/": 94 }], 17: [function (require, module, exports) { - var AWS = require('./core'); require('./credentials'); require('./credentials/credential_provider_chain'); var PromisesDependency;/** + */module.exports=AWS;require('./credentials');require('./credentials/credential_provider_chain');require('./credentials/temporary_credentials');require('./credentials/chainable_temporary_credentials');require('./credentials/web_identity_credentials');require('./credentials/cognito_identity_credentials');require('./credentials/saml_credentials');// Load the DOMParser XML parser +AWS.XML.Parser=require('./xml/browser_parser');// Load the XHR HttpClient +require('./http/xhr');if(typeof process==='undefined'){var process={browser:true};}}).call(this);}).call(this,require('_process'));},{"./browserCryptoLib":10,"./core":18,"./credentials":19,"./credentials/chainable_temporary_credentials":20,"./credentials/cognito_identity_credentials":21,"./credentials/credential_provider_chain":22,"./credentials/saml_credentials":23,"./credentials/temporary_credentials":24,"./credentials/web_identity_credentials":25,"./event-stream/buffered-create-event-stream":27,"./http/xhr":35,"./realclock/browserClock":52,"./util":71,"./xml/browser_parser":72,"_process":86,"buffer/":81,"querystring/":92,"url/":94}],17:[function(require,module,exports){var AWS=require('./core');require('./credentials');require('./credentials/credential_provider_chain');var PromisesDependency;/** * The main configuration class used by all service objects to set * the region, credentials, and other options for requests. * @@ -2323,7 +2282,7 @@ * @return ['legacy'|'regional'] whether to send sts request to global endpoints or * regional endpoints. * Defaults to 'legacy' - */AWS.Config = AWS.util.inherit({/** + */AWS.Config=AWS.util.inherit({/** * @!endgroup */ /** * Creates a new configuration object. This is the object that passes @@ -2461,7 +2420,7 @@ * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request * to global endpoints or regional endpoints. * Defaults to 'legacy'. - */constructor: function Config(options) { if (options === undefined) options = {}; options = this.extractCredentials(options); AWS.util.each.call(this, this.keys, function (key, value) { this.set(key, options[key], value); }); },/** + */constructor:function Config(options){if(options===undefined)options={};options=this.extractCredentials(options);AWS.util.each.call(this,this.keys,function(key,value){this.set(key,options[key],value);});},/** * @!group Managing Credentials */ /** * Loads credentials from the configuration object. This is used internally @@ -2487,13 +2446,8 @@ * loaded and this error provides information why. * @see credentials * @see Credentials - */getCredentials: function getCredentials(callback) { - var self = this; function finish(err) { callback(err, err ? null : self.credentials); } function credError(msg, err) { return new AWS.util.error(err || new Error(), { code: 'CredentialsError', message: msg, name: 'CredentialsError' }); } function getAsyncCredentials() { self.credentials.get(function (err) { if (err) { var msg = 'Could not load credentials from ' + self.credentials.constructor.name; err = credError(msg, err); } finish(err); }); } function getStaticCredentials() { var err = null; if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) { err = credError('Missing credentials'); } finish(err); } if (self.credentials) { - if (typeof self.credentials.get === 'function') { getAsyncCredentials(); } else {// static credentials - getStaticCredentials(); - } - } else if (self.credentialProvider) { self.credentialProvider.resolve(function (err, creds) { if (err) { err = credError('Could not load credentials from any providers', err); } self.credentials = creds; finish(err); }); } else { finish(credError('No credentials to load')); } - },/** + */getCredentials:function getCredentials(callback){var self=this;function finish(err){callback(err,err?null:self.credentials);}function credError(msg,err){return new AWS.util.error(err||new Error(),{code:'CredentialsError',message:msg,name:'CredentialsError'});}function getAsyncCredentials(){self.credentials.get(function(err){if(err){var msg='Could not load credentials from '+self.credentials.constructor.name;err=credError(msg,err);}finish(err);});}function getStaticCredentials(){var err=null;if(!self.credentials.accessKeyId||!self.credentials.secretAccessKey){err=credError('Missing credentials');}finish(err);}if(self.credentials){if(typeof self.credentials.get==='function'){getAsyncCredentials();}else{// static credentials +getStaticCredentials();}}else if(self.credentialProvider){self.credentialProvider.resolve(function(err,creds){if(err){err=credError('Could not load credentials from any providers',err);}self.credentials=creds;finish(err);});}else{finish(credError('No credentials to load'));}},/** * @!group Loading and Setting Configuration Options */ /** * @overload update(options, allowUnknownKeys = false) @@ -2505,7 +2459,7 @@ * @param [Boolean] allowUnknownKeys whether unknown keys can be set on * the configuration object. Defaults to `false`. * @see constructor - */update: function update(options, allowUnknownKeys) { allowUnknownKeys = allowUnknownKeys || false; options = this.extractCredentials(options); AWS.util.each.call(this, options, function (key, value) { if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) || AWS.Service.hasService(key)) { this.set(key, value); } }); },/** + */update:function update(options,allowUnknownKeys){allowUnknownKeys=allowUnknownKeys||false;options=this.extractCredentials(options);AWS.util.each.call(this,options,function(key,value){if(allowUnknownKeys||Object.prototype.hasOwnProperty.call(this.keys,key)||AWS.Service.hasService(key)){this.set(key,value);}});},/** * Loads configuration data from a JSON file into this config object. * @note Loading configuration will reset all existing configuration * on the object. @@ -2513,75 +2467,65 @@ * @param path [String] the path relative to your process's current * working directory to load configuration from. * @return [AWS.Config] the same configuration object - */loadFromPath: function loadFromPath(path) { this.clear(); var options = JSON.parse(AWS.util.readFileSync(path)); var fileSystemCreds = new AWS.FileSystemCredentials(path); var chain = new AWS.CredentialProviderChain(); chain.providers.unshift(fileSystemCreds); chain.resolve(function (err, creds) { if (err) throw err; else options.credentials = creds; }); this.constructor(options); return this; },/** + */loadFromPath:function loadFromPath(path){this.clear();var options=JSON.parse(AWS.util.readFileSync(path));var fileSystemCreds=new AWS.FileSystemCredentials(path);var chain=new AWS.CredentialProviderChain();chain.providers.unshift(fileSystemCreds);chain.resolve(function(err,creds){if(err)throw err;else options.credentials=creds;});this.constructor(options);return this;},/** * Clears configuration data on this object * * @api private - */clear: function clear() {/*jshint forin:false */AWS.util.each.call(this, this.keys, function (key) { delete this[key]; });// reset credential provider - this.set('credentials', undefined); this.set('credentialProvider', undefined); - },/** + */clear:function clear(){/*jshint forin:false */AWS.util.each.call(this,this.keys,function(key){delete this[key];});// reset credential provider +this.set('credentials',undefined);this.set('credentialProvider',undefined);},/** * Sets a property on the configuration object, allowing for a * default value * @api private - */set: function set(property, value, defaultValue) { - if (value === undefined) { if (defaultValue === undefined) { defaultValue = this.keys[property]; } if (typeof defaultValue === 'function') { this[property] = defaultValue.call(this); } else { this[property] = defaultValue; } } else if (property === 'httpOptions' && this[property]) {// deep merge httpOptions - this[property] = AWS.util.merge(this[property], value); - } else { this[property] = value; } - },/** + */set:function set(property,value,defaultValue){if(value===undefined){if(defaultValue===undefined){defaultValue=this.keys[property];}if(typeof defaultValue==='function'){this[property]=defaultValue.call(this);}else{this[property]=defaultValue;}}else if(property==='httpOptions'&&this[property]){// deep merge httpOptions +this[property]=AWS.util.merge(this[property],value);}else{this[property]=value;}},/** * All of the keys with their default values. * * @constant * @api private - */keys: { credentials: null, credentialProvider: null, region: null, logger: null, apiVersions: {}, apiVersion: null, endpoint: undefined, httpOptions: { timeout: 120000 }, maxRetries: undefined, maxRedirects: 10, paramValidation: true, sslEnabled: true, s3ForcePathStyle: false, s3BucketEndpoint: false, s3DisableBodySigning: true, computeChecksums: true, convertResponseTypes: true, correctClockSkew: false, customUserAgent: null, dynamoDbCrc32: true, systemClockOffset: 0, signatureVersion: null, signatureCache: true, retryDelayOptions: {}, useAccelerateEndpoint: false, clientSideMonitoring: false, endpointDiscoveryEnabled: false, endpointCacheSize: 1000, hostPrefixEnabled: true, stsRegionalEndpoints: null },/** + */keys:{credentials:null,credentialProvider:null,region:null,logger:null,apiVersions:{},apiVersion:null,endpoint:undefined,httpOptions:{timeout:120000},maxRetries:undefined,maxRedirects:10,paramValidation:true,sslEnabled:true,s3ForcePathStyle:false,s3BucketEndpoint:false,s3DisableBodySigning:true,computeChecksums:true,convertResponseTypes:true,correctClockSkew:false,customUserAgent:null,dynamoDbCrc32:true,systemClockOffset:0,signatureVersion:null,signatureCache:true,retryDelayOptions:{},useAccelerateEndpoint:false,clientSideMonitoring:false,endpointDiscoveryEnabled:false,endpointCacheSize:1000,hostPrefixEnabled:true,stsRegionalEndpoints:null},/** * Extracts accessKeyId, secretAccessKey and sessionToken * from a configuration hash. * * @api private - */extractCredentials: function extractCredentials(options) { if (options.accessKeyId && options.secretAccessKey) { options = AWS.util.copy(options); options.credentials = new AWS.Credentials(options); } return options; },/** + */extractCredentials:function extractCredentials(options){if(options.accessKeyId&&options.secretAccessKey){options=AWS.util.copy(options);options.credentials=new AWS.Credentials(options);}return options;},/** * Sets the promise dependency the SDK will use wherever Promises are returned. * Passing `null` will force the SDK to use native Promises if they are available. * If native Promises are not available, passing `null` will have no effect. * @param [Constructor] dep A reference to a Promise constructor - */setPromisesDependency: function setPromisesDependency(dep) { - PromisesDependency = dep;// if null was passed in, we should try to use native promises - if (dep === null && typeof Promise === 'function') { PromisesDependency = Promise; } var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain]; if (AWS.S3) { constructors.push(AWS.S3); if (AWS.S3.ManagedUpload) { constructors.push(AWS.S3.ManagedUpload); } } AWS.util.addPromises(constructors, PromisesDependency); - },/** + */setPromisesDependency:function setPromisesDependency(dep){PromisesDependency=dep;// if null was passed in, we should try to use native promises +if(dep===null&&typeof Promise==='function'){PromisesDependency=Promise;}var constructors=[AWS.Request,AWS.Credentials,AWS.CredentialProviderChain];if(AWS.S3){constructors.push(AWS.S3);if(AWS.S3.ManagedUpload){constructors.push(AWS.S3.ManagedUpload);}}AWS.util.addPromises(constructors,PromisesDependency);},/** * Gets the promise dependency set by `AWS.config.setPromisesDependency`. - */getPromisesDependency: function getPromisesDependency() { return PromisesDependency; } - });/** + */getPromisesDependency:function getPromisesDependency(){return PromisesDependency;}});/** * @return [AWS.Config] The global configuration object singleton instance * @readonly * @see AWS.Config - */AWS.config = new AWS.Config(); - }, { "./core": 18, "./credentials": 19, "./credentials/credential_provider_chain": 22 }], 18: [function (require, module, exports) {/** + */AWS.config=new AWS.Config();},{"./core":18,"./credentials":19,"./credentials/credential_provider_chain":22}],18:[function(require,module,exports){/** * The main AWS namespace - */var AWS = { util: require('./util') };/** + */var AWS={util:require('./util')};/** * @api private * @!macro [new] nobrowser * @note This feature is not supported in the browser environment of the SDK. - */var _hidden = {}; _hidden.toString();// hack to parse macro + */var _hidden={};_hidden.toString();// hack to parse macro /** * @api private - */module.exports = AWS; AWS.util.update(AWS, {/** + */module.exports=AWS;AWS.util.update(AWS,{/** * @constant - */VERSION: '2.553.0',/** + */VERSION:'2.553.0',/** * @api private - */Signers: {},/** + */Signers:{},/** * @api private - */Protocol: { Json: require('./protocol/json'), Query: require('./protocol/query'), Rest: require('./protocol/rest'), RestJson: require('./protocol/rest_json'), RestXml: require('./protocol/rest_xml') },/** + */Protocol:{Json:require('./protocol/json'),Query:require('./protocol/query'),Rest:require('./protocol/rest'),RestJson:require('./protocol/rest_json'),RestXml:require('./protocol/rest_xml')},/** * @api private - */XML: { - Builder: require('./xml/builder'), Parser: null// conditionally set based on environment - },/** + */XML:{Builder:require('./xml/builder'),Parser:null// conditionally set based on environment +},/** * @api private - */JSON: { Builder: require('./json/builder'), Parser: require('./json/parser') },/** + */JSON:{Builder:require('./json/builder'),Parser:require('./json/parser')},/** * @api private - */Model: { Api: require('./model/api'), Operation: require('./model/operation'), Shape: require('./model/shape'), Paginator: require('./model/paginator'), ResourceWaiter: require('./model/resource_waiter') },/** + */Model:{Api:require('./model/api'),Operation:require('./model/operation'),Shape:require('./model/shape'),Paginator:require('./model/paginator'),ResourceWaiter:require('./model/resource_waiter')},/** * @api private - */apiLoader: require('./api_loader'),/** + */apiLoader:require('./api_loader'),/** * @api private - */EndpointCache: require('../vendor/endpoint-cache').EndpointCache - }); require('./sequential_executor'); require('./service'); require('./config'); require('./http'); require('./event_listeners'); require('./request'); require('./response'); require('./resource_waiter'); require('./signers/request_signer'); require('./param_validator');/** + */EndpointCache:require('../vendor/endpoint-cache').EndpointCache});require('./sequential_executor');require('./service');require('./config');require('./http');require('./event_listeners');require('./request');require('./response');require('./resource_waiter');require('./signers/request_signer');require('./param_validator');/** * @readonly * @return [AWS.SequentialExecutor] a collection of global event listeners that * are attached to every sent request. @@ -2595,10 +2539,8 @@ * }); * * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds' - */AWS.events = new AWS.SequentialExecutor();//create endpoint cache lazily - AWS.util.memoizedProperty(AWS, 'endpointCache', function () { return new AWS.EndpointCache(AWS.config.endpointCacheSize); }, true); - }, { "../vendor/endpoint-cache": 103, "./api_loader": 9, "./config": 17, "./event_listeners": 33, "./http": 34, "./json/builder": 36, "./json/parser": 37, "./model/api": 38, "./model/operation": 40, "./model/paginator": 41, "./model/resource_waiter": 42, "./model/shape": 43, "./param_validator": 44, "./protocol/json": 46, "./protocol/query": 47, "./protocol/rest": 48, "./protocol/rest_json": 49, "./protocol/rest_xml": 50, "./request": 55, "./resource_waiter": 56, "./response": 57, "./sequential_executor": 58, "./service": 59, "./signers/request_signer": 63, "./util": 71, "./xml/builder": 73 }], 19: [function (require, module, exports) { - var AWS = require('./core');/** + */AWS.events=new AWS.SequentialExecutor();//create endpoint cache lazily +AWS.util.memoizedProperty(AWS,'endpointCache',function(){return new AWS.EndpointCache(AWS.config.endpointCacheSize);},true);},{"../vendor/endpoint-cache":103,"./api_loader":9,"./config":17,"./event_listeners":33,"./http":34,"./json/builder":36,"./json/parser":37,"./model/api":38,"./model/operation":40,"./model/paginator":41,"./model/resource_waiter":42,"./model/shape":43,"./param_validator":44,"./protocol/json":46,"./protocol/query":47,"./protocol/rest":48,"./protocol/rest_json":49,"./protocol/rest_xml":50,"./request":55,"./resource_waiter":56,"./response":57,"./sequential_executor":58,"./service":59,"./signers/request_signer":63,"./util":71,"./xml/builder":73}],19:[function(require,module,exports){var AWS=require('./core');/** * Represents your AWS security credentials, specifically the * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}. * Creating a `Credentials` object allows you to pass around your @@ -2635,7 +2577,7 @@ * @return [String] the AWS secret access key * @!attribute sessionToken * @return [String] an optional AWS session token - */AWS.Credentials = AWS.util.inherit({/** + */AWS.Credentials=AWS.util.inherit({/** * A credentials object can be created using positional arguments or an options * hash. * @@ -2657,16 +2599,15 @@ * var creds = new AWS.Credentials({ * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session' * }); - */constructor: function Credentials() {// hide secretAccessKey from being displayed with util.inspect - AWS.util.hideProperties(this, ['secretAccessKey']); this.expired = false; this.expireTime = null; this.refreshCallbacks = []; if (arguments.length === 1 && _typeof(arguments[0]) === 'object') { var creds = arguments[0].credentials || arguments[0]; this.accessKeyId = creds.accessKeyId; this.secretAccessKey = creds.secretAccessKey; this.sessionToken = creds.sessionToken; } else { this.accessKeyId = arguments[0]; this.secretAccessKey = arguments[1]; this.sessionToken = arguments[2]; } - },/** + */constructor:function Credentials(){// hide secretAccessKey from being displayed with util.inspect +AWS.util.hideProperties(this,['secretAccessKey']);this.expired=false;this.expireTime=null;this.refreshCallbacks=[];if(arguments.length===1&&_typeof(arguments[0])==='object'){var creds=arguments[0].credentials||arguments[0];this.accessKeyId=creds.accessKeyId;this.secretAccessKey=creds.secretAccessKey;this.sessionToken=creds.sessionToken;}else{this.accessKeyId=arguments[0];this.secretAccessKey=arguments[1];this.sessionToken=arguments[2];}},/** * @return [Integer] the number of seconds before {expireTime} during which * the credentials will be considered expired. - */expiryWindow: 15,/** + */expiryWindow:15,/** * @return [Boolean] whether the credentials object should call {refresh} * @note Subclasses should override this method to provide custom refresh * logic. - */needsRefresh: function needsRefresh() { var currentTime = AWS.util.date.getDate().getTime(); var adjustedTime = new Date(currentTime + this.expiryWindow * 1000); if (this.expireTime && adjustedTime > this.expireTime) { return true; } else { return this.expired || !this.accessKeyId || !this.secretAccessKey; } },/** + */needsRefresh:function needsRefresh(){var currentTime=AWS.util.date.getDate().getTime();var adjustedTime=new Date(currentTime+this.expiryWindow*1000);if(this.expireTime&&adjustedTime>this.expireTime){return true;}else{return this.expired||!this.accessKeyId||!this.secretAccessKey;}},/** * Gets the existing credentials, refreshing them if they are not yet loaded * or have expired. Users should call this method before using {refresh}, * as this will not attempt to reload credentials when they are already @@ -2678,14 +2619,8 @@ * been loaded into the object (as the `accessKeyId`, `secretAccessKey`, * and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled - */get: function get(callback) { - var self = this; if (this.needsRefresh()) { - this.refresh(function (err) { - if (!err) self.expired = false;// reset expired flag - if (callback) callback(err); - }); - } else if (callback) { callback(); } - },/** + */get:function get(callback){var self=this;if(this.needsRefresh()){this.refresh(function(err){if(!err)self.expired=false;// reset expired flag +if(callback)callback(err);});}else if(callback){callback();}},/** * @!method getPromise() * Returns a 'thenable' promise. * Gets the existing credentials, refreshing them if they are not yet loaded @@ -2742,30 +2677,18 @@ * on the credentials object and then call the callback with * any error information. * @see get - */refresh: function refresh(callback) { this.expired = false; callback(); },/** + */refresh:function refresh(callback){this.expired=false;callback();},/** * @api private * @param callback - */coalesceRefresh: function coalesceRefresh(callback, sync) { - var self = this; if (self.refreshCallbacks.push(callback) === 1) { - self.load(function onLoad(err) { - AWS.util.arrayEach(self.refreshCallbacks, function (callback) { - if (sync) { callback(err); } else {// callback could throw, so defer to ensure all callbacks are notified - AWS.util.defer(function () { callback(err); }); - } - }); self.refreshCallbacks.length = 0; - }); - } - },/** + */coalesceRefresh:function coalesceRefresh(callback,sync){var self=this;if(self.refreshCallbacks.push(callback)===1){self.load(function onLoad(err){AWS.util.arrayEach(self.refreshCallbacks,function(callback){if(sync){callback(err);}else{// callback could throw, so defer to ensure all callbacks are notified +AWS.util.defer(function(){callback(err);});}});self.refreshCallbacks.length=0;});}},/** * @api private * @param callback - */load: function load(callback) { callback(); } - });/** + */load:function load(callback){callback();}});/** * @api private - */AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) { this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency); this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency); };/** + */AWS.Credentials.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.getPromise=AWS.util.promisifyMethod('get',PromiseDependency);this.prototype.refreshPromise=AWS.util.promisifyMethod('refresh',PromiseDependency);};/** * @api private - */AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.getPromise; delete this.prototype.refreshPromise; }; AWS.util.addPromises(AWS.Credentials); - }, { "./core": 18 }], 20: [function (require, module, exports) { - var AWS = require('../core'); var STS = require('../../clients/sts');/** + */AWS.Credentials.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.getPromise;delete this.prototype.refreshPromise;};AWS.util.addPromises(AWS.Credentials);},{"./core":18}],20:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents temporary credentials retrieved from {AWS.STS}. Without any * extra parameters, credentials will be fetched from the * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the @@ -2832,7 +2755,7 @@ * @return [AWS.STS] the STS service instance used to * get and refresh temporary credentials from AWS STS. * @note (see constructor) - */AWS.ChainableTemporaryCredentials = AWS.util.inherit(AWS.Credentials, {/** + */AWS.ChainableTemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new temporary credentials object. * * @param options [map] a set of options @@ -2859,7 +2782,7 @@ * }); * @see AWS.STS.assumeRole * @see AWS.STS.getSessionToken - */constructor: function ChainableTemporaryCredentials(options) { AWS.Credentials.call(this); options = options || {}; this.errorCode = 'ChainableTemporaryCredentialsProviderFailure'; this.expired = true; this.tokenCodeFn = null; var params = AWS.util.copy(options.params) || {}; if (params.RoleArn) { params.RoleSessionName = params.RoleSessionName || 'temporary-credentials'; } if (params.SerialNumber) { if (!options.tokenCodeFn || typeof options.tokenCodeFn !== 'function') { throw new AWS.util.error(new Error('tokenCodeFn must be a function when params.SerialNumber is given'), { code: this.errorCode }); } else { this.tokenCodeFn = options.tokenCodeFn; } } var config = AWS.util.merge({ params: params, credentials: options.masterCredentials || AWS.config.credentials }, options.stsConfig || {}); this.service = new STS(config); },/** + */constructor:function ChainableTemporaryCredentials(options){AWS.Credentials.call(this);options=options||{};this.errorCode='ChainableTemporaryCredentialsProviderFailure';this.expired=true;this.tokenCodeFn=null;var params=AWS.util.copy(options.params)||{};if(params.RoleArn){params.RoleSessionName=params.RoleSessionName||'temporary-credentials';}if(params.SerialNumber){if(!options.tokenCodeFn||typeof options.tokenCodeFn!=='function'){throw new AWS.util.error(new Error('tokenCodeFn must be a function when params.SerialNumber is given'),{code:this.errorCode});}else{this.tokenCodeFn=options.tokenCodeFn;}}var config=AWS.util.merge({params:params,credentials:options.masterCredentials||AWS.config.credentials},options.stsConfig||{});this.service=new STS(config);},/** * Refreshes credentials using {AWS.STS.assumeRole} or * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed * to the credentials {constructor}. @@ -2871,15 +2794,12 @@ * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see AWS.Credentials.get - */refresh: function refresh(callback) { this.coalesceRefresh(callback || AWS.util.fn.callback); },/** + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private * @param callback - */load: function load(callback) { var self = this; var operation = self.service.config.params.RoleArn ? 'assumeRole' : 'getSessionToken'; this.getTokenCode(function (err, tokenCode) { var params = {}; if (err) { callback(err); return; } if (tokenCode) { params.TokenCode = tokenCode; } self.service[operation](params, function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }); },/** + */load:function load(callback){var self=this;var operation=self.service.config.params.RoleArn?'assumeRole':'getSessionToken';this.getTokenCode(function(err,tokenCode){var params={};if(err){callback(err);return;}if(tokenCode){params.TokenCode=tokenCode;}self.service[operation](params,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** * @api private - */getTokenCode: function getTokenCode(callback) { var self = this; if (this.tokenCodeFn) { this.tokenCodeFn(this.service.config.params.SerialNumber, function (err, token) { if (err) { var message = err; if (err instanceof Error) { message = err.message; } callback(AWS.util.error(new Error('Error fetching MFA token: ' + message), { code: self.errorCode })); return; } callback(null, token); }); } else { callback(null); } } - }); - }, { "../../clients/sts": 8, "../core": 18 }], 21: [function (require, module, exports) { - var AWS = require('../core'); var CognitoIdentity = require('../../clients/cognitoidentity'); var STS = require('../../clients/sts');/** + */getTokenCode:function getTokenCode(callback){var self=this;if(this.tokenCodeFn){this.tokenCodeFn(this.service.config.params.SerialNumber,function(err,token){if(err){var message=err;if(err instanceof Error){message=err.message;}callback(AWS.util.error(new Error('Error fetching MFA token: '+message),{code:self.errorCode}));return;}callback(null,token);});}else{callback(null);}}});},{"../../clients/sts":8,"../core":18}],21:[function(require,module,exports){var AWS=require('../core');var CognitoIdentity=require('../../clients/cognitoidentity');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS Web Identity Federation using * the Amazon Cognito Identity service. * @@ -2934,9 +2854,9 @@ * @return [String] the Cognito ID returned by the last call to * {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual * final resolved identity ID from Amazon Cognito. - */AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, {/** + */AWS.CognitoIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** * @api private - */localStorageKey: { id: 'aws.cognito.identity-id.', providers: 'aws.cognito.identity-providers.' },/** + */localStorageKey:{id:'aws.cognito.identity-id.',providers:'aws.cognito.identity-providers.'},/** * Creates a new credentials object. * @example Creating a new credentials object * AWS.config.credentials = new AWS.CognitoIdentityCredentials({ @@ -2992,7 +2912,7 @@ * specified in the `clientConfig` to the CognitoIdentityCredentials * constructor, you may encounter a 'Missing credentials in config' error * when calling making a service call. - */constructor: function CognitoIdentityCredentials(params, clientConfig) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.data = null; this._identityId = null; this._clientConfig = AWS.util.copy(clientConfig || {}); this.loadCachedId(); var self = this; Object.defineProperty(this, 'identityId', { get: function get() { self.loadCachedId(); return self._identityId || self.params.IdentityId; }, set: function set(identityId) { self._identityId = identityId; } }); },/** + */constructor:function CognitoIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.data=null;this._identityId=null;this._clientConfig=AWS.util.copy(clientConfig||{});this.loadCachedId();var self=this;Object.defineProperty(this,'identityId',{get:function get(){self.loadCachedId();return self._identityId||self.params.IdentityId;},set:function set(identityId){self._identityId=identityId;}});},/** * Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity}, * or {AWS.STS.assumeRoleWithWebIdentity}. * @@ -3003,16 +2923,16 @@ * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see AWS.Credentials.get - */refresh: function refresh(callback) { this.coalesceRefresh(callback || AWS.util.fn.callback); },/** + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private * @param callback - */load: function load(callback) { var self = this; self.createClients(); self.data = null; self._identityId = null; self.getId(function (err) { if (!err) { if (!self.params.RoleArn) { self.getCredentialsForIdentity(callback); } else { self.getCredentialsFromSTS(callback); } } else { self.clearIdOnNotAuthorized(err); callback(err); } }); },/** + */load:function load(callback){var self=this;self.createClients();self.data=null;self._identityId=null;self.getId(function(err){if(!err){if(!self.params.RoleArn){self.getCredentialsForIdentity(callback);}else{self.getCredentialsFromSTS(callback);}}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** * Clears the cached Cognito ID associated with the currently configured * identity pool ID. Use this to manually invalidate your cache if * the identity pool ID was deleted. - */clearCachedId: function clearCache() { this._identityId = null; delete this.params.IdentityId; var poolId = this.params.IdentityPoolId; var loginId = this.params.LoginId || ''; delete this.storage[this.localStorageKey.id + poolId + loginId]; delete this.storage[this.localStorageKey.providers + poolId + loginId]; },/** + */clearCachedId:function clearCache(){this._identityId=null;delete this.params.IdentityId;var poolId=this.params.IdentityPoolId;var loginId=this.params.LoginId||'';delete this.storage[this.localStorageKey.id+poolId+loginId];delete this.storage[this.localStorageKey.providers+poolId+loginId];},/** * @api private - */clearIdOnNotAuthorized: function clearIdOnNotAuthorized(err) { var self = this; if (err.code == 'NotAuthorizedException') { self.clearCachedId(); } },/** + */clearIdOnNotAuthorized:function clearIdOnNotAuthorized(err){var self=this;if(err.code=='NotAuthorizedException'){self.clearCachedId();}},/** * Retrieves a Cognito ID, loading from cache if it was already retrieved * on this device. * @@ -3024,44 +2944,29 @@ * @note If not loaded explicitly, the Cognito ID is loaded and stored in * localStorage in the browser environment of a device. * @api private - */getId: function getId(callback) { var self = this; if (typeof self.params.IdentityId === 'string') { return callback(null, self.params.IdentityId); } self.cognito.getId(function (err, data) { if (!err && data.IdentityId) { self.params.IdentityId = data.IdentityId; callback(null, data.IdentityId); } else { callback(err); } }); },/** + */getId:function getId(callback){var self=this;if(typeof self.params.IdentityId==='string'){return callback(null,self.params.IdentityId);}self.cognito.getId(function(err,data){if(!err&&data.IdentityId){self.params.IdentityId=data.IdentityId;callback(null,data.IdentityId);}else{callback(err);}});},/** * @api private - */loadCredentials: function loadCredentials(data, credentials) { if (!data || !credentials) return; credentials.expired = false; credentials.accessKeyId = data.Credentials.AccessKeyId; credentials.secretAccessKey = data.Credentials.SecretKey; credentials.sessionToken = data.Credentials.SessionToken; credentials.expireTime = data.Credentials.Expiration; },/** + */loadCredentials:function loadCredentials(data,credentials){if(!data||!credentials)return;credentials.expired=false;credentials.accessKeyId=data.Credentials.AccessKeyId;credentials.secretAccessKey=data.Credentials.SecretKey;credentials.sessionToken=data.Credentials.SessionToken;credentials.expireTime=data.Credentials.Expiration;},/** * @api private - */getCredentialsForIdentity: function getCredentialsForIdentity(callback) { var self = this; self.cognito.getCredentialsForIdentity(function (err, data) { if (!err) { self.cacheId(data); self.data = data; self.loadCredentials(self.data, self); } else { self.clearIdOnNotAuthorized(err); } callback(err); }); },/** + */getCredentialsForIdentity:function getCredentialsForIdentity(callback){var self=this;self.cognito.getCredentialsForIdentity(function(err,data){if(!err){self.cacheId(data);self.data=data;self.loadCredentials(self.data,self);}else{self.clearIdOnNotAuthorized(err);}callback(err);});},/** * @api private - */getCredentialsFromSTS: function getCredentialsFromSTS(callback) { var self = this; self.cognito.getOpenIdToken(function (err, data) { if (!err) { self.cacheId(data); self.params.WebIdentityToken = data.Token; self.webIdentityCredentials.refresh(function (webErr) { if (!webErr) { self.data = self.webIdentityCredentials.data; self.sts.credentialsFrom(self.data, self); } callback(webErr); }); } else { self.clearIdOnNotAuthorized(err); callback(err); } }); },/** + */getCredentialsFromSTS:function getCredentialsFromSTS(callback){var self=this;self.cognito.getOpenIdToken(function(err,data){if(!err){self.cacheId(data);self.params.WebIdentityToken=data.Token;self.webIdentityCredentials.refresh(function(webErr){if(!webErr){self.data=self.webIdentityCredentials.data;self.sts.credentialsFrom(self.data,self);}callback(webErr);});}else{self.clearIdOnNotAuthorized(err);callback(err);}});},/** * @api private - */loadCachedId: function loadCachedId() { - var self = this;// in the browser we source default IdentityId from localStorage - if (AWS.util.isBrowser() && !self.params.IdentityId) { - var id = self.getStorage('id'); if (id && self.params.Logins) { - var actualProviders = Object.keys(self.params.Logins); var cachedProviders = (self.getStorage('providers') || '').split(',');// only load ID if at least one provider used this ID before - var intersect = cachedProviders.filter(function (n) { return actualProviders.indexOf(n) !== -1; }); if (intersect.length !== 0) { self.params.IdentityId = id; } - } else if (id) { self.params.IdentityId = id; } - } - },/** + */loadCachedId:function loadCachedId(){var self=this;// in the browser we source default IdentityId from localStorage +if(AWS.util.isBrowser()&&!self.params.IdentityId){var id=self.getStorage('id');if(id&&self.params.Logins){var actualProviders=Object.keys(self.params.Logins);var cachedProviders=(self.getStorage('providers')||'').split(',');// only load ID if at least one provider used this ID before +var intersect=cachedProviders.filter(function(n){return actualProviders.indexOf(n)!==-1;});if(intersect.length!==0){self.params.IdentityId=id;}}else if(id){self.params.IdentityId=id;}}},/** * @api private - */createClients: function createClients() { var clientConfig = this._clientConfig; this.webIdentityCredentials = this.webIdentityCredentials || new AWS.WebIdentityCredentials(this.params, clientConfig); if (!this.cognito) { var cognitoConfig = AWS.util.merge({}, clientConfig); cognitoConfig.params = this.params; this.cognito = new CognitoIdentity(cognitoConfig); } this.sts = this.sts || new STS(clientConfig); },/** + */createClients:function createClients(){var clientConfig=this._clientConfig;this.webIdentityCredentials=this.webIdentityCredentials||new AWS.WebIdentityCredentials(this.params,clientConfig);if(!this.cognito){var cognitoConfig=AWS.util.merge({},clientConfig);cognitoConfig.params=this.params;this.cognito=new CognitoIdentity(cognitoConfig);}this.sts=this.sts||new STS(clientConfig);},/** * @api private - */cacheId: function cacheId(data) { - this._identityId = data.IdentityId; this.params.IdentityId = this._identityId;// cache this IdentityId in browser localStorage if possible - if (AWS.util.isBrowser()) { this.setStorage('id', data.IdentityId); if (this.params.Logins) { this.setStorage('providers', Object.keys(this.params.Logins).join(',')); } } - },/** + */cacheId:function cacheId(data){this._identityId=data.IdentityId;this.params.IdentityId=this._identityId;// cache this IdentityId in browser localStorage if possible +if(AWS.util.isBrowser()){this.setStorage('id',data.IdentityId);if(this.params.Logins){this.setStorage('providers',Object.keys(this.params.Logins).join(','));}}},/** * @api private - */getStorage: function getStorage(key) { return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')]; },/** + */getStorage:function getStorage(key){return this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')];},/** * @api private - */setStorage: function setStorage(key, val) { try { this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val; } catch (_) { } },/** + */setStorage:function setStorage(key,val){try{this.storage[this.localStorageKey[key]+this.params.IdentityPoolId+(this.params.LoginId||'')]=val;}catch(_){}},/** * @api private - */storage: function () { - try { - var storage = AWS.util.isBrowser() && window.localStorage !== null && _typeof(window.localStorage) === 'object' ? window.localStorage : {};// Test set/remove which would throw an error in Safari's private browsing - storage['aws.test-storage'] = 'foobar'; delete storage['aws.test-storage']; return storage; - } catch (_) { return {}; } - }() - }); - }, { "../../clients/cognitoidentity": 7, "../../clients/sts": 8, "../core": 18 }], 22: [function (require, module, exports) { - var AWS = require('../core');/** + */storage:function(){try{var storage=AWS.util.isBrowser()&&window.localStorage!==null&&_typeof(window.localStorage)==='object'?window.localStorage:{};// Test set/remove which would throw an error in Safari's private browsing +storage['aws.test-storage']='foobar';delete storage['aws.test-storage'];return storage;}catch(_){return{};}}()});},{"../../clients/cognitoidentity":7,"../../clients/sts":8,"../core":18}],22:[function(require,module,exports){var AWS=require('../core');/** * Creates a credential provider chain that searches for AWS credentials * in a list of credential providers specified by the {providers} property. * @@ -3102,10 +3007,10 @@ * credentials. By default, this object will be set to the * {defaultProviders}. * @see defaultProviders - */AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {/** + */AWS.CredentialProviderChain=AWS.util.inherit(AWS.Credentials,{/** * Creates a new CredentialProviderChain with a default set of providers * specified by {defaultProviders}. - */constructor: function CredentialProviderChain(providers) { if (providers) { this.providers = providers; } else { this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0); } this.resolveCallbacks = []; },/** + */constructor:function CredentialProviderChain(providers){if(providers){this.providers=providers;}else{this.providers=AWS.CredentialProviderChain.defaultProviders.slice(0);}this.resolveCallbacks=[];},/** * @!method resolvePromise() * Returns a 'thenable' promise. * Resolves the provider chain by searching for the first set of @@ -3139,8 +3044,7 @@ * @param credentials [AWS.Credentials] the credentials object resolved * by the provider chain. * @return [AWS.CredentialProviderChain] the provider, for chaining. - */resolve: function resolve(callback) { var self = this; if (self.providers.length === 0) { callback(new Error('No providers')); return self; } if (self.resolveCallbacks.push(callback) === 1) { var resolveNext = function resolveNext(err, creds) { if (!err && creds || index === providers.length) { AWS.util.arrayEach(self.resolveCallbacks, function (callback) { callback(err, creds); }); self.resolveCallbacks.length = 0; return; } var provider = providers[index++]; if (typeof provider === 'function') { creds = provider.call(); } else { creds = provider; } if (creds.get) { creds.get(function (getErr) { resolveNext(getErr, getErr ? null : creds); }); } else { resolveNext(null, creds); } }; var index = 0; var providers = self.providers.slice(0); resolveNext(); } return self; } - });/** + */resolve:function resolve(callback){var self=this;if(self.providers.length===0){callback(new Error('No providers'));return self;}if(self.resolveCallbacks.push(callback)===1){var resolveNext=function resolveNext(err,creds){if(!err&&creds||index===providers.length){AWS.util.arrayEach(self.resolveCallbacks,function(callback){callback(err,creds);});self.resolveCallbacks.length=0;return;}var provider=providers[index++];if(typeof provider==='function'){creds=provider.call();}else{creds=provider;}if(creds.get){creds.get(function(getErr){resolveNext(getErr,getErr?null:creds);});}else{resolveNext(null,creds);}};var index=0;var providers=self.providers.slice(0);resolveNext();}return self;}});/** * The default set of providers used by a vanilla CredentialProviderChain. * * In the browser: @@ -3162,13 +3066,11 @@ * function () { return new AWS.EC2MetadataCredentials() } * ] * ``` - */AWS.CredentialProviderChain.defaultProviders = [];/** + */AWS.CredentialProviderChain.defaultProviders=[];/** * @api private - */AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) { this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency); };/** + */AWS.CredentialProviderChain.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.resolvePromise=AWS.util.promisifyMethod('resolve',PromiseDependency);};/** * @api private - */AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.resolvePromise; }; AWS.util.addPromises(AWS.CredentialProviderChain); - }, { "../core": 18 }], 23: [function (require, module, exports) { - var AWS = require('../core'); var STS = require('../../clients/sts');/** + */AWS.CredentialProviderChain.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.resolvePromise;};AWS.util.addPromises(AWS.CredentialProviderChain);},{"../core":18}],23:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS SAML support. * * By default this provider gets credentials using the @@ -3203,7 +3105,7 @@ * @return [map] the map of params passed to * {AWS.STS.assumeRoleWithSAML}. To update the token, set the * `params.SAMLAssertion` property. - */AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, {/** + */AWS.SAMLCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithSAML) * @example Creating a new credentials object @@ -3213,7 +3115,7 @@ * SAMLAssertion: 'base64-token', // base64-encoded token from IdP * }); * @see AWS.STS.assumeRoleWithSAML - */constructor: function SAMLCredentials(params) { AWS.Credentials.call(this); this.expired = true; this.params = params; },/** + */constructor:function SAMLCredentials(params){AWS.Credentials.call(this);this.expired=true;this.params=params;},/** * Refreshes credentials using {AWS.STS.assumeRoleWithSAML} * * @callback callback function(err) @@ -3223,14 +3125,11 @@ * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get - */refresh: function refresh(callback) { this.coalesceRefresh(callback || AWS.util.fn.callback); },/** + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private - */load: function load(callback) { var self = this; self.createClients(); self.service.assumeRoleWithSAML(function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); },/** + */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithSAML(function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});},/** * @api private - */createClients: function createClients() { this.service = this.service || new STS({ params: this.params }); } - }); - }, { "../../clients/sts": 8, "../core": 18 }], 24: [function (require, module, exports) { - var AWS = require('../core'); var STS = require('../../clients/sts');/** + */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":18}],24:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents temporary credentials retrieved from {AWS.STS}. Without any * extra parameters, credentials will be fetched from the * {AWS.STS.getSessionToken} operation. If an IAM role is provided, the @@ -3262,7 +3161,7 @@ * @return [AWS.Credentials] the master (non-temporary) credentials used to * get and refresh temporary credentials from AWS STS. * @note (see constructor) - */AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, {/** + */AWS.TemporaryCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new temporary credentials object. * * @note In order to create temporary credentials, you first need to have @@ -3283,7 +3182,7 @@ * }); * @see AWS.STS.assumeRole * @see AWS.STS.getSessionToken - */constructor: function TemporaryCredentials(params, masterCredentials) { AWS.Credentials.call(this); this.loadMasterCredentials(masterCredentials); this.expired = true; this.params = params || {}; if (this.params.RoleArn) { this.params.RoleSessionName = this.params.RoleSessionName || 'temporary-credentials'; } },/** + */constructor:function TemporaryCredentials(params,masterCredentials){AWS.Credentials.call(this);this.loadMasterCredentials(masterCredentials);this.expired=true;this.params=params||{};if(this.params.RoleArn){this.params.RoleSessionName=this.params.RoleSessionName||'temporary-credentials';}},/** * Refreshes credentials using {AWS.STS.assumeRole} or * {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed * to the credentials {constructor}. @@ -3295,16 +3194,13 @@ * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get - */refresh: function refresh(callback) { this.coalesceRefresh(callback || AWS.util.fn.callback); },/** + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private - */load: function load(callback) { var self = this; self.createClients(); self.masterCredentials.get(function () { self.service.config.credentials = self.masterCredentials; var operation = self.params.RoleArn ? self.service.assumeRole : self.service.getSessionToken; operation.call(self.service, function (err, data) { if (!err) { self.service.credentialsFrom(data, self); } callback(err); }); }); },/** + */load:function load(callback){var self=this;self.createClients();self.masterCredentials.get(function(){self.service.config.credentials=self.masterCredentials;var operation=self.params.RoleArn?self.service.assumeRole:self.service.getSessionToken;operation.call(self.service,function(err,data){if(!err){self.service.credentialsFrom(data,self);}callback(err);});});},/** * @api private - */loadMasterCredentials: function loadMasterCredentials(masterCredentials) { this.masterCredentials = masterCredentials || AWS.config.credentials; while (this.masterCredentials.masterCredentials) { this.masterCredentials = this.masterCredentials.masterCredentials; } if (typeof this.masterCredentials.get !== 'function') { this.masterCredentials = new AWS.Credentials(this.masterCredentials); } },/** + */loadMasterCredentials:function loadMasterCredentials(masterCredentials){this.masterCredentials=masterCredentials||AWS.config.credentials;while(this.masterCredentials.masterCredentials){this.masterCredentials=this.masterCredentials.masterCredentials;}if(typeof this.masterCredentials.get!=='function'){this.masterCredentials=new AWS.Credentials(this.masterCredentials);}},/** * @api private - */createClients: function createClients() { this.service = this.service || new STS({ params: this.params }); } - }); - }, { "../../clients/sts": 8, "../core": 18 }], 25: [function (require, module, exports) { - var AWS = require('../core'); var STS = require('../../clients/sts');/** + */createClients:function createClients(){this.service=this.service||new STS({params:this.params});}});},{"../../clients/sts":8,"../core":18}],25:[function(require,module,exports){var AWS=require('../core');var STS=require('../../clients/sts');/** * Represents credentials retrieved from STS Web Identity Federation support. * * By default this provider gets credentials using the @@ -3342,7 +3238,7 @@ * @return [map] the raw data response from the call to * {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get * access to other properties from the response. - */AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, {/** + */AWS.WebIdentityCredentials=AWS.util.inherit(AWS.Credentials,{/** * Creates a new credentials object. * @param (see AWS.STS.assumeRoleWithWebIdentity) * @example Creating a new credentials object @@ -3361,7 +3257,7 @@ * }); * @see AWS.STS.assumeRoleWithWebIdentity * @see AWS.Config - */constructor: function WebIdentityCredentials(params, clientConfig) { AWS.Credentials.call(this); this.expired = true; this.params = params; this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity'; this.data = null; this._clientConfig = AWS.util.copy(clientConfig || {}); },/** + */constructor:function WebIdentityCredentials(params,clientConfig){AWS.Credentials.call(this);this.expired=true;this.params=params;this.params.RoleSessionName=this.params.RoleSessionName||'web-identity';this.data=null;this._clientConfig=AWS.util.copy(clientConfig||{});},/** * Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity} * * @callback callback function(err) @@ -3371,16 +3267,11 @@ * `secretAccessKey`, and `sessionToken` properties). * @param err [Error] if an error occurred, this value will be filled * @see get - */refresh: function refresh(callback) { this.coalesceRefresh(callback || AWS.util.fn.callback); },/** + */refresh:function refresh(callback){this.coalesceRefresh(callback||AWS.util.fn.callback);},/** * @api private - */load: function load(callback) { var self = this; self.createClients(); self.service.assumeRoleWithWebIdentity(function (err, data) { self.data = null; if (!err) { self.data = data; self.service.credentialsFrom(data, self); } callback(err); }); },/** + */load:function load(callback){var self=this;self.createClients();self.service.assumeRoleWithWebIdentity(function(err,data){self.data=null;if(!err){self.data=data;self.service.credentialsFrom(data,self);}callback(err);});},/** * @api private - */createClients: function createClients() { if (!this.service) { var stsConfig = AWS.util.merge({}, this._clientConfig); stsConfig.params = this.params; this.service = new STS(stsConfig); } } - }); - }, { "../../clients/sts": 8, "../core": 18 }], 26: [function (require, module, exports) { - (function (process) { - (function () { - var AWS = require('./core'); var util = require('./util'); var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];/** + */createClients:function createClients(){if(!this.service){var stsConfig=AWS.util.merge({},this._clientConfig);stsConfig.params=this.params;this.service=new STS(stsConfig);}}});},{"../../clients/sts":8,"../core":18}],26:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var util=require('./util');var endpointDiscoveryEnabledEnvs=['AWS_ENABLE_ENDPOINT_DISCOVERY','AWS_ENDPOINT_DISCOVERY_ENABLED'];/** * Generate key (except resources and operation part) to index the endpoints in the cache * If input shape has endpointdiscoveryid trait then use * accessKey + operation + resources + region + service as cache key @@ -3388,41 +3279,31 @@ * accessKey + region + service as cache key * @return [map] object with keys to index endpoints. * @api private - */function getCacheKey(request) { var service = request.service; var api = service.api || {}; var operations = api.operations; var identifiers = {}; if (service.config.region) { identifiers.region = service.config.region; } if (api.serviceId) { identifiers.serviceId = api.serviceId; } if (service.config.credentials.accessKeyId) { identifiers.accessKeyId = service.config.credentials.accessKeyId; } return identifiers; }/** + */function getCacheKey(request){var service=request.service;var api=service.api||{};var operations=api.operations;var identifiers={};if(service.config.region){identifiers.region=service.config.region;}if(api.serviceId){identifiers.serviceId=api.serviceId;}if(service.config.credentials.accessKeyId){identifiers.accessKeyId=service.config.credentials.accessKeyId;}return identifiers;}/** * Recursive helper for marshallCustomIdentifiers(). * Looks for required string input members that have 'endpointdiscoveryid' trait. * @api private - */function marshallCustomIdentifiersHelper(result, params, shape) { if (!shape || params === undefined || params === null) return; if (shape.type === 'structure' && shape.required && shape.required.length > 0) { util.arrayEach(shape.required, function (name) { var memberShape = shape.members[name]; if (memberShape.endpointDiscoveryId === true) { var locationName = memberShape.isLocationName ? memberShape.name : name; result[locationName] = String(params[name]); } else { marshallCustomIdentifiersHelper(result, params[name], memberShape); } }); } }/** + */function marshallCustomIdentifiersHelper(result,params,shape){if(!shape||params===undefined||params===null)return;if(shape.type==='structure'&&shape.required&&shape.required.length>0){util.arrayEach(shape.required,function(name){var memberShape=shape.members[name];if(memberShape.endpointDiscoveryId===true){var locationName=memberShape.isLocationName?memberShape.name:name;result[locationName]=String(params[name]);}else{marshallCustomIdentifiersHelper(result,params[name],memberShape);}});}}/** * Get custom identifiers for cache key. * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait. * @param [object] request object * @param [object] input shape of the given operation's api * @api private - */function marshallCustomIdentifiers(request, shape) { var identifiers = {}; marshallCustomIdentifiersHelper(identifiers, request.params, shape); return identifiers; }/** + */function marshallCustomIdentifiers(request,shape){var identifiers={};marshallCustomIdentifiersHelper(identifiers,request.params,shape);return identifiers;}/** * Call endpoint discovery operation when it's optional. * When endpoint is available in cache then use the cached endpoints. If endpoints * are unavailable then use regional endpoints and call endpoint discovery operation * asynchronously. This is turned off by default. * @param [object] request object * @api private - */function optionalDiscoverEndpoint(request) { - var service = request.service; var api = service.api; var operationModel = api.operations ? api.operations[request.operation] : undefined; var inputShape = operationModel ? operationModel.input : undefined; var identifiers = marshallCustomIdentifiers(request, inputShape); var cacheKey = getCacheKey(request); if (Object.keys(identifiers).length > 0) { cacheKey = util.update(cacheKey, identifiers); if (operationModel) cacheKey.operation = operationModel.name; } var endpoints = AWS.endpointCache.get(cacheKey); if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {//endpoint operation is being made but response not yet received - //or endpoint operation just failed in 1 minute - return; - } else if (endpoints && endpoints.length > 0) {//found endpoint record from cache - request.httpRequest.updateEndpoint(endpoints[0].Address); - } else {//endpoint record not in cache or outdated. make discovery operation - var endpointRequest = service.makeRequest(api.endpointOperation, { Operation: operationModel.name, Identifiers: identifiers }); addApiVersionHeader(endpointRequest); endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);//put in a placeholder for endpoints already requested, prevent - //too much in-flight calls - AWS.endpointCache.put(cacheKey, [{ Address: '', CachePeriodInMinutes: 1 }]); endpointRequest.send(function (err, data) { - if (data && data.Endpoints) { AWS.endpointCache.put(cacheKey, data.Endpoints); } else if (err) { - AWS.endpointCache.put(cacheKey, [{ - Address: '', CachePeriodInMinutes: 1//not to make more endpoint operation in next 1 minute - }]); - } - }); - } - } var requestQueue = {};/** + */function optionalDiscoverEndpoint(request){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var endpoints=AWS.endpointCache.get(cacheKey);if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received +//or endpoint operation just failed in 1 minute +return;}else if(endpoints&&endpoints.length>0){//found endpoint record from cache +request.httpRequest.updateEndpoint(endpoints[0].Address);}else{//endpoint record not in cache or outdated. make discovery operation +var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});addApiVersionHeader(endpointRequest);endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);endpointRequest.removeListener('retry',AWS.EventListeners.Core.RETRY_CHECK);//put in a placeholder for endpoints already requested, prevent +//too much in-flight calls +AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1}]);endpointRequest.send(function(err,data){if(data&&data.Endpoints){AWS.endpointCache.put(cacheKey,data.Endpoints);}else if(err){AWS.endpointCache.put(cacheKey,[{Address:'',CachePeriodInMinutes:1//not to make more endpoint operation in next 1 minute +}]);}});}}var requestQueue={};/** * Call endpoint discovery operation when it's required. * When endpoint is available in cache then use cached ones. If endpoints are * unavailable then SDK should call endpoint operation then use returned new @@ -3430,42 +3311,29 @@ * discovery. This is turned off by default * @param [object] request object * @api private - */function requiredDiscoverEndpoint(request, done) { - var service = request.service; var api = service.api; var operationModel = api.operations ? api.operations[request.operation] : undefined; var inputShape = operationModel ? operationModel.input : undefined; var identifiers = marshallCustomIdentifiers(request, inputShape); var cacheKey = getCacheKey(request); if (Object.keys(identifiers).length > 0) { cacheKey = util.update(cacheKey, identifiers); if (operationModel) cacheKey.operation = operationModel.name; } var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey); var endpoints = AWS.endpointCache.get(cacheKeyStr);//endpoint cache also accepts string keys - if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {//endpoint operation is being made but response not yet received - //push request object to a pending queue - if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = []; requestQueue[cacheKeyStr].push({ request: request, callback: done }); return; - } else if (endpoints && endpoints.length > 0) { request.httpRequest.updateEndpoint(endpoints[0].Address); done(); } else { - var endpointRequest = service.makeRequest(api.endpointOperation, { Operation: operationModel.name, Identifiers: identifiers }); endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); addApiVersionHeader(endpointRequest);//put in a placeholder for endpoints already requested, prevent - //too much in-flight calls - AWS.endpointCache.put(cacheKeyStr, [{ - Address: '', CachePeriodInMinutes: 60//long-live cache - }]); endpointRequest.send(function (err, data) { - if (err) { - var errorParams = { code: 'EndpointDiscoveryException', message: 'Request cannot be fulfilled without specifying an endpoint', retryable: false }; request.response.error = util.error(err, errorParams); AWS.endpointCache.remove(cacheKey);//fail all the pending requests in batch - if (requestQueue[cacheKeyStr]) { var pendingRequests = requestQueue[cacheKeyStr]; util.arrayEach(pendingRequests, function (requestContext) { requestContext.request.response.error = util.error(err, errorParams); requestContext.callback(); }); delete requestQueue[cacheKeyStr]; } - } else if (data) { - AWS.endpointCache.put(cacheKeyStr, data.Endpoints); request.httpRequest.updateEndpoint(data.Endpoints[0].Address);//update the endpoint for all the pending requests in batch - if (requestQueue[cacheKeyStr]) { var pendingRequests = requestQueue[cacheKeyStr]; util.arrayEach(pendingRequests, function (requestContext) { requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address); requestContext.callback(); }); delete requestQueue[cacheKeyStr]; } - } done(); - }); - } - }/** + */function requiredDiscoverEndpoint(request,done){var service=request.service;var api=service.api;var operationModel=api.operations?api.operations[request.operation]:undefined;var inputShape=operationModel?operationModel.input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operationModel)cacheKey.operation=operationModel.name;}var cacheKeyStr=AWS.EndpointCache.getKeyString(cacheKey);var endpoints=AWS.endpointCache.get(cacheKeyStr);//endpoint cache also accepts string keys +if(endpoints&&endpoints.length===1&&endpoints[0].Address===''){//endpoint operation is being made but response not yet received +//push request object to a pending queue +if(!requestQueue[cacheKeyStr])requestQueue[cacheKeyStr]=[];requestQueue[cacheKeyStr].push({request:request,callback:done});return;}else if(endpoints&&endpoints.length>0){request.httpRequest.updateEndpoint(endpoints[0].Address);done();}else{var endpointRequest=service.makeRequest(api.endpointOperation,{Operation:operationModel.name,Identifiers:identifiers});endpointRequest.removeListener('validate',AWS.EventListeners.Core.VALIDATE_PARAMETERS);addApiVersionHeader(endpointRequest);//put in a placeholder for endpoints already requested, prevent +//too much in-flight calls +AWS.endpointCache.put(cacheKeyStr,[{Address:'',CachePeriodInMinutes:60//long-live cache +}]);endpointRequest.send(function(err,data){if(err){var errorParams={code:'EndpointDiscoveryException',message:'Request cannot be fulfilled without specifying an endpoint',retryable:false};request.response.error=util.error(err,errorParams);AWS.endpointCache.remove(cacheKey);//fail all the pending requests in batch +if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.response.error=util.error(err,errorParams);requestContext.callback();});delete requestQueue[cacheKeyStr];}}else if(data){AWS.endpointCache.put(cacheKeyStr,data.Endpoints);request.httpRequest.updateEndpoint(data.Endpoints[0].Address);//update the endpoint for all the pending requests in batch +if(requestQueue[cacheKeyStr]){var pendingRequests=requestQueue[cacheKeyStr];util.arrayEach(pendingRequests,function(requestContext){requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);requestContext.callback();});delete requestQueue[cacheKeyStr];}}done();});}}/** * add api version header to endpoint operation * @api private - */function addApiVersionHeader(endpointRequest) { var api = endpointRequest.service.api; var apiVersion = api.apiVersion; if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) { endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion; } }/** + */function addApiVersionHeader(endpointRequest){var api=endpointRequest.service.api;var apiVersion=api.apiVersion;if(apiVersion&&!endpointRequest.httpRequest.headers['x-amz-api-version']){endpointRequest.httpRequest.headers['x-amz-api-version']=apiVersion;}}/** * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid * endpoint from cache. * @api private - */function invalidateCachedEndpoints(response) { var error = response.error; var httpResponse = response.httpResponse; if (error && (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)) { var request = response.request; var operations = request.service.api.operations || {}; var inputShape = operations[request.operation] ? operations[request.operation].input : undefined; var identifiers = marshallCustomIdentifiers(request, inputShape); var cacheKey = getCacheKey(request); if (Object.keys(identifiers).length > 0) { cacheKey = util.update(cacheKey, identifiers); if (operations[request.operation]) cacheKey.operation = operations[request.operation].name; } AWS.endpointCache.remove(cacheKey); } }/** + */function invalidateCachedEndpoints(response){var error=response.error;var httpResponse=response.httpResponse;if(error&&(error.code==='InvalidEndpointException'||httpResponse.statusCode===421)){var request=response.request;var operations=request.service.api.operations||{};var inputShape=operations[request.operation]?operations[request.operation].input:undefined;var identifiers=marshallCustomIdentifiers(request,inputShape);var cacheKey=getCacheKey(request);if(Object.keys(identifiers).length>0){cacheKey=util.update(cacheKey,identifiers);if(operations[request.operation])cacheKey.operation=operations[request.operation].name;}AWS.endpointCache.remove(cacheKey);}}/** * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime. * @param [object] client Service client object. * @api private - */function hasCustomEndpoint(client) {//if set endpoint is set for specific client, enable endpoint discovery will raise an error. - if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) { throw util.error(new Error(), { code: 'ConfigurationException', message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.' }); }; var svcConfig = AWS.config[client.serviceIdentifier] || {}; return Boolean(AWS.config.endpoint || svcConfig.endpoint || client._originalConfig && client._originalConfig.endpoint); - }/** + */function hasCustomEndpoint(client){//if set endpoint is set for specific client, enable endpoint discovery will raise an error. +if(client._originalConfig&&client._originalConfig.endpoint&&client._originalConfig.endpointDiscoveryEnabled===true){throw util.error(new Error(),{code:'ConfigurationException',message:'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'});};var svcConfig=AWS.config[client.serviceIdentifier]||{};return Boolean(AWS.config.endpoint||svcConfig.endpoint||client._originalConfig&&client._originalConfig.endpoint);}/** * @api private - */function isFalsy(value) { return ['false', '0'].indexOf(value) >= 0; }/** + */function isFalsy(value){return['false','0'].indexOf(value)>=0;}/** * If endpoint discovery should perform for this request when endpoint discovery is optional. * SDK performs config resolution in order like below: * 1. If turned on client configuration(default to off) then turn on endpoint discovery. @@ -3474,35 +3342,23 @@ * turn on endpoint discovery. * @param [object] request request object. * @api private - */function isEndpointDiscoveryApplicable(request) { - var service = request.service || {}; if (service.config.endpointDiscoveryEnabled === true) return true;//shared ini file is only available in Node - //not to check env in browser - if (util.isBrowser()) return false; for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) { var env = endpointDiscoveryEnabledEnvs[i]; if (Object.prototype.hasOwnProperty.call(process.env, env)) { if (process.env[env] === '' || process.env[env] === undefined) { throw util.error(new Error(), { code: 'ConfigurationException', message: 'environmental variable ' + env + ' cannot be set to nothing' }); } if (!isFalsy(process.env[env])) return true; } } var configFile = {}; try { configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({ isConfig: true, filename: process.env[AWS.util.sharedConfigFileEnv] }) : {}; } catch (e) { } var sharedFileConfig = configFile[process.env.AWS_PROFILE || AWS.util.defaultProfile] || {}; if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) { if (sharedFileConfig.endpoint_discovery_enabled === undefined) { throw util.error(new Error(), { code: 'ConfigurationException', message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing' }); } if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true; } return false; - }/** + */function isEndpointDiscoveryApplicable(request){var service=request.service||{};if(service.config.endpointDiscoveryEnabled===true)return true;//shared ini file is only available in Node +//not to check env in browser +if(util.isBrowser())return false;for(var i=0;i 9223372036854775807 || number < -9223372036854775808) { throw new Error(number + ' is too large (or, if negative, too small) to represent as an Int64'); } var bytes = new Uint8Array(8); for (var i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { bytes[i] = remaining; } if (number < 0) { negate(bytes); } return new Int64(bytes); };/** + */Int64.fromNumber=function(number){if(number>9223372036854775807||number<-9223372036854775808){throw new Error(number+' is too large (or, if negative, too small) to represent as an Int64');}var bytes=new Uint8Array(8);for(var i=7,remaining=Math.abs(Math.round(number));i>-1&&remaining>0;i--,remaining/=256){bytes[i]=remaining;}if(number<0){negate(bytes);}return new Int64(bytes);};/** * @returns {number} * * @api private - */Int64.prototype.valueOf = function () { var bytes = this.bytes.slice(0); var negative = bytes[0] & 128; if (negative) { negate(bytes); } return parseInt(bytes.toString('hex'), 16) * (negative ? -1 : 1); }; Int64.prototype.toString = function () { return String(this.valueOf()); };/** + */Int64.prototype.valueOf=function(){var bytes=this.bytes.slice(0);var negative=bytes[0]&128;if(negative){negate(bytes);}return parseInt(bytes.toString('hex'),16)*(negative?-1:1);};Int64.prototype.toString=function(){return String(this.valueOf());};/** * @param {Buffer} bytes * * @api private - */function negate(bytes) { for (var i = 0; i < 8; i++) { bytes[i] ^= 0xFF; } for (var i = 7; i > -1; i--) { bytes[i]++; if (bytes[i] !== 0) { break; } } }/** + */function negate(bytes){for(var i=0;i<8;i++){bytes[i]^=0xFF;}for(var i=7;i>-1;i--){bytes[i]++;if(bytes[i]!==0){break;}}}/** * @api private - */module.exports = { Int64: Int64 }; - }, { "../core": 18 }], 30: [function (require, module, exports) { - var parseMessage = require('./parse-message').parseMessage;/** + */module.exports={Int64:Int64};},{"../core":18}],30:[function(require,module,exports){var parseMessage=require('./parse-message').parseMessage;/** * * @param {*} parser * @param {Buffer} message * @param {*} shape * @api private - */function parseEvent(parser, message, shape) { - var parsedMessage = parseMessage(message);// check if message is an event or error - var messageType = parsedMessage.headers[':message-type']; if (messageType) { - if (messageType.value === 'error') { throw parseError(parsedMessage); } else if (messageType.value !== 'event') {// not sure how to parse non-events/non-errors, ignore for now - return; - } - }// determine event type - var eventType = parsedMessage.headers[':event-type'];// check that the event type is modeled - var eventModel = shape.members[eventType.value]; if (!eventModel) { return; } var result = {};// check if an event payload exists - var eventPayloadMemberName = eventModel.eventPayloadMemberName; if (eventPayloadMemberName) { - var payloadShape = eventModel.members[eventPayloadMemberName];// if the shape is binary, return the byte array - if (payloadShape.type === 'binary') { result[eventPayloadMemberName] = parsedMessage.body; } else { result[eventPayloadMemberName] = parser.parse(parsedMessage.body.toString(), payloadShape); } - }// read event headers - var eventHeaderNames = eventModel.eventHeaderMemberNames; for (var i = 0; i < eventHeaderNames.length; i++) { - var name = eventHeaderNames[i]; if (parsedMessage.headers[name]) {// parse the header! - result[name] = eventModel.members[name].toType(parsedMessage.headers[name].value); - } - } var output = {}; output[eventType.value] = result; return output; - } function parseError(message) { var errorCode = message.headers[':error-code']; var errorMessage = message.headers[':error-message']; var error = new Error(errorMessage.value || errorMessage); error.code = error.name = errorCode.value || errorCode; return error; }/** + */function parseEvent(parser,message,shape){var parsedMessage=parseMessage(message);// check if message is an event or error +var messageType=parsedMessage.headers[':message-type'];if(messageType){if(messageType.value==='error'){throw parseError(parsedMessage);}else if(messageType.value!=='event'){// not sure how to parse non-events/non-errors, ignore for now +return;}}// determine event type +var eventType=parsedMessage.headers[':event-type'];// check that the event type is modeled +var eventModel=shape.members[eventType.value];if(!eventModel){return;}var result={};// check if an event payload exists +var eventPayloadMemberName=eventModel.eventPayloadMemberName;if(eventPayloadMemberName){var payloadShape=eventModel.members[eventPayloadMemberName];// if the shape is binary, return the byte array +if(payloadShape.type==='binary'){result[eventPayloadMemberName]=parsedMessage.body;}else{result[eventPayloadMemberName]=parser.parse(parsedMessage.body.toString(),payloadShape);}}// read event headers +var eventHeaderNames=eventModel.eventHeaderMemberNames;for(var i=0;i= 0) { req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD'; return done(); } AWS.util.computeSha256(body, function (err, sha) { if (err) { done(err); } else { req.httpRequest.headers['X-Amz-Content-Sha256'] = sha; done(); } }); } else { done(); } - }); add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) { - var authtype = getOperationAuthtype(req); var payloadMember = AWS.util.getRequestPayloadShape(req); if (req.httpRequest.headers['Content-Length'] === undefined) { - try { var length = AWS.util.string.byteLength(req.httpRequest.body); req.httpRequest.headers['Content-Length'] = length; } catch (err) { - if (payloadMember && payloadMember.isStreaming) { - if (payloadMember.requiresLength) {//streaming payload requires length(s3, glacier) - throw err; - } else if (authtype.indexOf('unsigned-body') >= 0) {//unbounded streaming payload(lex, mediastore) - req.httpRequest.headers['Transfer-Encoding'] = 'chunked'; return; - } else { throw err; } - } throw err; - } - } - }); add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; this.httpRequest = new AWS.HttpRequest(this.service.endpoint, this.service.region); if (this.response.retryCount < this.service.config.maxRetries) { this.response.retryCount++; } else { this.response.error = null; } }); var addToHead = true; addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead); addAsync('SIGN', 'sign', function SIGN(req, done) { - var service = req.service; var operations = req.service.api.operations || {}; var operation = operations[req.operation]; var authtype = operation ? operation.authtype : ''; if (!service.api.signatureVersion && !authtype && !service.config.signatureVersion) return done();// none - service.config.getCredentials(function (err, credentials) { - if (err) { req.response.error = err; return done(); } try { - var date = service.getSkewCorrectedDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, service.api.signingName || service.api.endpointPrefix, { signatureCache: service.config.signatureCache, operation: operation, signatureVersion: service.api.signatureVersion }); signer.setServiceClientId(service._clientId);// clear old authorization headers - delete req.httpRequest.headers['Authorization']; delete req.httpRequest.headers['Date']; delete req.httpRequest.headers['X-Amz-Date'];// add new authorization - signer.addAuthorization(credentials, date); req.signedAt = date; - } catch (e) { req.response.error = e; } done(); - }); - }); add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) { if (this.service.successfulResponse(resp, this)) { resp.data = {}; resp.error = null; } else { resp.data = null; resp.error = AWS.util.error(new Error(), { code: 'UnknownError', message: 'An unknown error occurred.' }); } }); addAsync('SEND', 'send', function SEND(resp, done) { - resp.httpResponse._abortCallback = done; resp.error = null; resp.data = null; function callback(httpResp) { - resp.httpResponse.stream = httpResp; var stream = resp.request.httpRequest.stream; var service = resp.request.service; var api = service.api; var operationName = resp.request.operation; var operation = api.operations[operationName] || {}; httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) { - resp.request.emit('httpHeaders', [statusCode, headers, resp, statusMessage]); if (!resp.httpResponse.streaming) { - if (AWS.HttpClient.streamsApiVersion === 2) {// streams2 API check - // if we detect event streams, we're going to have to - // return the stream immediately - if (operation.hasEventOutput && service.successfulResponse(resp)) {// skip reading the IncomingStream - resp.request.emit('httpDone'); done(); return; - } httpResp.on('readable', function onReadable() { var data = httpResp.read(); if (data !== null) { resp.request.emit('httpData', [data, resp]); } }); - } else {// legacy streams API - httpResp.on('data', function onData(data) { resp.request.emit('httpData', [data, resp]); }); - } - } - }); httpResp.on('end', function onEnd() { - if (!stream || !stream.didCallback) { - if (AWS.HttpClient.streamsApiVersion === 2 && operation.hasEventOutput && service.successfulResponse(resp)) {// don't concatenate response chunks when streaming event stream data when response is successful - return; - } resp.request.emit('httpDone'); done(); - } - }); - } function progress(httpResp) { httpResp.on('sendProgress', function onSendProgress(value) { resp.request.emit('httpUploadProgress', [value, resp]); }); httpResp.on('receiveProgress', function onReceiveProgress(value) { resp.request.emit('httpDownloadProgress', [value, resp]); }); } function error(err) { if (err.code !== 'RequestAbortedError') { var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError'; err = AWS.util.error(err, { code: errCode, region: resp.request.httpRequest.region, hostname: resp.request.httpRequest.endpoint.hostname, retryable: true }); } resp.error = err; resp.request.emit('httpError', [resp.error, resp], function () { done(); }); } function executeSend() { var http = AWS.HttpClient.getInstance(); var httpOptions = resp.request.service.config.httpOptions || {}; try { var stream = http.handleRequest(resp.request.httpRequest, httpOptions, callback, error); progress(stream); } catch (err) { error(err); } } var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000; if (timeDiff >= 60 * 10) {// if we signed 10min ago, re-sign - this.emit('sign', [this], function (err) { if (err) done(err); else executeSend(); }); - } else { executeSend(); } - }); add('HTTP_HEADERS', 'httpHeaders', function HTTP_HEADERS(statusCode, headers, resp, statusMessage) { resp.httpResponse.statusCode = statusCode; resp.httpResponse.statusMessage = statusMessage; resp.httpResponse.headers = headers; resp.httpResponse.body = AWS.util.buffer.toBuffer(''); resp.httpResponse.buffers = []; resp.httpResponse.numBytes = 0; var dateHeader = headers.date || headers.Date; var service = resp.request.service; if (dateHeader) { var serverTime = Date.parse(dateHeader); if (service.config.correctClockSkew && service.isClockSkewed(serverTime)) { service.applyClockOffset(serverTime); } } }); add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) { if (chunk) { if (AWS.util.isNode()) { resp.httpResponse.numBytes += chunk.length; var total = resp.httpResponse.headers['content-length']; var progress = { loaded: resp.httpResponse.numBytes, total: total }; resp.request.emit('httpDownloadProgress', [progress, resp]); } resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk)); } }); add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {// convert buffers array into single buffer - if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) { var body = AWS.util.buffer.concat(resp.httpResponse.buffers); resp.httpResponse.body = body; } delete resp.httpResponse.numBytes; delete resp.httpResponse.buffers; - }); add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) { if (resp.httpResponse.statusCode) { resp.error.statusCode = resp.httpResponse.statusCode; if (resp.error.retryable === undefined) { resp.error.retryable = this.service.retryableError(resp.error, this); } } }); add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) { - if (!resp.error) return; switch (resp.error.code) { - case 'RequestExpired':// EC2 only - case 'ExpiredTokenException': case 'ExpiredToken': resp.error.retryable = true; resp.request.service.config.credentials.expired = true; - } - }); add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) { var err = resp.error; if (!err) return; if (typeof err.code === 'string' && typeof err.message === 'string') { if (err.code.match(/Signature/) && err.message.match(/expired/)) { resp.error.retryable = true; } } }); add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) { if (!resp.error) return; if (this.service.clockSkewError(resp.error) && this.service.config.correctClockSkew) { resp.error.retryable = true; } }); add('REDIRECT', 'retry', function REDIRECT(resp) { if (resp.error && resp.error.statusCode >= 300 && resp.error.statusCode < 400 && resp.httpResponse.headers['location']) { this.httpRequest.endpoint = new AWS.Endpoint(resp.httpResponse.headers['location']); this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host; resp.error.redirect = true; resp.error.retryable = true; } }); add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) { if (resp.error) { if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.error.retryDelay = 0; } else if (resp.retryCount < resp.maxRetries) { resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0; } } }); addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) { var delay, willRetry = false; if (resp.error) { delay = resp.error.retryDelay || 0; if (resp.error.retryable && resp.retryCount < resp.maxRetries) { resp.retryCount++; willRetry = true; } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.redirectCount++; willRetry = true; } } if (willRetry) { resp.error = null; setTimeout(done, delay); } else { done(); } }); - }), CorePost: new SequentialExecutor().addNamedListeners(function (add) { add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId); add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId); add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) { if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') { var message = 'Inaccessible host: `' + err.hostname + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { code: 'UnknownEndpoint', region: err.region, hostname: err.hostname, retryable: true, originalError: err }); } }); }), Logger: new SequentialExecutor().addNamedListeners(function (add) { add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) { var req = resp.request; var logger = req.service.config.logger; if (!logger) return; function filterSensitiveLog(inputShape, shape) { if (!shape) { return shape; } switch (inputShape.type) { case 'structure': var struct = {}; AWS.util.each(shape, function (subShapeName, subShape) { if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) { struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape); } else { struct[subShapeName] = subShape; } }); return struct; case 'list': var list = []; AWS.util.arrayEach(shape, function (subShape, index) { list.push(filterSensitiveLog(inputShape.member, subShape)); }); return list; case 'map': var map = {}; AWS.util.each(shape, function (key, value) { map[key] = filterSensitiveLog(inputShape.value, value); }); return map; default: if (inputShape.isSensitive) { return '***SensitiveInformation***'; } else { return shape; } } } function buildMessage() { var time = resp.request.service.getSkewCorrectedDate().getTime(); var delta = (time - req.startTime.getTime()) / 1000; var ansi = logger.isTTY ? true : false; var status = resp.httpResponse.statusCode; var censoredParams = req.params; if (req.service.api.operations && req.service.api.operations[req.operation] && req.service.api.operations[req.operation].input) { var inputShape = req.service.api.operations[req.operation].input; censoredParams = filterSensitiveLog(inputShape, req.params); } var params = require('util').inspect(censoredParams, true, null); var message = ''; if (ansi) message += '\x1B[33m'; message += '[AWS ' + req.service.serviceIdentifier + ' ' + status; message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]'; if (ansi) message += '\x1B[0;1m'; message += ' ' + AWS.util.string.lowerFirst(req.operation); message += '(' + params + ')'; if (ansi) message += '\x1B[0m'; return message; } var line = buildMessage(); if (typeof logger.log === 'function') { logger.log(line); } else if (typeof logger.write === 'function') { logger.write(line + '\n'); } }); }), Json: new SequentialExecutor().addNamedListeners(function (add) { var svc = require('./protocol/json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Rest: new SequentialExecutor().addNamedListeners(function (add) { var svc = require('./protocol/rest'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestJson: new SequentialExecutor().addNamedListeners(function (add) { var svc = require('./protocol/rest_json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestXml: new SequentialExecutor().addNamedListeners(function (add) { var svc = require('./protocol/rest_xml'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Query: new SequentialExecutor().addNamedListeners(function (add) { var svc = require('./protocol/query'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }) - }; - }, { "./core": 18, "./discover_endpoint": 26, "./protocol/json": 46, "./protocol/query": 47, "./protocol/rest": 48, "./protocol/rest_json": 49, "./protocol/rest_xml": 50, "./sequential_executor": 58, "util": 97 }], 34: [function (require, module, exports) { - var AWS = require('./core'); var inherit = AWS.util.inherit;/** + */function getOperationAuthtype(req){if(!req.service.api.operations){return'';}var operation=req.service.api.operations[req.operation];return operation?operation.authtype:'';}AWS.EventListeners={Core:new SequentialExecutor().addNamedListeners(function(add,addAsync){addAsync('VALIDATE_CREDENTIALS','validate',function VALIDATE_CREDENTIALS(req,done){if(!req.service.api.signatureVersion&&!req.service.config.signatureVersion)return done();// none +req.service.config.getCredentials(function(err){if(err){req.response.error=AWS.util.error(err,{code:'CredentialsError',message:'Missing credentials in config'});}done();});});add('VALIDATE_REGION','validate',function VALIDATE_REGION(req){if(!req.service.config.region&&!req.service.isGlobalEndpoint){req.response.error=AWS.util.error(new Error(),{code:'ConfigError',message:'Missing region in config'});}});add('BUILD_IDEMPOTENCY_TOKENS','validate',function BUILD_IDEMPOTENCY_TOKENS(req){if(!req.service.api.operations){return;}var operation=req.service.api.operations[req.operation];if(!operation){return;}var idempotentMembers=operation.idempotentMembers;if(!idempotentMembers.length){return;}// creates a copy of params so user's param object isn't mutated +var params=AWS.util.copy(req.params);for(var i=0,iLen=idempotentMembers.length;i=0){req.httpRequest.headers['X-Amz-Content-Sha256']='UNSIGNED-PAYLOAD';return done();}AWS.util.computeSha256(body,function(err,sha){if(err){done(err);}else{req.httpRequest.headers['X-Amz-Content-Sha256']=sha;done();}});}else{done();}});add('SET_CONTENT_LENGTH','afterBuild',function SET_CONTENT_LENGTH(req){var authtype=getOperationAuthtype(req);var payloadMember=AWS.util.getRequestPayloadShape(req);if(req.httpRequest.headers['Content-Length']===undefined){try{var length=AWS.util.string.byteLength(req.httpRequest.body);req.httpRequest.headers['Content-Length']=length;}catch(err){if(payloadMember&&payloadMember.isStreaming){if(payloadMember.requiresLength){//streaming payload requires length(s3, glacier) +throw err;}else if(authtype.indexOf('unsigned-body')>=0){//unbounded streaming payload(lex, mediastore) +req.httpRequest.headers['Transfer-Encoding']='chunked';return;}else{throw err;}}throw err;}}});add('SET_HTTP_HOST','afterBuild',function SET_HTTP_HOST(req){req.httpRequest.headers['Host']=req.httpRequest.endpoint.host;});add('RESTART','restart',function RESTART(){var err=this.response.error;if(!err||!err.retryable)return;this.httpRequest=new AWS.HttpRequest(this.service.endpoint,this.service.region);if(this.response.retryCount=60*10){// if we signed 10min ago, re-sign +this.emit('sign',[this],function(err){if(err)done(err);else executeSend();});}else{executeSend();}});add('HTTP_HEADERS','httpHeaders',function HTTP_HEADERS(statusCode,headers,resp,statusMessage){resp.httpResponse.statusCode=statusCode;resp.httpResponse.statusMessage=statusMessage;resp.httpResponse.headers=headers;resp.httpResponse.body=AWS.util.buffer.toBuffer('');resp.httpResponse.buffers=[];resp.httpResponse.numBytes=0;var dateHeader=headers.date||headers.Date;var service=resp.request.service;if(dateHeader){var serverTime=Date.parse(dateHeader);if(service.config.correctClockSkew&&service.isClockSkewed(serverTime)){service.applyClockOffset(serverTime);}}});add('HTTP_DATA','httpData',function HTTP_DATA(chunk,resp){if(chunk){if(AWS.util.isNode()){resp.httpResponse.numBytes+=chunk.length;var total=resp.httpResponse.headers['content-length'];var progress={loaded:resp.httpResponse.numBytes,total:total};resp.request.emit('httpDownloadProgress',[progress,resp]);}resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk));}});add('HTTP_DONE','httpDone',function HTTP_DONE(resp){// convert buffers array into single buffer +if(resp.httpResponse.buffers&&resp.httpResponse.buffers.length>0){var body=AWS.util.buffer.concat(resp.httpResponse.buffers);resp.httpResponse.body=body;}delete resp.httpResponse.numBytes;delete resp.httpResponse.buffers;});add('FINALIZE_ERROR','retry',function FINALIZE_ERROR(resp){if(resp.httpResponse.statusCode){resp.error.statusCode=resp.httpResponse.statusCode;if(resp.error.retryable===undefined){resp.error.retryable=this.service.retryableError(resp.error,this);}}});add('INVALIDATE_CREDENTIALS','retry',function INVALIDATE_CREDENTIALS(resp){if(!resp.error)return;switch(resp.error.code){case'RequestExpired':// EC2 only +case'ExpiredTokenException':case'ExpiredToken':resp.error.retryable=true;resp.request.service.config.credentials.expired=true;}});add('EXPIRED_SIGNATURE','retry',function EXPIRED_SIGNATURE(resp){var err=resp.error;if(!err)return;if(typeof err.code==='string'&&typeof err.message==='string'){if(err.code.match(/Signature/)&&err.message.match(/expired/)){resp.error.retryable=true;}}});add('CLOCK_SKEWED','retry',function CLOCK_SKEWED(resp){if(!resp.error)return;if(this.service.clockSkewError(resp.error)&&this.service.config.correctClockSkew){resp.error.retryable=true;}});add('REDIRECT','retry',function REDIRECT(resp){if(resp.error&&resp.error.statusCode>=300&&resp.error.statusCode<400&&resp.httpResponse.headers['location']){this.httpRequest.endpoint=new AWS.Endpoint(resp.httpResponse.headers['location']);this.httpRequest.headers['Host']=this.httpRequest.endpoint.host;resp.error.redirect=true;resp.error.retryable=true;}});add('RETRY_CHECK','retry',function RETRY_CHECK(resp){if(resp.error){if(resp.error.redirect&&resp.redirectCount= this.HEADERS_RECEIVED && !headersEmitted) { emitter.statusCode = xhr.status; emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders()); emitter.emit('headers', emitter.statusCode, emitter.headers, xhr.statusText); headersEmitted = true; } if (this.readyState === this.DONE) { self.finishRequest(xhr, emitter); } - }, false); xhr.upload.addEventListener('progress', function (evt) { emitter.emit('sendProgress', evt); }); xhr.addEventListener('progress', function (evt) { emitter.emit('receiveProgress', evt); }, false); xhr.addEventListener('timeout', function () { errCallback(AWS.util.error(new Error('Timeout'), { code: 'TimeoutError' })); }, false); xhr.addEventListener('error', function () { errCallback(AWS.util.error(new Error('Network Failure'), { code: 'NetworkingError' })); }, false); xhr.addEventListener('abort', function () { errCallback(AWS.util.error(new Error('Request aborted'), { code: 'RequestAbortedError' })); }, false); callback(emitter); xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false); AWS.util.each(httpRequest.headers, function (key, value) { if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') { xhr.setRequestHeader(key, value); } }); if (httpOptions.timeout && httpOptions.xhrAsync !== false) { xhr.timeout = httpOptions.timeout; } if (httpOptions.xhrWithCredentials) { xhr.withCredentials = true; } try { xhr.responseType = 'arraybuffer'; } catch (e) { } try { if (httpRequest.body) { xhr.send(httpRequest.body); } else { xhr.send(); } } catch (err) { - if (httpRequest.body && _typeof(httpRequest.body.buffer) === 'object') { - xhr.send(httpRequest.body.buffer);// send ArrayBuffer directly - } else { throw err; } - } return emitter; - }, parseHeaders: function parseHeaders(rawHeaders) { var headers = {}; AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) { var key = line.split(':', 1)[0]; var value = line.substring(key.length + 2); if (key.length > 0) headers[key.toLowerCase()] = value; }); return headers; }, finishRequest: function finishRequest(xhr, emitter) { var buffer; if (xhr.responseType === 'arraybuffer' && xhr.response) { var ab = xhr.response; buffer = new AWS.util.Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } } try { if (!buffer && typeof xhr.responseText === 'string') { buffer = new AWS.util.Buffer(xhr.responseText); } } catch (e) { } if (buffer) emitter.emit('data', buffer); emitter.emit('end'); } - });/** + */AWS.XHRClient=AWS.util.inherit({handleRequest:function handleRequest(httpRequest,httpOptions,callback,errCallback){var self=this;var endpoint=httpRequest.endpoint;var emitter=new EventEmitter();var href=endpoint.protocol+'//'+endpoint.hostname;if(endpoint.port!==80&&endpoint.port!==443){href+=':'+endpoint.port;}href+=httpRequest.path;var xhr=new XMLHttpRequest(),headersEmitted=false;httpRequest.stream=xhr;xhr.addEventListener('readystatechange',function(){try{if(xhr.status===0)return;// 0 code is invalid +}catch(e){return;}if(this.readyState>=this.HEADERS_RECEIVED&&!headersEmitted){emitter.statusCode=xhr.status;emitter.headers=self.parseHeaders(xhr.getAllResponseHeaders());emitter.emit('headers',emitter.statusCode,emitter.headers,xhr.statusText);headersEmitted=true;}if(this.readyState===this.DONE){self.finishRequest(xhr,emitter);}},false);xhr.upload.addEventListener('progress',function(evt){emitter.emit('sendProgress',evt);});xhr.addEventListener('progress',function(evt){emitter.emit('receiveProgress',evt);},false);xhr.addEventListener('timeout',function(){errCallback(AWS.util.error(new Error('Timeout'),{code:'TimeoutError'}));},false);xhr.addEventListener('error',function(){errCallback(AWS.util.error(new Error('Network Failure'),{code:'NetworkingError'}));},false);xhr.addEventListener('abort',function(){errCallback(AWS.util.error(new Error('Request aborted'),{code:'RequestAbortedError'}));},false);callback(emitter);xhr.open(httpRequest.method,href,httpOptions.xhrAsync!==false);AWS.util.each(httpRequest.headers,function(key,value){if(key!=='Content-Length'&&key!=='User-Agent'&&key!=='Host'){xhr.setRequestHeader(key,value);}});if(httpOptions.timeout&&httpOptions.xhrAsync!==false){xhr.timeout=httpOptions.timeout;}if(httpOptions.xhrWithCredentials){xhr.withCredentials=true;}try{xhr.responseType='arraybuffer';}catch(e){}try{if(httpRequest.body){xhr.send(httpRequest.body);}else{xhr.send();}}catch(err){if(httpRequest.body&&_typeof(httpRequest.body.buffer)==='object'){xhr.send(httpRequest.body.buffer);// send ArrayBuffer directly +}else{throw err;}}return emitter;},parseHeaders:function parseHeaders(rawHeaders){var headers={};AWS.util.arrayEach(rawHeaders.split(/\r?\n/),function(line){var key=line.split(':',1)[0];var value=line.substring(key.length+2);if(key.length>0)headers[key.toLowerCase()]=value;});return headers;},finishRequest:function finishRequest(xhr,emitter){var buffer;if(xhr.responseType==='arraybuffer'&&xhr.response){var ab=xhr.response;buffer=new AWS.util.Buffer(ab.byteLength);var view=new Uint8Array(ab);for(var i=0;i -1 ? value || '' : value; if (this.isJsonValue) { return JSON.parse(value); } return value && typeof value.toString === 'function' ? value.toString() : value; }; this.toWireFormat = function (value) { return this.isJsonValue ? JSON.stringify(value) : value; }; } function FloatShape() { Shape.apply(this, arguments); this.toType = function (value) { if (value === null || value === undefined) return null; return parseFloat(value); }; this.toWireFormat = this.toType; } function IntegerShape() { Shape.apply(this, arguments); this.toType = function (value) { if (value === null || value === undefined) return null; return parseInt(value, 10); }; this.toWireFormat = this.toType; } function BinaryShape() { - Shape.apply(this, arguments); this.toType = function (value) { - var buf = util.base64.decode(value); if (this.isSensitive && util.isNode() && typeof util.Buffer.alloc === 'function') {/* Node.js can create a Buffer that is not isolated. + */Shape.types={'structure':StructureShape,'list':ListShape,'map':MapShape,'boolean':BooleanShape,'timestamp':TimestampShape,'float':FloatShape,'integer':IntegerShape,'string':StringShape,'base64':Base64Shape,'binary':BinaryShape};Shape.resolve=function resolve(shape,options){if(shape.shape){var refShape=options.api.shapes[shape.shape];if(!refShape){throw new Error('Cannot find shape reference: '+shape.shape);}return refShape;}else{return null;}};Shape.create=function create(shape,options,memberName){if(shape.isShape)return shape;var refShape=Shape.resolve(shape,options);if(refShape){var filteredKeys=Object.keys(shape);if(!options.documentation){filteredKeys=filteredKeys.filter(function(name){return!name.match(/documentation/);});}// create an inline shape with extra members +var InlineShape=function InlineShape(){refShape.constructor.call(this,shape,options,memberName);};InlineShape.prototype=refShape;return new InlineShape();}else{// set type if not set +if(!shape.type){if(shape.members)shape.type='structure';else if(shape.member)shape.type='list';else if(shape.key)shape.type='map';else shape.type='string';}// normalize types +var origType=shape.type;if(Shape.normalizedTypes[shape.type]){shape.type=Shape.normalizedTypes[shape.type];}if(Shape.types[shape.type]){return new Shape.types[shape.type](shape,options,memberName);}else{throw new Error('Unrecognized shape type: '+origType);}}};function CompositeShape(shape){Shape.apply(this,arguments);property(this,'isComposite',true);if(shape.flattened){property(this,'flattened',shape.flattened||false);}}function StructureShape(shape,options){var self=this;var requiredMap=null,firstInit=!this.isShape;CompositeShape.apply(this,arguments);if(firstInit){property(this,'defaultValue',function(){return{};});property(this,'members',{});property(this,'memberNames',[]);property(this,'required',[]);property(this,'isRequired',function(){return false;});}if(shape.members){property(this,'members',new Collection(shape.members,options,function(name,member){return Shape.create(member,options,name);}));memoizedProperty(this,'memberNames',function(){return shape.xmlOrder||Object.keys(shape.members);});if(shape.event){memoizedProperty(this,'eventPayloadMemberName',function(){var members=self.members;var memberNames=self.memberNames;// iterate over members to find ones that are event payloads +for(var i=0,iLen=memberNames.length;i-1?value||'':value;if(this.isJsonValue){return JSON.parse(value);}return value&&typeof value.toString==='function'?value.toString():value;};this.toWireFormat=function(value){return this.isJsonValue?JSON.stringify(value):value;};}function FloatShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseFloat(value);};this.toWireFormat=this.toType;}function IntegerShape(){Shape.apply(this,arguments);this.toType=function(value){if(value===null||value===undefined)return null;return parseInt(value,10);};this.toWireFormat=this.toType;}function BinaryShape(){Shape.apply(this,arguments);this.toType=function(value){var buf=util.base64.decode(value);if(this.isSensitive&&util.isNode()&&typeof util.Buffer.alloc==='function'){/* Node.js can create a Buffer that is not isolated. * i.e. buf.byteLength !== buf.buffer.byteLength * This means that the sensitive data is accessible to anyone with access to buf.buffer. * If this is the node shared Buffer, then other code within this process _could_ find this secret. * Copy sensitive data to an isolated Buffer and zero the sensitive data. * While this is safe to do here, copying this code somewhere else may produce unexpected results. - */var secureBuf = util.Buffer.alloc(buf.length, buf); buf.fill(0); buf = secureBuf; - } return buf; - }; this.toWireFormat = util.base64.encode; - } function Base64Shape() { BinaryShape.apply(this, arguments); } function BooleanShape() { Shape.apply(this, arguments); this.toType = function (value) { if (typeof value === 'boolean') return value; if (value === null || value === undefined) return null; return value === 'true'; }; }/** + */var secureBuf=util.Buffer.alloc(buf.length,buf);buf.fill(0);buf=secureBuf;}return buf;};this.toWireFormat=util.base64.encode;}function Base64Shape(){BinaryShape.apply(this,arguments);}function BooleanShape(){Shape.apply(this,arguments);this.toType=function(value){if(typeof value==='boolean')return value;if(value===null||value===undefined)return null;return value==='true';};}/** * @api private - */Shape.shapes = { StructureShape: StructureShape, ListShape: ListShape, MapShape: MapShape, StringShape: StringShape, BooleanShape: BooleanShape, Base64Shape: Base64Shape };/** + */Shape.shapes={StructureShape:StructureShape,ListShape:ListShape,MapShape:MapShape,StringShape:StringShape,BooleanShape:BooleanShape,Base64Shape:Base64Shape};/** * @api private - */module.exports = Shape; - }, { "../util": 71, "./collection": 39 }], 44: [function (require, module, exports) { - var AWS = require('./core');/** + */module.exports=Shape;},{"../util":71,"./collection":39}],44:[function(require,module,exports){var AWS=require('./core');/** * @api private - */AWS.ParamValidator = AWS.util.inherit({/** + */AWS.ParamValidator=AWS.util.inherit({/** * Create a new validator object. * * @param validation [Boolean|map] whether input parameters should be @@ -3940,142 +3663,63 @@ * regular expression. * * **enum** [Boolean] — Validates that a string value matches one * of the allowable enum values. - */constructor: function ParamValidator(validation) { if (validation === true || validation === undefined) { validation = { 'min': true }; } this.validation = validation; }, validate: function validate(shape, params, context) { this.errors = []; this.validateMember(shape, params || {}, context || 'params'); if (this.errors.length > 1) { var msg = this.errors.join('\n* '); msg = 'There were ' + this.errors.length + ' validation errors:\n* ' + msg; throw AWS.util.error(new Error(msg), { code: 'MultipleValidationErrors', errors: this.errors }); } else if (this.errors.length === 1) { throw this.errors[0]; } else { return true; } }, fail: function fail(code, message) { this.errors.push(AWS.util.error(new Error(message), { code: code })); }, validateStructure: function validateStructure(shape, params, context) { - this.validateType(params, context, ['object'], 'structure'); var paramName; for (var i = 0; shape.required && i < shape.required.length; i++) { paramName = shape.required[i]; var value = params[paramName]; if (value === undefined || value === null) { this.fail('MissingRequiredParameter', 'Missing required key \'' + paramName + '\' in ' + context); } }// validate hash members - for (paramName in params) { if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue; var paramValue = params[paramName], memberShape = shape.members[paramName]; if (memberShape !== undefined) { var memberContext = [context, paramName].join('.'); this.validateMember(memberShape, paramValue, memberContext); } else { this.fail('UnexpectedParameter', 'Unexpected key \'' + paramName + '\' found in ' + context); } } return true; - }, validateMember: function validateMember(shape, param, context) { switch (shape.type) { case 'structure': return this.validateStructure(shape, param, context); case 'list': return this.validateList(shape, param, context); case 'map': return this.validateMap(shape, param, context); default: return this.validateScalar(shape, param, context); } }, validateList: function validateList(shape, params, context) { - if (this.validateType(params, context, [Array])) { - this.validateRange(shape, params.length, context, 'list member count');// validate array members - for (var i = 0; i < params.length; i++) { this.validateMember(shape.member, params[i], context + '[' + i + ']'); } - } - }, validateMap: function validateMap(shape, params, context) { - if (this.validateType(params, context, ['object'], 'map')) {// Build up a count of map members to validate range traits. - var mapCount = 0; for (var param in params) { - if (!Object.prototype.hasOwnProperty.call(params, param)) continue;// Validate any map key trait constraints - this.validateMember(shape.key, param, context + '[key=\'' + param + '\']'); this.validateMember(shape.value, params[param], context + '[\'' + param + '\']'); mapCount++; - } this.validateRange(shape, mapCount, context, 'map member count'); - } - }, validateScalar: function validateScalar(shape, value, context) { switch (shape.type) { case null: case undefined: case 'string': return this.validateString(shape, value, context); case 'base64': case 'binary': return this.validatePayload(value, context); case 'integer': case 'float': return this.validateNumber(shape, value, context); case 'boolean': return this.validateType(value, context, ['boolean']); case 'timestamp': return this.validateType(value, context, [Date, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'], 'Date object, ISO-8601 string, or a UNIX timestamp'); default: return this.fail('UnkownType', 'Unhandled type ' + shape.type + ' for ' + context); } }, validateString: function validateString(shape, value, context) { var validTypes = ['string']; if (shape.isJsonValue) { validTypes = validTypes.concat(['number', 'object', 'boolean']); } if (value !== null && this.validateType(value, context, validTypes)) { this.validateEnum(shape, value, context); this.validateRange(shape, value.length, context, 'string length'); this.validatePattern(shape, value, context); this.validateUri(shape, value, context); } }, validateUri: function validateUri(shape, value, context) { if (shape['location'] === 'uri') { if (value.length === 0) { this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,' + ' but found "' + value + '" for ' + context); } } }, validatePattern: function validatePattern(shape, value, context) { if (this.validation['pattern'] && shape['pattern'] !== undefined) { if (!new RegExp(shape['pattern']).test(value)) { this.fail('PatternMatchError', 'Provided value "' + value + '" ' + 'does not match regex pattern /' + shape['pattern'] + '/ for ' + context); } } }, validateRange: function validateRange(shape, value, context, descriptor) { if (this.validation['min']) { if (shape['min'] !== undefined && value < shape['min']) { this.fail('MinRangeError', 'Expected ' + descriptor + ' >= ' + shape['min'] + ', but found ' + value + ' for ' + context); } } if (this.validation['max']) { if (shape['max'] !== undefined && value > shape['max']) { this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= ' + shape['max'] + ', but found ' + value + ' for ' + context); } } }, validateEnum: function validateRange(shape, value, context) { - if (this.validation['enum'] && shape['enum'] !== undefined) {// Fail if the string value is not present in the enum list - if (shape['enum'].indexOf(value) === -1) { this.fail('EnumError', 'Found string value of ' + value + ', but ' + 'expected ' + shape['enum'].join('|') + ' for ' + context); } - } - }, validateType: function validateType(value, context, acceptedTypes, type) {// We will not log an error for null or undefined, but we will return - // false so that callers know that the expected type was not strictly met. - if (value === null || value === undefined) return false; var foundInvalidType = false; for (var i = 0; i < acceptedTypes.length; i++) { if (typeof acceptedTypes[i] === 'string') { if (_typeof(value) === acceptedTypes[i]) return true; } else if (acceptedTypes[i] instanceof RegExp) { if ((value || '').toString().match(acceptedTypes[i])) return true; } else { if (value instanceof acceptedTypes[i]) return true; if (AWS.util.isType(value, acceptedTypes[i])) return true; if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice(); acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]); } foundInvalidType = true; } var acceptedType = type; if (!acceptedType) { acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1'); } var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : ''; this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' + vowel + ' ' + acceptedType); return false; - }, validateNumber: function validateNumber(shape, value, context) { if (value === null || value === undefined) return; if (typeof value === 'string') { var castedValue = parseFloat(value); if (castedValue.toString() === value) value = castedValue; } if (this.validateType(value, context, ['number'])) { this.validateRange(shape, value, context, 'numeric value'); } }, validatePayload: function validatePayload(value, context) { - if (value === null || value === undefined) return; if (typeof value === 'string') return; if (value && typeof value.byteLength === 'number') return;// typed arrays - if (AWS.util.isNode()) {// special check for buffer/stream in Node.js - var Stream = AWS.util.stream.Stream; if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return; - } else { if ((typeof Blob === "undefined" ? "undefined" : _typeof(Blob)) !== void 0 && value instanceof Blob) return; } var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView']; if (value) { for (var i = 0; i < types.length; i++) { if (AWS.util.isType(value, types[i])) return; if (AWS.util.typeName(value.constructor) === types[i]) return; } } this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' + 'string, Buffer, Stream, Blob, or typed array object'); - } - }); - }, { "./core": 18 }], 45: [function (require, module, exports) { - var util = require('../util'); var AWS = require('../core');/** + */constructor:function ParamValidator(validation){if(validation===true||validation===undefined){validation={'min':true};}this.validation=validation;},validate:function validate(shape,params,context){this.errors=[];this.validateMember(shape,params||{},context||'params');if(this.errors.length>1){var msg=this.errors.join('\n* ');msg='There were '+this.errors.length+' validation errors:\n* '+msg;throw AWS.util.error(new Error(msg),{code:'MultipleValidationErrors',errors:this.errors});}else if(this.errors.length===1){throw this.errors[0];}else{return true;}},fail:function fail(code,message){this.errors.push(AWS.util.error(new Error(message),{code:code}));},validateStructure:function validateStructure(shape,params,context){this.validateType(params,context,['object'],'structure');var paramName;for(var i=0;shape.required&&i= 1,'+' but found "'+value+'" for '+context);}}},validatePattern:function validatePattern(shape,value,context){if(this.validation['pattern']&&shape['pattern']!==undefined){if(!new RegExp(shape['pattern']).test(value)){this.fail('PatternMatchError','Provided value "'+value+'" '+'does not match regex pattern /'+shape['pattern']+'/ for '+context);}}},validateRange:function validateRange(shape,value,context,descriptor){if(this.validation['min']){if(shape['min']!==undefined&&value= '+shape['min']+', but found '+value+' for '+context);}}if(this.validation['max']){if(shape['max']!==undefined&&value>shape['max']){this.fail('MaxRangeError','Expected '+descriptor+' <= '+shape['max']+', but found '+value+' for '+context);}}},validateEnum:function validateRange(shape,value,context){if(this.validation['enum']&&shape['enum']!==undefined){// Fail if the string value is not present in the enum list +if(shape['enum'].indexOf(value)===-1){this.fail('EnumError','Found string value of '+value+', but '+'expected '+shape['enum'].join('|')+' for '+context);}}},validateType:function validateType(value,context,acceptedTypes,type){// We will not log an error for null or undefined, but we will return +// false so that callers know that the expected type was not strictly met. +if(value===null||value===undefined)return false;var foundInvalidType=false;for(var i=0;i 63) { throw util.error(new Error(), { code: 'ValidationError', message: 'Hostname label length should be between 1 to 63 characters, inclusive.' }); } if (!hostPattern.test(label)) { throw AWS.util.error(new Error(), { code: 'ValidationError', message: label + ' is not hostname compatible.' }); } }); - } module.exports = { populateHostPrefix: populateHostPrefix }; - }, { "../core": 18, "../util": 71 }], 46: [function (require, module, exports) { - var util = require('../util'); var JsonBuilder = require('../json/builder'); var JsonParser = require('../json/parser'); var populateHostPrefix = require('./helpers').populateHostPrefix; function buildRequest(req) { var httpRequest = req.httpRequest; var api = req.service.api; var target = api.targetPrefix + '.' + api.operations[req.operation].name; var version = api.jsonVersion || '1.0'; var input = api.operations[req.operation].input; var builder = new JsonBuilder(); if (version === 1) version = '1.0'; httpRequest.body = builder.build(req.params || {}, input); httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version; httpRequest.headers['X-Amz-Target'] = target; populateHostPrefix(req); } function extractError(resp) { var error = {}; var httpResponse = resp.httpResponse; error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError'; if (typeof error.code === 'string') { error.code = error.code.split(':')[0]; } if (httpResponse.body.length > 0) { try { var e = JSON.parse(httpResponse.body.toString()); if (e.__type || e.code) { error.code = (e.__type || e.code).split('#').pop(); } if (error.code === 'RequestEntityTooLarge') { error.message = 'Request body must be less than 1 MB'; } else { error.message = e.message || e.Message || null; } } catch (e) { error.statusCode = httpResponse.statusCode; error.message = httpResponse.statusMessage; } } else { error.statusCode = httpResponse.statusCode; error.message = httpResponse.statusCode.toString(); } resp.error = util.error(new Error(), error); } function extractData(resp) { var body = resp.httpResponse.body.toString() || '{}'; if (resp.request.service.config.convertResponseTypes === false) { resp.data = JSON.parse(body); } else { var operation = resp.request.service.api.operations[resp.request.operation]; var shape = operation.output || {}; var parser = new JsonParser(); resp.data = parser.parse(body, shape); } }/** + */function validateHostname(hostname){var labels=hostname.split('.');//Reference: https://tools.ietf.org/html/rfc1123#section-2 +var hostPattern=/^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;util.arrayEach(labels,function(label){if(!label.length||label.length<1||label.length>63){throw util.error(new Error(),{code:'ValidationError',message:'Hostname label length should be between 1 to 63 characters, inclusive.'});}if(!hostPattern.test(label)){throw AWS.util.error(new Error(),{code:'ValidationError',message:label+' is not hostname compatible.'});}});}module.exports={populateHostPrefix:populateHostPrefix};},{"../core":18,"../util":71}],46:[function(require,module,exports){var util=require('../util');var JsonBuilder=require('../json/builder');var JsonParser=require('../json/parser');var populateHostPrefix=require('./helpers').populateHostPrefix;function buildRequest(req){var httpRequest=req.httpRequest;var api=req.service.api;var target=api.targetPrefix+'.'+api.operations[req.operation].name;var version=api.jsonVersion||'1.0';var input=api.operations[req.operation].input;var builder=new JsonBuilder();if(version===1)version='1.0';httpRequest.body=builder.build(req.params||{},input);httpRequest.headers['Content-Type']='application/x-amz-json-'+version;httpRequest.headers['X-Amz-Target']=target;populateHostPrefix(req);}function extractError(resp){var error={};var httpResponse=resp.httpResponse;error.code=httpResponse.headers['x-amzn-errortype']||'UnknownError';if(typeof error.code==='string'){error.code=error.code.split(':')[0];}if(httpResponse.body.length>0){try{var e=JSON.parse(httpResponse.body.toString());if(e.__type||e.code){error.code=(e.__type||e.code).split('#').pop();}if(error.code==='RequestEntityTooLarge'){error.message='Request body must be less than 1 MB';}else{error.message=e.message||e.Message||null;}}catch(e){error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusMessage;}}else{error.statusCode=httpResponse.statusCode;error.message=httpResponse.statusCode.toString();}resp.error=util.error(new Error(),error);}function extractData(resp){var body=resp.httpResponse.body.toString()||'{}';if(resp.request.service.config.convertResponseTypes===false){resp.data=JSON.parse(body);}else{var operation=resp.request.service.api.operations[resp.request.operation];var shape=operation.output||{};var parser=new JsonParser();resp.data=parser.parse(body,shape);}}/** * @api private - */module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; - }, { "../json/builder": 36, "../json/parser": 37, "../util": 71, "./helpers": 45 }], 47: [function (require, module, exports) { - var AWS = require('../core'); var util = require('../util'); var QueryParamSerializer = require('../query/query_param_serializer'); var Shape = require('../model/shape'); var populateHostPrefix = require('./helpers').populateHostPrefix; function buildRequest(req) { - var operation = req.service.api.operations[req.operation]; var httpRequest = req.httpRequest; httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'; httpRequest.params = { Version: req.service.api.apiVersion, Action: operation.name };// convert the request parameters into a list of query params, - // e.g. Deeply.NestedParam.0.Name=value - var builder = new QueryParamSerializer(); builder.serialize(req.params, operation.input, function (name, value) { httpRequest.params[name] = value; }); httpRequest.body = util.queryParamsToString(httpRequest.params); populateHostPrefix(req); - } function extractError(resp) { var data, body = resp.httpResponse.body.toString(); if (body.match('= 0 ? '&' : '?'; var parts = []; util.arrayEach(Object.keys(queryString).sort(), function (key) { if (!Array.isArray(queryString[key])) { queryString[key] = [queryString[key]]; } for (var i = 0; i < queryString[key].length; i++) { parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]); } }); uri += parts.join('&'); } return uri; } function populateURI(req) { var operation = req.service.api.operations[req.operation]; var input = operation.input; var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params); req.httpRequest.path = uri; } function populateHeaders(req) { var operation = req.service.api.operations[req.operation]; util.each(operation.input.members, function (name, member) { var value = req.params[name]; if (value === null || value === undefined) return; if (member.location === 'headers' && member.type === 'map') { util.each(value, function (key, memberValue) { req.httpRequest.headers[member.name + key] = memberValue; }); } else if (member.location === 'header') { value = member.toWireFormat(value).toString(); if (member.isJsonValue) { value = util.base64.encode(value); } req.httpRequest.headers[member.name] = value; } }); } function buildRequest(req) { populateMethod(req); populateURI(req); populateHeaders(req); populateHostPrefix(req); } function extractError() { } function extractData(resp) { - var req = resp.request; var data = {}; var r = resp.httpResponse; var operation = req.service.api.operations[req.operation]; var output = operation.output;// normalize headers names to lower-cased keys for matching - var headers = {}; util.each(r.headers, function (k, v) { headers[k.toLowerCase()] = v; }); util.each(output.members, function (name, member) { var header = (member.name || name).toLowerCase(); if (member.location === 'headers' && member.type === 'map') { data[name] = {}; var location = member.isLocationName ? member.name : ''; var pattern = new RegExp('^' + location + '(.+)', 'i'); util.each(r.headers, function (k, v) { var result = k.match(pattern); if (result !== null) { data[name][result[1]] = v; } }); } else if (member.location === 'header') { if (headers[header] !== undefined) { var value = member.isJsonValue ? util.base64.decode(headers[header]) : headers[header]; data[name] = member.toType(value); } } else if (member.location === 'statusCode') { data[name] = parseInt(r.statusCode, 10); } }); resp.data = data; - }/** + */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../core":18,"../model/shape":43,"../query/query_param_serializer":51,"../util":71,"./helpers":45}],48:[function(require,module,exports){var util=require('../util');var populateHostPrefix=require('./helpers').populateHostPrefix;function populateMethod(req){req.httpRequest.method=req.service.api.operations[req.operation].httpMethod;}function generateURI(endpointPath,operationPath,input,params){var uri=[endpointPath,operationPath].join('/');uri=uri.replace(/\/+/g,'/');var queryString={},queryStringSet=false;util.each(input.members,function(name,member){var paramValue=params[name];if(paramValue===null||paramValue===undefined)return;if(member.location==='uri'){var regex=new RegExp('\\{'+member.name+'(\\+)?\\}');uri=uri.replace(regex,function(_,plus){var fn=plus?util.uriEscapePath:util.uriEscape;return fn(String(paramValue));});}else if(member.location==='querystring'){queryStringSet=true;if(member.type==='list'){queryString[member.name]=paramValue.map(function(val){return util.uriEscape(member.member.toWireFormat(val).toString());});}else if(member.type==='map'){util.each(paramValue,function(key,value){if(Array.isArray(value)){queryString[key]=value.map(function(val){return util.uriEscape(String(val));});}else{queryString[key]=util.uriEscape(String(value));}});}else{queryString[member.name]=util.uriEscape(member.toWireFormat(paramValue).toString());}}});if(queryStringSet){uri+=uri.indexOf('?')>=0?'&':'?';var parts=[];util.arrayEach(Object.keys(queryString).sort(),function(key){if(!Array.isArray(queryString[key])){queryString[key]=[queryString[key]];}for(var i=0;i 0) { parser = new AWS.XML.Parser(); var data = parser.parse(body.toString(), output); util.update(resp.data, data); } }/** + */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../json/builder":36,"../json/parser":37,"../util":71,"./json":46,"./rest":48}],50:[function(require,module,exports){var AWS=require('../core');var util=require('../util');var Rest=require('./rest');function populateBody(req){var input=req.service.api.operations[req.operation].input;var builder=new AWS.XML.Builder();var params=req.params;var payload=input.payload;if(payload){var payloadMember=input.members[payload];params=params[payload];if(params===undefined)return;if(payloadMember.type==='structure'){var rootElement=payloadMember.name;req.httpRequest.body=builder.toXML(params,payloadMember,rootElement,true);}else{// non-xml payload +req.httpRequest.body=params;}}else{req.httpRequest.body=builder.toXML(params,input,input.name||input.shape||util.string.upperFirst(req.operation)+'Request');}}function buildRequest(req){Rest.buildRequest(req);// never send body payload on GET/HEAD +if(['GET','HEAD'].indexOf(req.httpRequest.method)<0){populateBody(req);}}function extractError(resp){Rest.extractError(resp);var data;try{data=new AWS.XML.Parser().parse(resp.httpResponse.body.toString());}catch(e){data={Code:resp.httpResponse.statusCode,Message:resp.httpResponse.statusMessage};}if(data.Errors)data=data.Errors;if(data.Error)data=data.Error;if(data.Code){resp.error=util.error(new Error(),{code:data.Code,message:data.Message});}else{resp.error=util.error(new Error(),{code:resp.httpResponse.statusCode,message:null});}}function extractData(resp){Rest.extractData(resp);var parser;var req=resp.request;var body=resp.httpResponse.body;var operation=req.service.api.operations[req.operation];var output=operation.output;var hasEventOutput=operation.hasEventOutput;var payload=output.payload;if(payload){var payloadMember=output.members[payload];if(payloadMember.isEventStream){parser=new AWS.XML.Parser();resp.data[payload]=util.createEventStream(AWS.HttpClient.streamsApiVersion===2?resp.httpResponse.stream:resp.httpResponse.body,parser,payloadMember);}else if(payloadMember.type==='structure'){parser=new AWS.XML.Parser();resp.data[payload]=parser.parse(body.toString(),payloadMember);}else if(payloadMember.type==='binary'||payloadMember.isStreaming){resp.data[payload]=body;}else{resp.data[payload]=payloadMember.toType(body);}}else if(body.length>0){parser=new AWS.XML.Parser();var data=parser.parse(body.toString(),output);util.update(resp.data,data);}}/** * @api private - */module.exports = { buildRequest: buildRequest, extractError: extractError, extractData: extractData }; - }, { "../core": 18, "../util": 71, "./rest": 48 }], 51: [function (require, module, exports) { - var util = require('../util'); function QueryParamSerializer() { } QueryParamSerializer.prototype.serialize = function (params, shape, fn) { serializeStructure('', params, shape, fn); }; function ucfirst(shape) { if (shape.isQueryName || shape.api.protocol !== 'ec2') { return shape.name; } else { return shape.name[0].toUpperCase() + shape.name.substr(1); } } function serializeStructure(prefix, struct, rules, fn) { util.each(rules.members, function (name, member) { var value = struct[name]; if (value === null || value === undefined) return; var memberName = ucfirst(member); memberName = prefix ? prefix + '.' + memberName : memberName; serializeMember(memberName, value, member, fn); }); } function serializeMap(name, map, rules, fn) { var i = 1; util.each(map, function (key, value) { var prefix = rules.flattened ? '.' : '.entry.'; var position = prefix + i++ + '.'; var keyName = position + (rules.key.name || 'key'); var valueName = position + (rules.value.name || 'value'); serializeMember(name + keyName, key, rules.key, fn); serializeMember(name + valueName, value, rules.value, fn); }); } function serializeList(name, list, rules, fn) { - var memberRules = rules.member || {}; if (list.length === 0) { fn.call(this, name, null); return; } util.arrayEach(list, function (v, n) { - var suffix = '.' + (n + 1); if (rules.api.protocol === 'ec2') {// Do nothing for EC2 - suffix = suffix + '';// make linter happy - } else if (rules.flattened) { if (memberRules.name) { var parts = name.split('.'); parts.pop(); parts.push(ucfirst(memberRules)); name = parts.join('.'); } } else { suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix; } serializeMember(name + suffix, v, memberRules, fn); - }); - } function serializeMember(name, value, rules, fn) { if (value === null || value === undefined) return; if (rules.type === 'structure') { serializeStructure(name, value, rules, fn); } else if (rules.type === 'list') { serializeList(name, value, rules, fn); } else if (rules.type === 'map') { serializeMap(name, value, rules, fn); } else { fn(name, rules.toWireFormat(value).toString()); } }/** + */module.exports={buildRequest:buildRequest,extractError:extractError,extractData:extractData};},{"../core":18,"../util":71,"./rest":48}],51:[function(require,module,exports){var util=require('../util');function QueryParamSerializer(){}QueryParamSerializer.prototype.serialize=function(params,shape,fn){serializeStructure('',params,shape,fn);};function ucfirst(shape){if(shape.isQueryName||shape.api.protocol!=='ec2'){return shape.name;}else{return shape.name[0].toUpperCase()+shape.name.substr(1);}}function serializeStructure(prefix,struct,rules,fn){util.each(rules.members,function(name,member){var value=struct[name];if(value===null||value===undefined)return;var memberName=ucfirst(member);memberName=prefix?prefix+'.'+memberName:memberName;serializeMember(memberName,value,member,fn);});}function serializeMap(name,map,rules,fn){var i=1;util.each(map,function(key,value){var prefix=rules.flattened?'.':'.entry.';var position=prefix+i++ +'.';var keyName=position+(rules.key.name||'key');var valueName=position+(rules.value.name||'value');serializeMember(name+keyName,key,rules.key,fn);serializeMember(name+valueName,value,rules.value,fn);});}function serializeList(name,list,rules,fn){var memberRules=rules.member||{};if(list.length===0){fn.call(this,name,null);return;}util.arrayEach(list,function(v,n){var suffix='.'+(n+1);if(rules.api.protocol==='ec2'){// Do nothing for EC2 +suffix=suffix+'';// make linter happy +}else if(rules.flattened){if(memberRules.name){var parts=name.split('.');parts.pop();parts.push(ucfirst(memberRules));name=parts.join('.');}}else{suffix='.'+(memberRules.name?memberRules.name:'member')+suffix;}serializeMember(name+suffix,v,memberRules,fn);});}function serializeMember(name,value,rules,fn){if(value===null||value===undefined)return;if(rules.type==='structure'){serializeStructure(name,value,rules,fn);}else if(rules.type==='list'){serializeList(name,value,rules,fn);}else if(rules.type==='map'){serializeMap(name,value,rules,fn);}else{fn(name,rules.toWireFormat(value).toString());}}/** * @api private - */module.exports = QueryParamSerializer; - }, { "../util": 71 }], 52: [function (require, module, exports) { - module.exports = {//provide realtime clock for performance measurement - now: function now() { if (typeof performance !== 'undefined' && typeof performance.now === 'function') { return performance.now(); } return Date.now(); } - }; - }, {}], 53: [function (require, module, exports) { - var util = require('./util'); var regionConfig = require('./region_config_data.json'); function generateRegionPrefix(region) { if (!region) return null; var parts = region.split('-'); if (parts.length < 3) return null; return parts.slice(0, parts.length - 2).join('-') + '-*'; } function derivedKeys(service) { var region = service.config.region; var regionPrefix = generateRegionPrefix(region); var endpointPrefix = service.api.endpointPrefix; return [[region, endpointPrefix], [regionPrefix, endpointPrefix], [region, '*'], [regionPrefix, '*'], ['*', endpointPrefix], ['*', '*']].map(function (item) { return item[0] && item[1] ? item.join('/') : null; }); } function applyConfig(service, config) { util.each(config, function (key, value) { if (key === 'globalEndpoint') return; if (service.config[key] === undefined || service.config[key] === null) { service.config[key] = value; } }); } function configureEndpoint(service) { - var keys = derivedKeys(service); for (var i = 0; i < keys.length; i++) { - var key = keys[i]; if (!key) continue; if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) { - var config = regionConfig.rules[key]; if (typeof config === 'string') { config = regionConfig.patterns[config]; }// set dualstack endpoint - if (service.config.useDualstack && util.isDualstackAvailable(service)) { config = util.copy(config); config.endpoint = '{service}.dualstack.{region}.amazonaws.com'; }// set global endpoint - service.isGlobalEndpoint = !!config.globalEndpoint;// signature version - if (!config.signatureVersion) config.signatureVersion = 'v4';// merge config - applyConfig(service, config); return; - } - } - }/** + */module.exports=QueryParamSerializer;},{"../util":71}],52:[function(require,module,exports){module.exports={//provide realtime clock for performance measurement +now:function now(){if(typeof performance!=='undefined'&&typeof performance.now==='function'){return performance.now();}return Date.now();}};},{}],53:[function(require,module,exports){var util=require('./util');var regionConfig=require('./region_config_data.json');function generateRegionPrefix(region){if(!region)return null;var parts=region.split('-');if(parts.length<3)return null;return parts.slice(0,parts.length-2).join('-')+'-*';}function derivedKeys(service){var region=service.config.region;var regionPrefix=generateRegionPrefix(region);var endpointPrefix=service.api.endpointPrefix;return[[region,endpointPrefix],[regionPrefix,endpointPrefix],[region,'*'],[regionPrefix,'*'],['*',endpointPrefix],['*','*']].map(function(item){return item[0]&&item[1]?item.join('/'):null;});}function applyConfig(service,config){util.each(config,function(key,value){if(key==='globalEndpoint')return;if(service.config[key]===undefined||service.config[key]===null){service.config[key]=value;}});}function configureEndpoint(service){var keys=derivedKeys(service);for(var i=0;i= 0) { shouldCheckContentLength = true; var receivedLen = 0; } var checkContentLengthAndEmit = function checkContentLengthAndEmit() { if (shouldCheckContentLength && receivedLen !== expectedLen) { stream.emit('error', AWS.util.error(new Error('Stream content length mismatch. Received ' + receivedLen + ' of ' + expectedLen + ' bytes.'), { code: 'StreamContentLengthMismatch' })); } else if (AWS.HttpClient.streamsApiVersion === 2) { stream.end(); } else { stream.emit('end'); } }; var httpStream = resp.httpResponse.createUnbufferedStream(); if (AWS.HttpClient.streamsApiVersion === 2) { if (shouldCheckContentLength) { var lengthAccumulator = new streams.PassThrough(); lengthAccumulator._write = function (chunk) { if (chunk && chunk.length) { receivedLen += chunk.length; } return streams.PassThrough.prototype._write.apply(this, arguments); }; lengthAccumulator.on('end', checkContentLengthAndEmit); stream.on('error', function (err) { shouldCheckContentLength = false; httpStream.unpipe(lengthAccumulator); lengthAccumulator.emit('end'); lengthAccumulator.end(); }); httpStream.pipe(lengthAccumulator).pipe(stream, { end: false }); } else { httpStream.pipe(stream); } } else { if (shouldCheckContentLength) { httpStream.on('data', function (arg) { if (arg && arg.length) { receivedLen += arg.length; } }); } httpStream.on('data', function (arg) { stream.emit('data', arg); }); httpStream.on('end', checkContentLengthAndEmit); } httpStream.on('error', function (err) { shouldCheckContentLength = false; stream.emit('error', err); }); } }); return stream; },/** + */createReadStream:function createReadStream(){var streams=AWS.util.stream;var req=this;var stream=null;if(AWS.HttpClient.streamsApiVersion===2){stream=new streams.PassThrough();process.nextTick(function(){req.send();});}else{stream=new streams.Stream();stream.readable=true;stream.sent=false;stream.on('newListener',function(event){if(!stream.sent&&event==='data'){stream.sent=true;process.nextTick(function(){req.send();});}});}this.on('error',function(err){stream.emit('error',err);});this.on('httpHeaders',function streamHeaders(statusCode,headers,resp){if(statusCode<300){req.removeListener('httpData',AWS.EventListeners.Core.HTTP_DATA);req.removeListener('httpError',AWS.EventListeners.Core.HTTP_ERROR);req.on('httpError',function streamHttpError(error){resp.error=error;resp.error.retryable=false;});var shouldCheckContentLength=false;var expectedLen;if(req.httpRequest.method!=='HEAD'){expectedLen=parseInt(headers['content-length'],10);}if(expectedLen!==undefined&&!isNaN(expectedLen)&&expectedLen>=0){shouldCheckContentLength=true;var receivedLen=0;}var checkContentLengthAndEmit=function checkContentLengthAndEmit(){if(shouldCheckContentLength&&receivedLen!==expectedLen){stream.emit('error',AWS.util.error(new Error('Stream content length mismatch. Received '+receivedLen+' of '+expectedLen+' bytes.'),{code:'StreamContentLengthMismatch'}));}else if(AWS.HttpClient.streamsApiVersion===2){stream.end();}else{stream.emit('end');}};var httpStream=resp.httpResponse.createUnbufferedStream();if(AWS.HttpClient.streamsApiVersion===2){if(shouldCheckContentLength){var lengthAccumulator=new streams.PassThrough();lengthAccumulator._write=function(chunk){if(chunk&&chunk.length){receivedLen+=chunk.length;}return streams.PassThrough.prototype._write.apply(this,arguments);};lengthAccumulator.on('end',checkContentLengthAndEmit);stream.on('error',function(err){shouldCheckContentLength=false;httpStream.unpipe(lengthAccumulator);lengthAccumulator.emit('end');lengthAccumulator.end();});httpStream.pipe(lengthAccumulator).pipe(stream,{end:false});}else{httpStream.pipe(stream);}}else{if(shouldCheckContentLength){httpStream.on('data',function(arg){if(arg&&arg.length){receivedLen+=arg.length;}});}httpStream.on('data',function(arg){stream.emit('data',arg);});httpStream.on('end',checkContentLengthAndEmit);}httpStream.on('error',function(err){shouldCheckContentLength=false;stream.emit('error',err);});}});return stream;},/** * @param [Array,Response] args This should be the response object, * or an array of args to send to the event. * @api private - */emitEvent: function emit(eventName, args, done) { if (typeof args === 'function') { done = args; args = null; } if (!done) done = function done() { }; if (!args) args = this.eventParameters(eventName, this.response); var origEmit = AWS.SequentialExecutor.prototype.emit; origEmit.call(this, eventName, args, function (err) { if (err) this.response.error = err; done.call(this, err); }); },/** + */emitEvent:function emit(eventName,args,done){if(typeof args==='function'){done=args;args=null;}if(!done)done=function done(){};if(!args)args=this.eventParameters(eventName,this.response);var origEmit=AWS.SequentialExecutor.prototype.emit;origEmit.call(this,eventName,args,function(err){if(err)this.response.error=err;done.call(this,err);});},/** * @api private - */eventParameters: function eventParameters(eventName) { switch (eventName) { case 'restart': case 'validate': case 'sign': case 'build': case 'afterValidate': case 'afterBuild': return [this]; case 'error': return [this.response.error, this.response]; default: return [this.response]; } },/** + */eventParameters:function eventParameters(eventName){switch(eventName){case'restart':case'validate':case'sign':case'build':case'afterValidate':case'afterBuild':return[this];case'error':return[this.response.error,this.response];default:return[this.response];}},/** * @api private - */presign: function presign(expires, callback) { if (!callback && typeof expires === 'function') { callback = expires; expires = null; } return new AWS.Signers.Presign().sign(this.toGet(), expires, callback); },/** + */presign:function presign(expires,callback){if(!callback&&typeof expires==='function'){callback=expires;expires=null;}return new AWS.Signers.Presign().sign(this.toGet(),expires,callback);},/** * @api private - */isPresigned: function isPresigned() { return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires'); },/** + */isPresigned:function isPresigned(){return Object.prototype.hasOwnProperty.call(this.httpRequest.headers,'presigned-expires');},/** * @api private - */toUnauthenticated: function toUnauthenticated() { this._unAuthenticated = true; this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS); this.removeListener('sign', AWS.EventListeners.Core.SIGN); return this; },/** + */toUnauthenticated:function toUnauthenticated(){this._unAuthenticated=true;this.removeListener('validate',AWS.EventListeners.Core.VALIDATE_CREDENTIALS);this.removeListener('sign',AWS.EventListeners.Core.SIGN);return this;},/** * @api private - */toGet: function toGet() { if (this.service.api.protocol === 'query' || this.service.api.protocol === 'ec2') { this.removeListener('build', this.buildAsGet); this.addListener('build', this.buildAsGet); } return this; },/** + */toGet:function toGet(){if(this.service.api.protocol==='query'||this.service.api.protocol==='ec2'){this.removeListener('build',this.buildAsGet);this.addListener('build',this.buildAsGet);}return this;},/** * @api private - */buildAsGet: function buildAsGet(request) { - request.httpRequest.method = 'GET'; request.httpRequest.path = request.service.endpoint.path + '?' + request.httpRequest.body; request.httpRequest.body = '';// don't need these headers on a GET request - delete request.httpRequest.headers['Content-Length']; delete request.httpRequest.headers['Content-Type']; - },/** + */buildAsGet:function buildAsGet(request){request.httpRequest.method='GET';request.httpRequest.path=request.service.endpoint.path+'?'+request.httpRequest.body;request.httpRequest.body='';// don't need these headers on a GET request +delete request.httpRequest.headers['Content-Length'];delete request.httpRequest.headers['Content-Type'];},/** * @api private - */haltHandlersOnError: function haltHandlersOnError() { this._haltHandlersOnError = true; } - });/** + */haltHandlersOnError:function haltHandlersOnError(){this._haltHandlersOnError=true;}});/** * @api private - */AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) { - this.prototype.promise = function promise() { - var self = this;// append to user agent - this.httpRequest.appendToUserAgent('promise'); return new PromiseDependency(function (resolve, reject) { - self.on('complete', function (resp) { - if (resp.error) { reject(resp.error); } else {// define $response property so that it is not enumberable - // this prevents circular reference errors when stringifying the JSON object - resolve(Object.defineProperty(resp.data || {}, '$response', { value: resp })); - } - }); self.runTo(); - }); - }; - };/** + */AWS.Request.addPromisesToClass=function addPromisesToClass(PromiseDependency){this.prototype.promise=function promise(){var self=this;// append to user agent +this.httpRequest.appendToUserAgent('promise');return new PromiseDependency(function(resolve,reject){self.on('complete',function(resp){if(resp.error){reject(resp.error);}else{// define $response property so that it is not enumberable +// this prevents circular reference errors when stringifying the JSON object +resolve(Object.defineProperty(resp.data||{},'$response',{value:resp}));}});self.runTo();});};};/** * @api private - */AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() { delete this.prototype.promise; }; AWS.util.addPromises(AWS.Request); AWS.util.mixin(AWS.Request, AWS.SequentialExecutor); - }).call(this); - }).call(this, require('_process')); - }, { "./core": 18, "./state_machine": 70, "_process": 86, "jmespath": 85 }], 56: [function (require, module, exports) {/** + */AWS.Request.deletePromisesFromClass=function deletePromisesFromClass(){delete this.prototype.promise;};AWS.util.addPromises(AWS.Request);AWS.util.mixin(AWS.Request,AWS.SequentialExecutor);}).call(this);}).call(this,require('_process'));},{"./core":18,"./state_machine":70,"_process":86,"jmespath":85}],56:[function(require,module,exports){/** * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You @@ -4519,11 +4138,11 @@ * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. - */var AWS = require('./core'); var inherit = AWS.util.inherit; var jmespath = require('jmespath');/** + */var AWS=require('./core');var inherit=AWS.util.inherit;var jmespath=require('jmespath');/** * @api private - */function CHECK_ACCEPTORS(resp) { var waiter = resp.request._waiter; var acceptors = waiter.config.acceptors; var acceptorMatched = false; var state = 'retry'; acceptors.forEach(function (acceptor) { if (!acceptorMatched) { var matcher = waiter.matchers[acceptor.matcher]; if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) { acceptorMatched = true; state = acceptor.state; } } }); if (!acceptorMatched && resp.error) state = 'failure'; if (state === 'success') { waiter.setSuccess(resp); } else { waiter.setError(resp, state === 'retry'); } }/** + */function CHECK_ACCEPTORS(resp){var waiter=resp.request._waiter;var acceptors=waiter.config.acceptors;var acceptorMatched=false;var state='retry';acceptors.forEach(function(acceptor){if(!acceptorMatched){var matcher=waiter.matchers[acceptor.matcher];if(matcher&&matcher(resp,acceptor.expected,acceptor.argument)){acceptorMatched=true;state=acceptor.state;}}});if(!acceptorMatched&&resp.error)state='failure';if(state==='success'){waiter.setSuccess(resp);}else{waiter.setError(resp,state==='retry');}}/** * @api private - */AWS.ResourceWaiter = inherit({/** + */AWS.ResourceWaiter=inherit({/** * Waits for a given state on a service object * @param service [Service] the service object to wait on * @param state [String] the state (defined in waiter configuration) to wait @@ -4531,21 +4150,14 @@ * @example Create a waiter for running EC2 instances * var ec2 = new AWS.EC2; * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning'); - */constructor: function constructor(service, state) { this.service = service; this.state = state; this.loadWaiterConfig(this.state); }, service: null, state: null, config: null, matchers: { - path: function path(resp, expected, argument) { try { var result = jmespath.search(resp.data, argument); } catch (err) { return false; } return jmespath.strictDeepEqual(result, expected); }, pathAll: function pathAll(resp, expected, argument) { try { var results = jmespath.search(resp.data, argument); } catch (err) { return false; } if (!Array.isArray(results)) results = [results]; var numResults = results.length; if (!numResults) return false; for (var ind = 0; ind < numResults; ind++) { if (!jmespath.strictDeepEqual(results[ind], expected)) { return false; } } return true; }, pathAny: function pathAny(resp, expected, argument) { try { var results = jmespath.search(resp.data, argument); } catch (err) { return false; } if (!Array.isArray(results)) results = [results]; var numResults = results.length; for (var ind = 0; ind < numResults; ind++) { if (jmespath.strictDeepEqual(results[ind], expected)) { return true; } } return false; }, status: function status(resp, expected) { var statusCode = resp.httpResponse.statusCode; return typeof statusCode === 'number' && statusCode === expected; }, error: function error(resp, expected) { - if (typeof expected === 'string' && resp.error) { return expected === resp.error.code; }// if expected is not string, can be boolean indicating presence of error - return expected === !!resp.error; - } - }, listeners: new AWS.SequentialExecutor().addNamedListeners(function (add) { add('RETRY_CHECK', 'retry', function (resp) { var waiter = resp.request._waiter; if (resp.error && resp.error.code === 'ResourceNotReady') { resp.error.retryDelay = (waiter.config.delay || 0) * 1000; } }); add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS); add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS); }),/** + */constructor:function constructor(service,state){this.service=service;this.state=state;this.loadWaiterConfig(this.state);},service:null,state:null,config:null,matchers:{path:function path(resp,expected,argument){try{var result=jmespath.search(resp.data,argument);}catch(err){return false;}return jmespath.strictDeepEqual(result,expected);},pathAll:function pathAll(resp,expected,argument){try{var results=jmespath.search(resp.data,argument);}catch(err){return false;}if(!Array.isArray(results))results=[results];var numResults=results.length;if(!numResults)return false;for(var ind=0;ind -1) { listeners.splice(position, 1); } } return this; }, removeAllListeners: function removeAllListeners(eventName) { if (eventName) { delete this._events[eventName]; } else { this._events = {}; } return this; },/** + */listeners:function listeners(eventName){return this._events[eventName]?this._events[eventName].slice(0):[];},on:function on(eventName,listener,toHead){if(this._events[eventName]){toHead?this._events[eventName].unshift(listener):this._events[eventName].push(listener);}else{this._events[eventName]=[listener];}return this;},onAsync:function onAsync(eventName,listener,toHead){listener._isAsync=true;return this.on(eventName,listener,toHead);},removeListener:function removeListener(eventName,listener){var listeners=this._events[eventName];if(listeners){var length=listeners.length;var position=-1;for(var i=0;i-1){listeners.splice(position,1);}}return this;},removeAllListeners:function removeAllListeners(eventName){if(eventName){delete this._events[eventName];}else{this._events={};}return this;},/** * @api private - */emit: function emit(eventName, eventArgs, doneCallback) { if (!doneCallback) doneCallback = function doneCallback() { }; var listeners = this.listeners(eventName); var count = listeners.length; this.callListeners(listeners, eventArgs, doneCallback); return count > 0; },/** + */emit:function emit(eventName,eventArgs,doneCallback){if(!doneCallback)doneCallback=function doneCallback(){};var listeners=this.listeners(eventName);var count=listeners.length;this.callListeners(listeners,eventArgs,doneCallback);return count>0;},/** * @api private - */callListeners: function callListeners(listeners, args, doneCallback, prevError) { - var self = this; var error = prevError || null; function callNextListener(err) { if (err) { error = AWS.util.error(error || new Error(), err); if (self._haltHandlersOnError) { return doneCallback.call(self, error); } } self.callListeners(listeners, args, doneCallback, error); } while (listeners.length > 0) { - var listener = listeners.shift(); if (listener._isAsync) {// asynchronous listener - listener.apply(self, args.concat([callNextListener])); return;// stop here, callNextListener will continue - } else {// synchronous listener - try { listener.apply(self, args); } catch (err) { error = AWS.util.error(error || new Error(), err); } if (error && self._haltHandlersOnError) { doneCallback.call(self, error); return; } - } - } doneCallback.call(self, error); - },/** + */callListeners:function callListeners(listeners,args,doneCallback,prevError){var self=this;var error=prevError||null;function callNextListener(err){if(err){error=AWS.util.error(error||new Error(),err);if(self._haltHandlersOnError){return doneCallback.call(self,error);}}self.callListeners(listeners,args,doneCallback,error);}while(listeners.length>0){var listener=listeners.shift();if(listener._isAsync){// asynchronous listener +listener.apply(self,args.concat([callNextListener]));return;// stop here, callNextListener will continue +}else{// synchronous listener +try{listener.apply(self,args);}catch(err){error=AWS.util.error(error||new Error(),err);}if(error&&self._haltHandlersOnError){doneCallback.call(self,error);return;}}}doneCallback.call(self,error);},/** * Adds or copies a set of listeners from another list of * listeners or SequentialExecutor object. * @@ -4713,10 +4316,8 @@ * emitter2.addListeners(emitter1); * emitter2.emit('event1'); // emitter2 has event1 * emitter2.emit('event2'); // emitter2 has event2 - */addListeners: function addListeners(listeners) { - var self = this;// extract listeners if parameter is an SequentialExecutor object - if (listeners._events) listeners = listeners._events; AWS.util.each(listeners, function (event, callbacks) { if (typeof callbacks === 'function') callbacks = [callbacks]; AWS.util.arrayEach(callbacks, function (callback) { self.on(event, callback); }); }); return self; - },/** + */addListeners:function addListeners(listeners){var self=this;// extract listeners if parameter is an SequentialExecutor object +if(listeners._events)listeners=listeners._events;AWS.util.each(listeners,function(event,callbacks){if(typeof callbacks==='function')callbacks=[callbacks];AWS.util.arrayEach(callbacks,function(callback){self.on(event,callback);});});return self;},/** * Registers an event with {on} and saves the callback handle function * as a property on the emitter object using a given `name`. * @@ -4731,9 +4332,9 @@ * * // the following prints: true * console.log(emitter.DATA_CALLBACK == listener); - */addNamedListener: function addNamedListener(name, eventName, callback, toHead) { this[name] = callback; this.addListener(eventName, callback, toHead); return this; },/** + */addNamedListener:function addNamedListener(name,eventName,callback,toHead){this[name]=callback;this.addListener(eventName,callback,toHead);return this;},/** * @api private - */addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) { callback._isAsync = true; return this.addNamedListener(name, eventName, callback, toHead); },/** + */addNamedAsyncListener:function addNamedAsyncListener(name,eventName,callback,toHead){callback._isAsync=true;return this.addNamedListener(name,eventName,callback,toHead);},/** * Helper method to add a set of named listeners using * {addNamedListener}. The callback contains a parameter * with a handle to the `addNamedListener` method. @@ -4755,17 +4356,12 @@ * emitter.DATA_CALLBACK; * emitter.OTHER; * emitter.LAST; - */addNamedListeners: function addNamedListeners(callback) { var self = this; callback(function () { self.addNamedListener.apply(self, arguments); }, function () { self.addNamedAsyncListener.apply(self, arguments); }); return this; } - });/** + */addNamedListeners:function addNamedListeners(callback){var self=this;callback(function(){self.addNamedListener.apply(self,arguments);},function(){self.addNamedAsyncListener.apply(self,arguments);});return this;}});/** * {on} is the prefered method. * @api private - */AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;/** + */AWS.SequentialExecutor.prototype.addListener=AWS.SequentialExecutor.prototype.on;/** * @api private - */module.exports = AWS.SequentialExecutor; - }, { "./core": 18 }], 59: [function (require, module, exports) { - (function (process) { - (function () { - var AWS = require('./core'); var Api = require('./model/api'); var regionConfig = require('./region_config'); var inherit = AWS.util.inherit; var clientCount = 0;/** + */module.exports=AWS.SequentialExecutor;},{"./core":18}],59:[function(require,module,exports){(function(process){(function(){var AWS=require('./core');var Api=require('./model/api');var regionConfig=require('./region_config');var inherit=AWS.util.inherit;var clientCount=0;/** * The service class representing an AWS service. * * @class_abstract This class is an abstract class. @@ -4773,35 +4369,30 @@ * @!attribute apiVersions * @return [Array] the list of API versions supported by this service. * @readonly - */AWS.Service = inherit({/** + */AWS.Service=inherit({/** * Create a new service object with a configuration object * * @param config [map] a map of configuration options - */constructor: function Service(config) { if (!this.loadServiceClass) { throw AWS.util.error(new Error(), 'Service must be constructed with `new\' operator'); } var ServiceClass = this.loadServiceClass(config || {}); if (ServiceClass) { var originalConfig = AWS.util.copy(config); var svc = new ServiceClass(config); Object.defineProperty(svc, '_originalConfig', { get: function get() { return originalConfig; }, enumerable: false, configurable: true }); svc._clientId = ++clientCount; return svc; } this.initialize(config); },/** + */constructor:function Service(config){if(!this.loadServiceClass){throw AWS.util.error(new Error(),'Service must be constructed with `new\' operator');}var ServiceClass=this.loadServiceClass(config||{});if(ServiceClass){var originalConfig=AWS.util.copy(config);var svc=new ServiceClass(config);Object.defineProperty(svc,'_originalConfig',{get:function get(){return originalConfig;},enumerable:false,configurable:true});svc._clientId=++clientCount;return svc;}this.initialize(config);},/** * @api private - */initialize: function initialize(config) { - var svcConfig = AWS.config[this.serviceIdentifier]; this.config = new AWS.Config(AWS.config); if (svcConfig) this.config.update(svcConfig, true); if (config) this.config.update(config, true); this.validateService(); if (!this.config.endpoint) regionConfig(this); this.config.endpoint = this.endpointFromTemplate(this.config.endpoint); this.setEndpoint(this.config.endpoint);//enable attaching listeners to service client - AWS.SequentialExecutor.call(this); AWS.Service.addDefaultMonitoringListeners(this); if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) { var publisher = this.publisher; this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) { process.nextTick(function () { publisher.eventHandler(event); }); }); this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) { process.nextTick(function () { publisher.eventHandler(event); }); }); } - },/** + */initialize:function initialize(config){var svcConfig=AWS.config[this.serviceIdentifier];this.config=new AWS.Config(AWS.config);if(svcConfig)this.config.update(svcConfig,true);if(config)this.config.update(config,true);this.validateService();if(!this.config.endpoint)regionConfig(this);this.config.endpoint=this.endpointFromTemplate(this.config.endpoint);this.setEndpoint(this.config.endpoint);//enable attaching listeners to service client +AWS.SequentialExecutor.call(this);AWS.Service.addDefaultMonitoringListeners(this);if((this.config.clientSideMonitoring||AWS.Service._clientSideMonitoring)&&this.publisher){var publisher=this.publisher;this.addNamedListener('PUBLISH_API_CALL','apiCall',function PUBLISH_API_CALL(event){process.nextTick(function(){publisher.eventHandler(event);});});this.addNamedListener('PUBLISH_API_ATTEMPT','apiCallAttempt',function PUBLISH_API_ATTEMPT(event){process.nextTick(function(){publisher.eventHandler(event);});});}},/** * @api private - */validateService: function validateService() { },/** + */validateService:function validateService(){},/** * @api private - */loadServiceClass: function loadServiceClass(serviceConfig) { var config = serviceConfig; if (!AWS.util.isEmpty(this.api)) { return null; } else if (config.apiConfig) { return AWS.Service.defineServiceApi(this.constructor, config.apiConfig); } else if (!this.constructor.services) { return null; } else { config = new AWS.Config(AWS.config); config.update(serviceConfig, true); var version = config.apiVersions[this.constructor.serviceIdentifier]; version = version || config.apiVersion; return this.getLatestServiceClass(version); } },/** + */loadServiceClass:function loadServiceClass(serviceConfig){var config=serviceConfig;if(!AWS.util.isEmpty(this.api)){return null;}else if(config.apiConfig){return AWS.Service.defineServiceApi(this.constructor,config.apiConfig);}else if(!this.constructor.services){return null;}else{config=new AWS.Config(AWS.config);config.update(serviceConfig,true);var version=config.apiVersions[this.constructor.serviceIdentifier];version=version||config.apiVersion;return this.getLatestServiceClass(version);}},/** * @api private - */getLatestServiceClass: function getLatestServiceClass(version) { version = this.getLatestServiceVersion(version); if (this.constructor.services[version] === null) { AWS.Service.defineServiceApi(this.constructor, version); } return this.constructor.services[version]; },/** + */getLatestServiceClass:function getLatestServiceClass(version){version=this.getLatestServiceVersion(version);if(this.constructor.services[version]===null){AWS.Service.defineServiceApi(this.constructor,version);}return this.constructor.services[version];},/** * @api private - */getLatestServiceVersion: function getLatestServiceVersion(version) { - if (!this.constructor.services || this.constructor.services.length === 0) { throw new Error('No services defined on ' + this.constructor.serviceIdentifier); } if (!version) { version = 'latest'; } else if (AWS.util.isType(version, Date)) { version = AWS.util.date.iso8601(version).split('T')[0]; } if (Object.hasOwnProperty(this.constructor.services, version)) { return version; } var keys = Object.keys(this.constructor.services).sort(); var selectedVersion = null; for (var i = keys.length - 1; i >= 0; i--) {// versions that end in "*" are not available on disk and can be - // skipped, so do not choose these as selectedVersions - if (keys[i][keys[i].length - 1] !== '*') { selectedVersion = keys[i]; } if (keys[i].substr(0, 10) <= version) { return selectedVersion; } - } throw new Error('Could not find ' + this.constructor.serviceIdentifier + ' API to satisfy version constraint `' + version + '\''); - },/** + */getLatestServiceVersion:function getLatestServiceVersion(version){if(!this.constructor.services||this.constructor.services.length===0){throw new Error('No services defined on '+this.constructor.serviceIdentifier);}if(!version){version='latest';}else if(AWS.util.isType(version,Date)){version=AWS.util.date.iso8601(version).split('T')[0];}if(Object.hasOwnProperty(this.constructor.services,version)){return version;}var keys=Object.keys(this.constructor.services).sort();var selectedVersion=null;for(var i=keys.length-1;i>=0;i--){// versions that end in "*" are not available on disk and can be +// skipped, so do not choose these as selectedVersions +if(keys[i][keys[i].length-1]!=='*'){selectedVersion=keys[i];}if(keys[i].substr(0,10)<=version){return selectedVersion;}}throw new Error('Could not find '+this.constructor.serviceIdentifier+' API to satisfy version constraint `'+version+'\'');},/** * @api private - */api: {},/** + */api:{},/** * @api private - */defaultRetryCount: 3,/** + */defaultRetryCount:3,/** * @api private - */customizeRequests: function customizeRequests(callback) { if (!callback) { this.customRequestHandler = null; } else if (typeof callback === 'function') { this.customRequestHandler = callback; } else { throw new Error('Invalid callback type \'' + _typeof(callback) + '\' provided in customizeRequests'); } },/** + */customizeRequests:function customizeRequests(callback){if(!callback){this.customRequestHandler=null;}else if(typeof callback==='function'){this.customRequestHandler=callback;}else{throw new Error('Invalid callback type \''+_typeof(callback)+'\' provided in customizeRequests');}},/** * Calls an operation on a service with the given input parameters. * * @param operation [String] the name of the operation to call on the service. @@ -4813,11 +4404,8 @@ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */makeRequest: function makeRequest(operation, params, callback) { - if (typeof params === 'function') { callback = params; params = null; } params = params || {}; if (this.config.params) {// copy only toplevel bound params - var rules = this.api.operations[operation]; if (rules) { params = AWS.util.copy(params); AWS.util.each(this.config.params, function (key, value) { if (rules.input.members[key]) { if (params[key] === undefined || params[key] === null) { params[key] = value; } } }); } - } var request = new AWS.Request(this, operation, params); this.addAllRequestListeners(request); this.attachMonitoringEmitter(request); if (callback) request.send(callback); return request; - },/** + */makeRequest:function makeRequest(operation,params,callback){if(typeof params==='function'){callback=params;params=null;}params=params||{};if(this.config.params){// copy only toplevel bound params +var rules=this.api.operations[operation];if(rules){params=AWS.util.copy(params);AWS.util.each(this.config.params,function(key,value){if(rules.input.members[key]){if(params[key]===undefined||params[key]===null){params[key]=value;}}});}}var request=new AWS.Request(this,operation,params);this.addAllRequestListeners(request);this.attachMonitoringEmitter(request);if(callback)request.send(callback);return request;},/** * Calls an operation on a service with the given input parameters, without * any authentication data. This method is useful for "public" API operations. * @@ -4830,7 +4418,7 @@ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) { if (typeof params === 'function') { callback = params; params = {}; } var request = this.makeRequest(operation, params).toUnauthenticated(); return callback ? request.send(callback) : request; },/** + */makeUnauthenticatedRequest:function makeUnauthenticatedRequest(operation,params,callback){if(typeof params==='function'){callback=params;params={};}var request=this.makeRequest(operation,params).toUnauthenticated();return callback?request.send(callback):request;},/** * Waits for a given state * * @param state [String] the state on the service to wait for @@ -4847,101 +4435,87 @@ * Set to `null` if the request is successful. * @param data [Object] the de-serialized data returned from * the request. Set to `null` if a request error occurs. - */waitFor: function waitFor(state, params, callback) { var waiter = new AWS.ResourceWaiter(this, state); return waiter.wait(params, callback); },/** + */waitFor:function waitFor(state,params,callback){var waiter=new AWS.ResourceWaiter(this,state);return waiter.wait(params,callback);},/** * @api private - */addAllRequestListeners: function addAllRequestListeners(request) { - var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(), AWS.EventListeners.CorePost]; for (var i = 0; i < list.length; i++) { if (list[i]) request.addListeners(list[i]); }// disable parameter validation - if (!this.config.paramValidation) { request.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS); } if (this.config.logger) {// add logging events - request.addListeners(AWS.EventListeners.Logger); - } this.setupRequestListeners(request);// call prototype's customRequestHandler - if (typeof this.constructor.prototype.customRequestHandler === 'function') { this.constructor.prototype.customRequestHandler(request); }// call instance's customRequestHandler - if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') { this.customRequestHandler(request); } - },/** + */addAllRequestListeners:function addAllRequestListeners(request){var list=[AWS.events,AWS.EventListeners.Core,this.serviceInterface(),AWS.EventListeners.CorePost];for(var i=0;i 299) { if (error.code) monitoringEvent.FinalAwsException = error.code; if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message; } else { if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name; if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message; } } return monitoringEvent; },/** + */apiCallEvent:function apiCallEvent(request){var api=request.service.api.operations[request.operation];var monitoringEvent={Type:'ApiCall',Api:api?api.name:request.operation,Version:1,Service:request.service.api.serviceId||request.service.api.endpointPrefix,Region:request.httpRequest.region,MaxRetriesExceeded:0,UserAgent:request.httpRequest.getUserAgent()};var response=request.response;if(response.httpResponse.statusCode){monitoringEvent.FinalHttpStatusCode=response.httpResponse.statusCode;}if(response.error){var error=response.error;var statusCode=response.httpResponse.statusCode;if(statusCode>299){if(error.code)monitoringEvent.FinalAwsException=error.code;if(error.message)monitoringEvent.FinalAwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.FinalSdkException=error.code||error.name;if(error.message)monitoringEvent.FinalSdkExceptionMessage=error.message;}}return monitoringEvent;},/** * Event recording metrics for an API call attempt. * @returns {object} a subset of api call attempt metrics * @api private - */apiAttemptEvent: function apiAttemptEvent(request) { var api = request.service.api.operations[request.operation]; var monitoringEvent = { Type: 'ApiCallAttempt', Api: api ? api.name : request.operation, Version: 1, Service: request.service.api.serviceId || request.service.api.endpointPrefix, Fqdn: request.httpRequest.endpoint.hostname, UserAgent: request.httpRequest.getUserAgent() }; var response = request.response; if (response.httpResponse.statusCode) { monitoringEvent.HttpStatusCode = response.httpResponse.statusCode; } if (!request._unAuthenticated && request.service.config.credentials && request.service.config.credentials.accessKeyId) { monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId; } if (!response.httpResponse.headers) return monitoringEvent; if (request.httpRequest.headers['x-amz-security-token']) { monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token']; } if (response.httpResponse.headers['x-amzn-requestid']) { monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid']; } if (response.httpResponse.headers['x-amz-request-id']) { monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id']; } if (response.httpResponse.headers['x-amz-id-2']) { monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2']; } return monitoringEvent; },/** + */apiAttemptEvent:function apiAttemptEvent(request){var api=request.service.api.operations[request.operation];var monitoringEvent={Type:'ApiCallAttempt',Api:api?api.name:request.operation,Version:1,Service:request.service.api.serviceId||request.service.api.endpointPrefix,Fqdn:request.httpRequest.endpoint.hostname,UserAgent:request.httpRequest.getUserAgent()};var response=request.response;if(response.httpResponse.statusCode){monitoringEvent.HttpStatusCode=response.httpResponse.statusCode;}if(!request._unAuthenticated&&request.service.config.credentials&&request.service.config.credentials.accessKeyId){monitoringEvent.AccessKey=request.service.config.credentials.accessKeyId;}if(!response.httpResponse.headers)return monitoringEvent;if(request.httpRequest.headers['x-amz-security-token']){monitoringEvent.SessionToken=request.httpRequest.headers['x-amz-security-token'];}if(response.httpResponse.headers['x-amzn-requestid']){monitoringEvent.XAmznRequestId=response.httpResponse.headers['x-amzn-requestid'];}if(response.httpResponse.headers['x-amz-request-id']){monitoringEvent.XAmzRequestId=response.httpResponse.headers['x-amz-request-id'];}if(response.httpResponse.headers['x-amz-id-2']){monitoringEvent.XAmzId2=response.httpResponse.headers['x-amz-id-2'];}return monitoringEvent;},/** * Add metrics of failed request. * @api private - */attemptFailEvent: function attemptFailEvent(request) { var monitoringEvent = this.apiAttemptEvent(request); var response = request.response; var error = response.error; if (response.httpResponse.statusCode > 299) { if (error.code) monitoringEvent.AwsException = error.code; if (error.message) monitoringEvent.AwsExceptionMessage = error.message; } else { if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name; if (error.message) monitoringEvent.SdkExceptionMessage = error.message; } return monitoringEvent; },/** + */attemptFailEvent:function attemptFailEvent(request){var monitoringEvent=this.apiAttemptEvent(request);var response=request.response;var error=response.error;if(response.httpResponse.statusCode>299){if(error.code)monitoringEvent.AwsException=error.code;if(error.message)monitoringEvent.AwsExceptionMessage=error.message;}else{if(error.code||error.name)monitoringEvent.SdkException=error.code||error.name;if(error.message)monitoringEvent.SdkExceptionMessage=error.message;}return monitoringEvent;},/** * Attach listeners to request object to fetch metrics of each request * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events. * @api private - */attachMonitoringEmitter: function attachMonitoringEmitter(request) { - var attemptTimestamp;//timestamp marking the beginning of a request attempt - var attemptStartRealTime;//Start time of request attempt. Used to calculating attemptLatency - var attemptLatency;//latency from request sent out to http response reaching SDK - var callStartRealTime;//Start time of API call. Used to calculating API call latency - var attemptCount = 0;//request.retryCount is not reliable here - var region;//region cache region for each attempt since it can be updated in plase (e.g. s3) - var callTimestamp;//timestamp when the request is created - var self = this; var addToHead = true; request.on('validate', function () { callStartRealTime = AWS.util.realClock.now(); callTimestamp = Date.now(); }, addToHead); request.on('sign', function () { attemptStartRealTime = AWS.util.realClock.now(); attemptTimestamp = Date.now(); region = request.httpRequest.region; attemptCount++; }, addToHead); request.on('validateResponse', function () { attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime); }); request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() { var apiAttemptEvent = self.apiAttemptEvent(request); apiAttemptEvent.Timestamp = attemptTimestamp; apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; apiAttemptEvent.Region = region; self.emit('apiCallAttempt', [apiAttemptEvent]); }); request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() { - var apiAttemptEvent = self.attemptFailEvent(request); apiAttemptEvent.Timestamp = attemptTimestamp;//attemptLatency may not be available if fail before response - attemptLatency = attemptLatency || Math.round(AWS.util.realClock.now() - attemptStartRealTime); apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0; apiAttemptEvent.Region = region; self.emit('apiCallAttempt', [apiAttemptEvent]); - }); request.addNamedListener('API_CALL', 'complete', function API_CALL() { var apiCallEvent = self.apiCallEvent(request); apiCallEvent.AttemptCount = attemptCount; if (apiCallEvent.AttemptCount <= 0) return; apiCallEvent.Timestamp = callTimestamp; var latency = Math.round(AWS.util.realClock.now() - callStartRealTime); apiCallEvent.Latency = latency >= 0 ? latency : 0; var response = request.response; if (typeof response.retryCount === 'number' && typeof response.maxRetries === 'number' && response.retryCount >= response.maxRetries) { apiCallEvent.MaxRetriesExceeded = 1; } self.emit('apiCall', [apiCallEvent]); }); - },/** + */attachMonitoringEmitter:function attachMonitoringEmitter(request){var attemptTimestamp;//timestamp marking the beginning of a request attempt +var attemptStartRealTime;//Start time of request attempt. Used to calculating attemptLatency +var attemptLatency;//latency from request sent out to http response reaching SDK +var callStartRealTime;//Start time of API call. Used to calculating API call latency +var attemptCount=0;//request.retryCount is not reliable here +var region;//region cache region for each attempt since it can be updated in plase (e.g. s3) +var callTimestamp;//timestamp when the request is created +var self=this;var addToHead=true;request.on('validate',function(){callStartRealTime=AWS.util.realClock.now();callTimestamp=Date.now();},addToHead);request.on('sign',function(){attemptStartRealTime=AWS.util.realClock.now();attemptTimestamp=Date.now();region=request.httpRequest.region;attemptCount++;},addToHead);request.on('validateResponse',function(){attemptLatency=Math.round(AWS.util.realClock.now()-attemptStartRealTime);});request.addNamedListener('API_CALL_ATTEMPT','success',function API_CALL_ATTEMPT(){var apiAttemptEvent=self.apiAttemptEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL_ATTEMPT_RETRY','retry',function API_CALL_ATTEMPT_RETRY(){var apiAttemptEvent=self.attemptFailEvent(request);apiAttemptEvent.Timestamp=attemptTimestamp;//attemptLatency may not be available if fail before response +attemptLatency=attemptLatency||Math.round(AWS.util.realClock.now()-attemptStartRealTime);apiAttemptEvent.AttemptLatency=attemptLatency>=0?attemptLatency:0;apiAttemptEvent.Region=region;self.emit('apiCallAttempt',[apiAttemptEvent]);});request.addNamedListener('API_CALL','complete',function API_CALL(){var apiCallEvent=self.apiCallEvent(request);apiCallEvent.AttemptCount=attemptCount;if(apiCallEvent.AttemptCount<=0)return;apiCallEvent.Timestamp=callTimestamp;var latency=Math.round(AWS.util.realClock.now()-callStartRealTime);apiCallEvent.Latency=latency>=0?latency:0;var response=request.response;if(typeof response.retryCount==='number'&&typeof response.maxRetries==='number'&&response.retryCount>=response.maxRetries){apiCallEvent.MaxRetriesExceeded=1;}self.emit('apiCall',[apiCallEvent]);});},/** * Override this method to setup any custom request listeners for each * new request to the service. * * @method_abstract This is an abstract method. - */setupRequestListeners: function setupRequestListeners(request) { },/** + */setupRequestListeners:function setupRequestListeners(request){},/** * Gets the signer class for a given request * @api private - */getSignerClass: function getSignerClass(request) { - var version;// get operation authtype if present - var operation = null; var authtype = ''; if (request) { var operations = request.service.api.operations || {}; operation = operations[request.operation] || null; authtype = operation ? operation.authtype : ''; } if (this.config.signatureVersion) { version = this.config.signatureVersion; } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') { version = 'v4'; } else { version = this.api.signatureVersion; } return AWS.Signers.RequestSigner.getVersion(version); - },/** + */getSignerClass:function getSignerClass(request){var version;// get operation authtype if present +var operation=null;var authtype='';if(request){var operations=request.service.api.operations||{};operation=operations[request.operation]||null;authtype=operation?operation.authtype:'';}if(this.config.signatureVersion){version=this.config.signatureVersion;}else if(authtype==='v4'||authtype==='v4-unsigned-body'){version='v4';}else{version=this.api.signatureVersion;}return AWS.Signers.RequestSigner.getVersion(version);},/** * @api private - */serviceInterface: function serviceInterface() { switch (this.api.protocol) { case 'ec2': return AWS.EventListeners.Query; case 'query': return AWS.EventListeners.Query; case 'json': return AWS.EventListeners.Json; case 'rest-json': return AWS.EventListeners.RestJson; case 'rest-xml': return AWS.EventListeners.RestXml; }if (this.api.protocol) { throw new Error('Invalid service `protocol\' ' + this.api.protocol + ' in API config'); } },/** + */serviceInterface:function serviceInterface(){switch(this.api.protocol){case'ec2':return AWS.EventListeners.Query;case'query':return AWS.EventListeners.Query;case'json':return AWS.EventListeners.Json;case'rest-json':return AWS.EventListeners.RestJson;case'rest-xml':return AWS.EventListeners.RestXml;}if(this.api.protocol){throw new Error('Invalid service `protocol\' '+this.api.protocol+' in API config');}},/** * @api private - */successfulResponse: function successfulResponse(resp) { return resp.httpResponse.statusCode < 300; },/** + */successfulResponse:function successfulResponse(resp){return resp.httpResponse.statusCode<300;},/** * How many times a failed request should be retried before giving up. * the defaultRetryCount can be overriden by service classes. * * @api private - */numRetries: function numRetries() { if (this.config.maxRetries !== undefined) { return this.config.maxRetries; } else { return this.defaultRetryCount; } },/** + */numRetries:function numRetries(){if(this.config.maxRetries!==undefined){return this.config.maxRetries;}else{return this.defaultRetryCount;}},/** * @api private - */retryDelays: function retryDelays(retryCount) { return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions); },/** + */retryDelays:function retryDelays(retryCount){return AWS.util.calculateRetryDelay(retryCount,this.config.retryDelayOptions);},/** * @api private - */retryableError: function retryableError(error) { if (this.timeoutError(error)) return true; if (this.networkingError(error)) return true; if (this.expiredCredentialsError(error)) return true; if (this.throttledError(error)) return true; if (error.statusCode >= 500) return true; return false; },/** + */retryableError:function retryableError(error){if(this.timeoutError(error))return true;if(this.networkingError(error))return true;if(this.expiredCredentialsError(error))return true;if(this.throttledError(error))return true;if(error.statusCode>=500)return true;return false;},/** * @api private - */networkingError: function networkingError(error) { return error.code === 'NetworkingError'; },/** + */networkingError:function networkingError(error){return error.code==='NetworkingError';},/** * @api private - */timeoutError: function timeoutError(error) { return error.code === 'TimeoutError'; },/** + */timeoutError:function timeoutError(error){return error.code==='TimeoutError';},/** * @api private - */expiredCredentialsError: function expiredCredentialsError(error) {// TODO : this only handles *one* of the expired credential codes - return error.code === 'ExpiredTokenException'; - },/** + */expiredCredentialsError:function expiredCredentialsError(error){// TODO : this only handles *one* of the expired credential codes +return error.code==='ExpiredTokenException';},/** * @api private - */clockSkewError: function clockSkewError(error) { switch (error.code) { case 'RequestTimeTooSkewed': case 'RequestExpired': case 'InvalidSignatureException': case 'SignatureDoesNotMatch': case 'AuthFailure': case 'RequestInTheFuture': return true; default: return false; } },/** + */clockSkewError:function clockSkewError(error){switch(error.code){case'RequestTimeTooSkewed':case'RequestExpired':case'InvalidSignatureException':case'SignatureDoesNotMatch':case'AuthFailure':case'RequestInTheFuture':return true;default:return false;}},/** * @api private - */getSkewCorrectedDate: function getSkewCorrectedDate() { return new Date(Date.now() + this.config.systemClockOffset); },/** + */getSkewCorrectedDate:function getSkewCorrectedDate(){return new Date(Date.now()+this.config.systemClockOffset);},/** * @api private - */applyClockOffset: function applyClockOffset(newServerTime) { if (newServerTime) { this.config.systemClockOffset = newServerTime - Date.now(); } },/** + */applyClockOffset:function applyClockOffset(newServerTime){if(newServerTime){this.config.systemClockOffset=newServerTime-Date.now();}},/** * @api private - */isClockSkewed: function isClockSkewed(newServerTime) { if (newServerTime) { return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000; } },/** + */isClockSkewed:function isClockSkewed(newServerTime){if(newServerTime){return Math.abs(this.getSkewCorrectedDate().getTime()-newServerTime)>=30000;}},/** * @api private - */throttledError: function throttledError(error) {// this logic varies between services - if (error.statusCode === 429) return true; switch (error.code) { - case 'ProvisionedThroughputExceededException': case 'Throttling': case 'ThrottlingException': case 'RequestLimitExceeded': case 'RequestThrottled': case 'RequestThrottledException': case 'TooManyRequestsException': case 'TransactionInProgressException'://dynamodb - return true; default: return false; - } - },/** + */throttledError:function throttledError(error){// this logic varies between services +if(error.statusCode===429)return true;switch(error.code){case'ProvisionedThroughputExceededException':case'Throttling':case'ThrottlingException':case'RequestLimitExceeded':case'RequestThrottled':case'RequestThrottledException':case'TooManyRequestsException':case'TransactionInProgressException'://dynamodb +return true;default:return false;}},/** * @api private - */endpointFromTemplate: function endpointFromTemplate(endpoint) { if (typeof endpoint !== 'string') return endpoint; var e = endpoint; e = e.replace(/\{service\}/g, this.api.endpointPrefix); e = e.replace(/\{region\}/g, this.config.region); e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http'); return e; },/** + */endpointFromTemplate:function endpointFromTemplate(endpoint){if(typeof endpoint!=='string')return endpoint;var e=endpoint;e=e.replace(/\{service\}/g,this.api.endpointPrefix);e=e.replace(/\{region\}/g,this.config.region);e=e.replace(/\{scheme\}/g,this.config.sslEnabled?'https':'http');return e;},/** * @api private - */setEndpoint: function setEndpoint(endpoint) { this.endpoint = new AWS.Endpoint(endpoint, this.config); },/** + */setEndpoint:function setEndpoint(endpoint){this.endpoint=new AWS.Endpoint(endpoint,this.config);},/** * @api private - */paginationConfig: function paginationConfig(operation, throwException) { var paginator = this.api.operations[operation].paginator; if (!paginator) { if (throwException) { var e = new Error(); throw AWS.util.error(e, 'No pagination configuration for ' + operation); } return null; } return paginator; } - }); AWS.util.update(AWS.Service, {/** + */paginationConfig:function paginationConfig(operation,throwException){var paginator=this.api.operations[operation].paginator;if(!paginator){if(throwException){var e=new Error();throw AWS.util.error(e,'No pagination configuration for '+operation);}return null;}return paginator;}});AWS.util.update(AWS.Service,{/** * Adds one method for each operation described in the api configuration * * @api private - */defineMethods: function defineMethods(svc) { AWS.util.each(svc.prototype.api.operations, function iterator(method) { if (svc.prototype[method]) return; var operation = svc.prototype.api.operations[method]; if (operation.authtype === 'none') { svc.prototype[method] = function (params, callback) { return this.makeUnauthenticatedRequest(method, params, callback); }; } else { svc.prototype[method] = function (params, callback) { return this.makeRequest(method, params, callback); }; } }); },/** + */defineMethods:function defineMethods(svc){AWS.util.each(svc.prototype.api.operations,function iterator(method){if(svc.prototype[method])return;var operation=svc.prototype.api.operations[method];if(operation.authtype==='none'){svc.prototype[method]=function(params,callback){return this.makeUnauthenticatedRequest(method,params,callback);};}else{svc.prototype[method]=function(params,callback){return this.makeRequest(method,params,callback);};}});},/** * Defines a new Service class using a service identifier and list of versions * including an optional set of features (functions) to apply to the class * prototype. @@ -4951,40 +4525,27 @@ * service * @param features [Object] an object to attach to the prototype * @return [Class] the service class defined by this function. - */defineService: function defineService(serviceIdentifier, versions, features) { - AWS.Service._serviceMap[serviceIdentifier] = true; if (!Array.isArray(versions)) { features = versions; versions = []; } var svc = inherit(AWS.Service, features || {}); if (typeof serviceIdentifier === 'string') { AWS.Service.addVersions(svc, versions); var identifier = svc.serviceIdentifier || serviceIdentifier; svc.serviceIdentifier = identifier; } else {// defineService called with an API - svc.prototype.api = serviceIdentifier; AWS.Service.defineMethods(svc); - } AWS.SequentialExecutor.call(this.prototype);//util.clientSideMonitoring is only available in node - if (!this.prototype.publisher && AWS.util.clientSideMonitoring) { - var Publisher = AWS.util.clientSideMonitoring.Publisher; var configProvider = AWS.util.clientSideMonitoring.configProvider; var publisherConfig = configProvider(); this.prototype.publisher = new Publisher(publisherConfig); if (publisherConfig.enabled) {//if csm is enabled in environment, SDK should send all metrics - AWS.Service._clientSideMonitoring = true; - } - } AWS.SequentialExecutor.call(svc.prototype); AWS.Service.addDefaultMonitoringListeners(svc.prototype); return svc; - },/** + */defineService:function defineService(serviceIdentifier,versions,features){AWS.Service._serviceMap[serviceIdentifier]=true;if(!Array.isArray(versions)){features=versions;versions=[];}var svc=inherit(AWS.Service,features||{});if(typeof serviceIdentifier==='string'){AWS.Service.addVersions(svc,versions);var identifier=svc.serviceIdentifier||serviceIdentifier;svc.serviceIdentifier=identifier;}else{// defineService called with an API +svc.prototype.api=serviceIdentifier;AWS.Service.defineMethods(svc);}AWS.SequentialExecutor.call(this.prototype);//util.clientSideMonitoring is only available in node +if(!this.prototype.publisher&&AWS.util.clientSideMonitoring){var Publisher=AWS.util.clientSideMonitoring.Publisher;var configProvider=AWS.util.clientSideMonitoring.configProvider;var publisherConfig=configProvider();this.prototype.publisher=new Publisher(publisherConfig);if(publisherConfig.enabled){//if csm is enabled in environment, SDK should send all metrics +AWS.Service._clientSideMonitoring=true;}}AWS.SequentialExecutor.call(svc.prototype);AWS.Service.addDefaultMonitoringListeners(svc.prototype);return svc;},/** * @api private - */addVersions: function addVersions(svc, versions) { if (!Array.isArray(versions)) versions = [versions]; svc.services = svc.services || {}; for (var i = 0; i < versions.length; i++) { if (svc.services[versions[i]] === undefined) { svc.services[versions[i]] = null; } } svc.apiVersions = Object.keys(svc.services).sort(); },/** + */addVersions:function addVersions(svc,versions){if(!Array.isArray(versions))versions=[versions];svc.services=svc.services||{};for(var i=0;i= 0) { this.config.stsRegionalEndpoints = configValue.toLowerCase(); return; } else { throw AWS.util.error(new Error(), errorOptions); } },/** + */validateRegionalEndpointsFlagValue:function validateRegionalEndpointsFlagValue(configValue,errorOptions){if(typeof configValue==='string'&&['legacy','regional'].indexOf(configValue.toLowerCase())>=0){this.config.stsRegionalEndpoints=configValue.toLowerCase();return;}else{throw AWS.util.error(new Error(),errorOptions);}},/** * @api private - */validateRegionalEndpointsFlag: function validateRegionalEndpointsFlag() {//validate config value - var config = this.config; if (config.stsRegionalEndpoints) { this.validateRegionalEndpointsFlagValue(config.stsRegionalEndpoints, { code: 'InvalidConfiguration', message: 'invalid "stsRegionalEndpoints" configuration. Expect "legacy" ' + ' or "regional". Got "' + config.stsRegionalEndpoints + '".' }); } if (!AWS.util.isNode()) return;//validate environmental variable - if (Object.prototype.hasOwnProperty.call(process.env, ENV_REGIONAL_ENDPOINT_ENABLED)) { var envFlag = process.env[ENV_REGIONAL_ENDPOINT_ENABLED]; this.validateRegionalEndpointsFlagValue(envFlag, { code: 'InvalidEnvironmentalVariable', message: 'invalid ' + ENV_REGIONAL_ENDPOINT_ENABLED + ' environmental variable. Expect "legacy" ' + ' or "regional". Got "' + process.env[ENV_REGIONAL_ENDPOINT_ENABLED] + '".' }); }//validate shared config file - var profile = {}; try { var profiles = AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader); profile = profiles[process.env.AWS_PROFILE || AWS.util.defaultProfile]; } catch (e) { }; if (profile && Object.prototype.hasOwnProperty.call(profile, CONFIG_REGIONAL_ENDPOINT_ENABLED)) { var fileFlag = profile[CONFIG_REGIONAL_ENDPOINT_ENABLED]; this.validateRegionalEndpointsFlagValue(fileFlag, { code: 'InvalidConfiguration', message: 'invalid ' + CONFIG_REGIONAL_ENDPOINT_ENABLED + ' profile config. Expect "legacy" ' + ' or "regional". Got "' + profile[CONFIG_REGIONAL_ENDPOINT_ENABLED] + '".' }); } - },/** + */validateRegionalEndpointsFlag:function validateRegionalEndpointsFlag(){//validate config value +var config=this.config;if(config.stsRegionalEndpoints){this.validateRegionalEndpointsFlagValue(config.stsRegionalEndpoints,{code:'InvalidConfiguration',message:'invalid "stsRegionalEndpoints" configuration. Expect "legacy" '+' or "regional". Got "'+config.stsRegionalEndpoints+'".'});}if(!AWS.util.isNode())return;//validate environmental variable +if(Object.prototype.hasOwnProperty.call(process.env,ENV_REGIONAL_ENDPOINT_ENABLED)){var envFlag=process.env[ENV_REGIONAL_ENDPOINT_ENABLED];this.validateRegionalEndpointsFlagValue(envFlag,{code:'InvalidEnvironmentalVariable',message:'invalid '+ENV_REGIONAL_ENDPOINT_ENABLED+' environmental variable. Expect "legacy" '+' or "regional". Got "'+process.env[ENV_REGIONAL_ENDPOINT_ENABLED]+'".'});}//validate shared config file +var profile={};try{var profiles=AWS.util.getProfilesFromSharedConfig(AWS.util.iniLoader);profile=profiles[process.env.AWS_PROFILE||AWS.util.defaultProfile];}catch(e){};if(profile&&Object.prototype.hasOwnProperty.call(profile,CONFIG_REGIONAL_ENDPOINT_ENABLED)){var fileFlag=profile[CONFIG_REGIONAL_ENDPOINT_ENABLED];this.validateRegionalEndpointsFlagValue(fileFlag,{code:'InvalidConfiguration',message:'invalid '+CONFIG_REGIONAL_ENDPOINT_ENABLED+' profile config. Expect "legacy" '+' or "regional". Got "'+profile[CONFIG_REGIONAL_ENDPOINT_ENABLED]+'".'});}},/** * @api private - */optInRegionalEndpoint: function optInRegionalEndpoint() { - this.validateRegionalEndpointsFlag(); var config = this.config; if (config.stsRegionalEndpoints === 'regional') { - regionConfig(this); if (!this.isGlobalEndpoint) return; this.isGlobalEndpoint = false;//client will throw if region is not supplied; request will be signed with specified region - if (!config.region) { throw AWS.util.error(new Error(), { code: 'ConfigError', message: 'Missing region in config' }); } var insertPoint = config.endpoint.indexOf('.amazonaws.com'); config.endpoint = config.endpoint.substring(0, insertPoint) + '.' + config.region + config.endpoint.substring(insertPoint); - } - }, validateService: function validateService() { this.optInRegionalEndpoint(); } - }); - }).call(this); - }).call(this, require('_process')); - }, { "../core": 18, "../region_config": 53, "_process": 86 }], 62: [function (require, module, exports) { - var AWS = require('../core'); var inherit = AWS.util.inherit;/** + */optInRegionalEndpoint:function optInRegionalEndpoint(){this.validateRegionalEndpointsFlag();var config=this.config;if(config.stsRegionalEndpoints==='regional'){regionConfig(this);if(!this.isGlobalEndpoint)return;this.isGlobalEndpoint=false;//client will throw if region is not supplied; request will be signed with specified region +if(!config.region){throw AWS.util.error(new Error(),{code:'ConfigError',message:'Missing region in config'});}var insertPoint=config.endpoint.indexOf('.amazonaws.com');config.endpoint=config.endpoint.substring(0,insertPoint)+'.'+config.region+config.endpoint.substring(insertPoint);}},validateService:function validateService(){this.optInRegionalEndpoint();}});}).call(this);}).call(this,require('_process'));},{"../core":18,"../region_config":53,"_process":86}],62:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** * @api private - */var expiresHeader = 'presigned-expires';/** + */var expiresHeader='presigned-expires';/** * @api private - */function signedUrlBuilder(request) { - var expires = request.httpRequest.headers[expiresHeader]; var signerClass = request.service.getSignerClass(request); delete request.httpRequest.headers['User-Agent']; delete request.httpRequest.headers['X-Amz-User-Agent']; if (signerClass === AWS.Signers.V4) { - if (expires > 604800) {// one week expiry is invalid - var message = 'Presigning does not support expiry time greater ' + 'than a week with SigV4 signing.'; throw AWS.util.error(new Error(), { code: 'InvalidExpiryTime', message: message, retryable: false }); - } request.httpRequest.headers[expiresHeader] = expires; - } else if (signerClass === AWS.Signers.S3) { var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate(); request.httpRequest.headers[expiresHeader] = parseInt(AWS.util.date.unixTimestamp(now) + expires, 10).toString(); } else { throw AWS.util.error(new Error(), { message: 'Presigning only supports S3 or SigV4 signing.', code: 'UnsupportedSigner', retryable: false }); } - }/** + */function signedUrlBuilder(request){var expires=request.httpRequest.headers[expiresHeader];var signerClass=request.service.getSignerClass(request);delete request.httpRequest.headers['User-Agent'];delete request.httpRequest.headers['X-Amz-User-Agent'];if(signerClass===AWS.Signers.V4){if(expires>604800){// one week expiry is invalid +var message='Presigning does not support expiry time greater '+'than a week with SigV4 signing.';throw AWS.util.error(new Error(),{code:'InvalidExpiryTime',message:message,retryable:false});}request.httpRequest.headers[expiresHeader]=expires;}else if(signerClass===AWS.Signers.S3){var now=request.service?request.service.getSkewCorrectedDate():AWS.util.date.getDate();request.httpRequest.headers[expiresHeader]=parseInt(AWS.util.date.unixTimestamp(now)+expires,10).toString();}else{throw AWS.util.error(new Error(),{message:'Presigning only supports S3 or SigV4 signing.',code:'UnsupportedSigner',retryable:false});}}/** * @api private - */function signedUrlSigner(request) { - var endpoint = request.httpRequest.endpoint; var parsedUrl = AWS.util.urlParse(request.httpRequest.path); var queryParams = {}; if (parsedUrl.search) { queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1)); } var auth = request.httpRequest.headers['Authorization'].split(' '); if (auth[0] === 'AWS') { - auth = auth[1].split(':'); queryParams['AWSAccessKeyId'] = auth[0]; queryParams['Signature'] = auth[1]; AWS.util.each(request.httpRequest.headers, function (key, value) { - if (key === expiresHeader) key = 'Expires'; if (key.indexOf('x-amz-meta-') === 0) {// Delete existing, potentially not normalized key - delete queryParams[key]; key = key.toLowerCase(); - } queryParams[key] = value; - }); delete request.httpRequest.headers[expiresHeader]; delete queryParams['Authorization']; delete queryParams['Host']; - } else if (auth[0] === 'AWS4-HMAC-SHA256') {// SigV4 signing - auth.shift(); var rest = auth.join(' '); var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1]; queryParams['X-Amz-Signature'] = signature; delete queryParams['Expires']; - }// build URL - endpoint.pathname = parsedUrl.pathname; endpoint.search = AWS.util.queryParamsToString(queryParams); - }/** + */function signedUrlSigner(request){var endpoint=request.httpRequest.endpoint;var parsedUrl=AWS.util.urlParse(request.httpRequest.path);var queryParams={};if(parsedUrl.search){queryParams=AWS.util.queryStringParse(parsedUrl.search.substr(1));}var auth=request.httpRequest.headers['Authorization'].split(' ');if(auth[0]==='AWS'){auth=auth[1].split(':');queryParams['AWSAccessKeyId']=auth[0];queryParams['Signature']=auth[1];AWS.util.each(request.httpRequest.headers,function(key,value){if(key===expiresHeader)key='Expires';if(key.indexOf('x-amz-meta-')===0){// Delete existing, potentially not normalized key +delete queryParams[key];key=key.toLowerCase();}queryParams[key]=value;});delete request.httpRequest.headers[expiresHeader];delete queryParams['Authorization'];delete queryParams['Host'];}else if(auth[0]==='AWS4-HMAC-SHA256'){// SigV4 signing +auth.shift();var rest=auth.join(' ');var signature=rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];queryParams['X-Amz-Signature']=signature;delete queryParams['Expires'];}// build URL +endpoint.pathname=parsedUrl.pathname;endpoint.search=AWS.util.queryParamsToString(queryParams);}/** * @api private - */AWS.Signers.Presign = inherit({/** + */AWS.Signers.Presign=inherit({/** * @api private - */sign: function sign(request, expireTime, callback) { request.httpRequest.headers[expiresHeader] = expireTime || 3600; request.on('build', signedUrlBuilder); request.on('sign', signedUrlSigner); request.removeListener('afterBuild', AWS.EventListeners.Core.SET_CONTENT_LENGTH); request.removeListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256); request.emit('beforePresign', [request]); if (callback) { request.build(function () { if (this.response.error) callback(this.response.error); else { callback(null, AWS.util.urlFormat(request.httpRequest.endpoint)); } }); } else { request.build(); if (request.response.error) throw request.response.error; return AWS.util.urlFormat(request.httpRequest.endpoint); } } - });/** + */sign:function sign(request,expireTime,callback){request.httpRequest.headers[expiresHeader]=expireTime||3600;request.on('build',signedUrlBuilder);request.on('sign',signedUrlSigner);request.removeListener('afterBuild',AWS.EventListeners.Core.SET_CONTENT_LENGTH);request.removeListener('afterBuild',AWS.EventListeners.Core.COMPUTE_SHA256);request.emit('beforePresign',[request]);if(callback){request.build(function(){if(this.response.error)callback(this.response.error);else{callback(null,AWS.util.urlFormat(request.httpRequest.endpoint));}});}else{request.build();if(request.response.error)throw request.response.error;return AWS.util.urlFormat(request.httpRequest.endpoint);}}});/** * @api private - */module.exports = AWS.Signers.Presign; - }, { "../core": 18 }], 63: [function (require, module, exports) { - var AWS = require('../core'); var inherit = AWS.util.inherit;/** + */module.exports=AWS.Signers.Presign;},{"../core":18}],63:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** * @api private - */AWS.Signers.RequestSigner = inherit({ constructor: function RequestSigner(request) { this.request = request; }, setServiceClientId: function setServiceClientId(id) { this.serviceClientId = id; }, getServiceClientId: function getServiceClientId() { return this.serviceClientId; } }); AWS.Signers.RequestSigner.getVersion = function getVersion(version) { switch (version) { case 'v2': return AWS.Signers.V2; case 'v3': return AWS.Signers.V3; case 's3v4': return AWS.Signers.V4; case 'v4': return AWS.Signers.V4; case 's3': return AWS.Signers.S3; case 'v3https': return AWS.Signers.V3Https; }throw new Error('Unknown signing version ' + version); }; require('./v2'); require('./v3'); require('./v3https'); require('./v4'); require('./s3'); require('./presign'); - }, { "../core": 18, "./presign": 62, "./s3": 64, "./v2": 65, "./v3": 66, "./v3https": 67, "./v4": 68 }], 64: [function (require, module, exports) { - var AWS = require('../core'); var inherit = AWS.util.inherit;/** + */AWS.Signers.RequestSigner=inherit({constructor:function RequestSigner(request){this.request=request;},setServiceClientId:function setServiceClientId(id){this.serviceClientId=id;},getServiceClientId:function getServiceClientId(){return this.serviceClientId;}});AWS.Signers.RequestSigner.getVersion=function getVersion(version){switch(version){case'v2':return AWS.Signers.V2;case'v3':return AWS.Signers.V3;case's3v4':return AWS.Signers.V4;case'v4':return AWS.Signers.V4;case's3':return AWS.Signers.S3;case'v3https':return AWS.Signers.V3Https;}throw new Error('Unknown signing version '+version);};require('./v2');require('./v3');require('./v3https');require('./v4');require('./s3');require('./presign');},{"../core":18,"./presign":62,"./s3":64,"./v2":65,"./v3":66,"./v3https":67,"./v4":68}],64:[function(require,module,exports){var AWS=require('../core');var inherit=AWS.util.inherit;/** * @api private - */AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {/** + */AWS.Signers.S3=inherit(AWS.Signers.RequestSigner,{/** * When building the stringToSign, these sub resource params should be * part of the canonical resource string with their NON-decoded values - */subResources: { 'acl': 1, 'accelerate': 1, 'analytics': 1, 'cors': 1, 'lifecycle': 1, 'delete': 1, 'inventory': 1, 'location': 1, 'logging': 1, 'metrics': 1, 'notification': 1, 'partNumber': 1, 'policy': 1, 'requestPayment': 1, 'replication': 1, 'restore': 1, 'tagging': 1, 'torrent': 1, 'uploadId': 1, 'uploads': 1, 'versionId': 1, 'versioning': 1, 'versions': 1, 'website': 1 },// when building the stringToSign, these querystring params should be - // part of the canonical resource string with their NON-encoded values - responseHeaders: { 'response-content-type': 1, 'response-content-language': 1, 'response-expires': 1, 'response-cache-control': 1, 'response-content-disposition': 1, 'response-content-encoding': 1 }, addAuthorization: function addAuthorization(credentials, date) { - if (!this.request.headers['presigned-expires']) { this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date); } if (credentials.sessionToken) {// presigned URLs require this header to be lowercased - this.request.headers['x-amz-security-token'] = credentials.sessionToken; - } var signature = this.sign(credentials.secretAccessKey, this.stringToSign()); var auth = 'AWS ' + credentials.accessKeyId + ':' + signature; this.request.headers['Authorization'] = auth; - }, stringToSign: function stringToSign() { - var r = this.request; var parts = []; parts.push(r.method); parts.push(r.headers['Content-MD5'] || ''); parts.push(r.headers['Content-Type'] || '');// This is the "Date" header, but we use X-Amz-Date. - // The S3 signing mechanism requires us to pass an empty - // string for this Date header regardless. - parts.push(r.headers['presigned-expires'] || ''); var headers = this.canonicalizedAmzHeaders(); if (headers) parts.push(headers); parts.push(this.canonicalizedResource()); return parts.join('\n'); - }, canonicalizedAmzHeaders: function canonicalizedAmzHeaders() { var amzHeaders = []; AWS.util.each(this.request.headers, function (name) { if (name.match(/^x-amz-/i)) amzHeaders.push(name); }); amzHeaders.sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, amzHeaders, function (name) { parts.push(name.toLowerCase() + ':' + String(this.request.headers[name])); }); return parts.join('\n'); }, canonicalizedResource: function canonicalizedResource() { - var r = this.request; var parts = r.path.split('?'); var path = parts[0]; var querystring = parts[1]; var resource = ''; if (r.virtualHostedBucket) resource += '/' + r.virtualHostedBucket; resource += path; if (querystring) {// collect a list of sub resources and query params that need to be signed - var resources = []; AWS.util.arrayEach.call(this, querystring.split('&'), function (param) { var name = param.split('=')[0]; var value = param.split('=')[1]; if (this.subResources[name] || this.responseHeaders[name]) { var subresource = { name: name }; if (value !== undefined) { if (this.subResources[name]) { subresource.value = value; } else { subresource.value = decodeURIComponent(value); } } resources.push(subresource); } }); resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; }); if (resources.length) { querystring = []; AWS.util.arrayEach(resources, function (res) { if (res.value === undefined) { querystring.push(res.name); } else { querystring.push(res.name + '=' + res.value); } }); resource += '?' + querystring.join('&'); } - } return resource; - }, sign: function sign(secret, string) { return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1'); } - });/** + */subResources:{'acl':1,'accelerate':1,'analytics':1,'cors':1,'lifecycle':1,'delete':1,'inventory':1,'location':1,'logging':1,'metrics':1,'notification':1,'partNumber':1,'policy':1,'requestPayment':1,'replication':1,'restore':1,'tagging':1,'torrent':1,'uploadId':1,'uploads':1,'versionId':1,'versioning':1,'versions':1,'website':1},// when building the stringToSign, these querystring params should be +// part of the canonical resource string with their NON-encoded values +responseHeaders:{'response-content-type':1,'response-content-language':1,'response-expires':1,'response-cache-control':1,'response-content-disposition':1,'response-content-encoding':1},addAuthorization:function addAuthorization(credentials,date){if(!this.request.headers['presigned-expires']){this.request.headers['X-Amz-Date']=AWS.util.date.rfc822(date);}if(credentials.sessionToken){// presigned URLs require this header to be lowercased +this.request.headers['x-amz-security-token']=credentials.sessionToken;}var signature=this.sign(credentials.secretAccessKey,this.stringToSign());var auth='AWS '+credentials.accessKeyId+':'+signature;this.request.headers['Authorization']=auth;},stringToSign:function stringToSign(){var r=this.request;var parts=[];parts.push(r.method);parts.push(r.headers['Content-MD5']||'');parts.push(r.headers['Content-Type']||'');// This is the "Date" header, but we use X-Amz-Date. +// The S3 signing mechanism requires us to pass an empty +// string for this Date header regardless. +parts.push(r.headers['presigned-expires']||'');var headers=this.canonicalizedAmzHeaders();if(headers)parts.push(headers);parts.push(this.canonicalizedResource());return parts.join('\n');},canonicalizedAmzHeaders:function canonicalizedAmzHeaders(){var amzHeaders=[];AWS.util.each(this.request.headers,function(name){if(name.match(/^x-amz-/i))amzHeaders.push(name);});amzHeaders.sort(function(a,b){return a.toLowerCase()= 0 ? '&' : '?'; this.request.path += sep + AWS.util.queryParamsToString(qs); - }, authorization: function authorization(credentials, datetime) { var parts = []; var credString = this.credentialString(datetime); parts.push(this.algorithm + ' Credential=' + credentials.accessKeyId + '/' + credString); parts.push('SignedHeaders=' + this.signedHeaders()); parts.push('Signature=' + this.signature(credentials, datetime)); return parts.join(', '); }, signature: function signature(credentials, datetime) { var signingKey = v4Credentials.getSigningKey(credentials, datetime.substr(0, 8), this.request.region, this.serviceName, this.signatureCache); return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex'); }, stringToSign: function stringToSign(datetime) { var parts = []; parts.push('AWS4-HMAC-SHA256'); parts.push(datetime); parts.push(this.credentialString(datetime)); parts.push(this.hexEncodedHash(this.canonicalString())); return parts.join('\n'); }, canonicalString: function canonicalString() { var parts = [], pathname = this.request.pathname(); if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname); parts.push(this.request.method); parts.push(pathname); parts.push(this.request.search()); parts.push(this.canonicalHeaders() + '\n'); parts.push(this.signedHeaders()); parts.push(this.hexEncodedBodyHash()); return parts.join('\n'); }, canonicalHeaders: function canonicalHeaders() { var headers = []; AWS.util.each.call(this, this.request.headers, function (key, item) { headers.push([key, item]); }); headers.sort(function (a, b) { return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1; }); var parts = []; AWS.util.arrayEach.call(this, headers, function (item) { var key = item[0].toLowerCase(); if (this.isSignableHeader(key)) { var value = item[1]; if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') { throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), { code: 'InvalidHeader' }); } parts.push(key + ':' + this.canonicalHeaderValues(value.toString())); } }); return parts.join('\n'); }, canonicalHeaderValues: function canonicalHeaderValues(values) { return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, ''); }, signedHeaders: function signedHeaders() { var keys = []; AWS.util.each.call(this, this.request.headers, function (key) { key = key.toLowerCase(); if (this.isSignableHeader(key)) keys.push(key); }); return keys.sort().join(';'); }, credentialString: function credentialString(datetime) { return v4Credentials.createScope(datetime.substr(0, 8), this.request.region, this.serviceName); }, hexEncodedHash: function hash(string) { return AWS.util.crypto.sha256(string, 'hex'); }, hexEncodedBodyHash: function hexEncodedBodyHash() { var request = this.request; if (this.isPresigned() && this.serviceName === 's3' && !request.body) { return 'UNSIGNED-PAYLOAD'; } else if (request.headers['X-Amz-Content-Sha256']) { return request.headers['X-Amz-Content-Sha256']; } else { return this.hexEncodedHash(this.request.body || ''); } }, unsignableHeaders: ['authorization', 'content-type', 'content-length', 'user-agent', expiresHeader, 'expect', 'x-amzn-trace-id'], isSignableHeader: function isSignableHeader(key) { if (key.toLowerCase().indexOf('x-amz-') === 0) return true; return this.unsignableHeaders.indexOf(key) < 0; }, isPresigned: function isPresigned() { return this.request.headers[expiresHeader] ? true : false; } - });/** + */AWS.Signers.V4=inherit(AWS.Signers.RequestSigner,{constructor:function V4(request,serviceName,options){AWS.Signers.RequestSigner.call(this,request);this.serviceName=serviceName;options=options||{};this.signatureCache=typeof options.signatureCache==='boolean'?options.signatureCache:true;this.operation=options.operation;this.signatureVersion=options.signatureVersion;},algorithm:'AWS4-HMAC-SHA256',addAuthorization:function addAuthorization(credentials,date){var datetime=AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g,'');if(this.isPresigned()){this.updateForPresigned(credentials,datetime);}else{this.addHeaders(credentials,datetime);}this.request.headers['Authorization']=this.authorization(credentials,datetime);},addHeaders:function addHeaders(credentials,datetime){this.request.headers['X-Amz-Date']=datetime;if(credentials.sessionToken){this.request.headers['x-amz-security-token']=credentials.sessionToken;}},updateForPresigned:function updateForPresigned(credentials,datetime){var credString=this.credentialString(datetime);var qs={'X-Amz-Date':datetime,'X-Amz-Algorithm':this.algorithm,'X-Amz-Credential':credentials.accessKeyId+'/'+credString,'X-Amz-Expires':this.request.headers[expiresHeader],'X-Amz-SignedHeaders':this.signedHeaders()};if(credentials.sessionToken){qs['X-Amz-Security-Token']=credentials.sessionToken;}if(this.request.headers['Content-Type']){qs['Content-Type']=this.request.headers['Content-Type'];}if(this.request.headers['Content-MD5']){qs['Content-MD5']=this.request.headers['Content-MD5'];}if(this.request.headers['Cache-Control']){qs['Cache-Control']=this.request.headers['Cache-Control'];}// need to pull in any other X-Amz-* headers +AWS.util.each.call(this,this.request.headers,function(key,value){if(key===expiresHeader)return;if(this.isSignableHeader(key)){var lowerKey=key.toLowerCase();// Metadata should be normalized +if(lowerKey.indexOf('x-amz-meta-')===0){qs[lowerKey]=value;}else if(lowerKey.indexOf('x-amz-')===0){qs[key]=value;}}});var sep=this.request.path.indexOf('?')>=0?'&':'?';this.request.path+=sep+AWS.util.queryParamsToString(qs);},authorization:function authorization(credentials,datetime){var parts=[];var credString=this.credentialString(datetime);parts.push(this.algorithm+' Credential='+credentials.accessKeyId+'/'+credString);parts.push('SignedHeaders='+this.signedHeaders());parts.push('Signature='+this.signature(credentials,datetime));return parts.join(', ');},signature:function signature(credentials,datetime){var signingKey=v4Credentials.getSigningKey(credentials,datetime.substr(0,8),this.request.region,this.serviceName,this.signatureCache);return AWS.util.crypto.hmac(signingKey,this.stringToSign(datetime),'hex');},stringToSign:function stringToSign(datetime){var parts=[];parts.push('AWS4-HMAC-SHA256');parts.push(datetime);parts.push(this.credentialString(datetime));parts.push(this.hexEncodedHash(this.canonicalString()));return parts.join('\n');},canonicalString:function canonicalString(){var parts=[],pathname=this.request.pathname();if(this.serviceName!=='s3'&&this.signatureVersion!=='s3v4')pathname=AWS.util.uriEscapePath(pathname);parts.push(this.request.method);parts.push(pathname);parts.push(this.request.search());parts.push(this.canonicalHeaders()+'\n');parts.push(this.signedHeaders());parts.push(this.hexEncodedBodyHash());return parts.join('\n');},canonicalHeaders:function canonicalHeaders(){var headers=[];AWS.util.each.call(this,this.request.headers,function(key,item){headers.push([key,item]);});headers.sort(function(a,b){return a[0].toLowerCase() maxCacheEntries) {// remove the oldest entry (not the least recently used) - delete cachedSecret[cacheQueue.shift()]; - } - } return signingKey; - },/** + */getSigningKey:function getSigningKey(credentials,date,region,service,shouldCache){var credsIdentifier=AWS.util.crypto.hmac(credentials.secretAccessKey,credentials.accessKeyId,'base64');var cacheKey=[credsIdentifier,date,region,service].join('_');shouldCache=shouldCache!==false;if(shouldCache&&cacheKey in cachedSecret){return cachedSecret[cacheKey];}var kDate=AWS.util.crypto.hmac('AWS4'+credentials.secretAccessKey,date,'buffer');var kRegion=AWS.util.crypto.hmac(kDate,region,'buffer');var kService=AWS.util.crypto.hmac(kRegion,service,'buffer');var signingKey=AWS.util.crypto.hmac(kService,v4Identifier,'buffer');if(shouldCache){cachedSecret[cacheKey]=signingKey;cacheQueue.push(cacheKey);if(cacheQueue.length>maxCacheEntries){// remove the oldest entry (not the least recently used) +delete cachedSecret[cacheQueue.shift()];}}return signingKey;},/** * @api private * * Empties the derived signing key cache. Made available for testing purposes * only. - */emptyCache: function emptyCache() { cachedSecret = {}; cacheQueue = []; } - }; - }, { "../core": 18 }], 70: [function (require, module, exports) { - function AcceptorStateMachine(states, state) { this.currentState = state || null; this.states = states || {}; } AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) { if (typeof finalState === 'function') { inputError = bindObject; bindObject = done; done = finalState; finalState = null; } var self = this; var state = self.states[self.currentState]; state.fn.call(bindObject || self, inputError, function (err) { if (err) { if (state.fail) self.currentState = state.fail; else return done ? done.call(bindObject, err) : null; } else { if (state.accept) self.currentState = state.accept; else return done ? done.call(bindObject) : null; } if (self.currentState === finalState) { return done ? done.call(bindObject, err) : null; } self.runTo(finalState, done, bindObject, err); }); }; AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) { if (typeof acceptState === 'function') { fn = acceptState; acceptState = null; failState = null; } else if (typeof failState === 'function') { fn = failState; failState = null; } if (!this.currentState) this.currentState = name; this.states[name] = { accept: acceptState, fail: failState, fn: fn }; return this; };/** + */emptyCache:function emptyCache(){cachedSecret={};cacheQueue=[];}};},{"../core":18}],70:[function(require,module,exports){function AcceptorStateMachine(states,state){this.currentState=state||null;this.states=states||{};}AcceptorStateMachine.prototype.runTo=function runTo(finalState,done,bindObject,inputError){if(typeof finalState==='function'){inputError=bindObject;bindObject=done;done=finalState;finalState=null;}var self=this;var state=self.states[self.currentState];state.fn.call(bindObject||self,inputError,function(err){if(err){if(state.fail)self.currentState=state.fail;else return done?done.call(bindObject,err):null;}else{if(state.accept)self.currentState=state.accept;else return done?done.call(bindObject):null;}if(self.currentState===finalState){return done?done.call(bindObject,err):null;}self.runTo(finalState,done,bindObject,err);});};AcceptorStateMachine.prototype.addState=function addState(name,acceptState,failState,fn){if(typeof acceptState==='function'){fn=acceptState;acceptState=null;failState=null;}else if(typeof failState==='function'){fn=failState;failState=null;}if(!this.currentState)this.currentState=name;this.states[name]={accept:acceptState,fail:failState,fn:fn};return this;};/** * @api private - */module.exports = AcceptorStateMachine; - }, {}], 71: [function (require, module, exports) { - (function (process, setImmediate) { - (function () {/* eslint guard-for-in:0 */var AWS;/** + */module.exports=AcceptorStateMachine;},{}],71:[function(require,module,exports){(function(process,setImmediate){(function(){/* eslint guard-for-in:0 */var AWS;/** * A set of utility methods for use with the AWS SDK. * * @!attribute abort @@ -5188,54 +4679,36 @@ * @see each * @see arrayEach * @api private - */var util = { - environment: 'nodejs', engine: function engine() { if (util.isBrowser() && typeof navigator !== 'undefined') { return navigator.userAgent; } else { var engine = process.platform + '/' + process.version; if (process.env.AWS_EXECUTION_ENV) { engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV; } return engine; } }, userAgent: function userAgent() { var name = util.environment; var agent = 'aws-sdk-' + name + '/' + require('./core').VERSION; if (name === 'nodejs') agent += ' ' + util.engine(); return agent; }, uriEscape: function uriEscape(string) { - var output = encodeURIComponent(string); output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);// AWS percent-encodes some extra non-standard characters in a URI - output = output.replace(/[*]/g, function (ch) { return '%' + ch.charCodeAt(0).toString(16).toUpperCase(); }); return output; - }, uriEscapePath: function uriEscapePath(string) { var parts = []; util.arrayEach(string.split('/'), function (part) { parts.push(util.uriEscape(part)); }); return parts.join('/'); }, urlParse: function urlParse(url) { return util.url.parse(url); }, urlFormat: function urlFormat(url) { return util.url.format(url); }, queryStringParse: function queryStringParse(qs) { return util.querystring.parse(qs); }, queryParamsToString: function queryParamsToString(params) { var items = []; var escape = util.uriEscape; var sortedKeys = Object.keys(params).sort(); util.arrayEach(sortedKeys, function (name) { var value = params[name]; var ename = escape(name); var result = ename + '='; if (Array.isArray(value)) { var vals = []; util.arrayEach(value, function (item) { vals.push(escape(item)); }); result = ename + '=' + vals.sort().join('&' + ename + '='); } else if (value !== undefined && value !== null) { result = ename + '=' + escape(value); } items.push(result); }); return items.join('&'); }, readFileSync: function readFileSync(path) { if (util.isBrowser()) return null; return require('fs').readFileSync(path, 'utf-8'); }, base64: { encode: function encode64(string) { if (typeof string === 'number') { throw util.error(new Error('Cannot base64 encode number ' + string)); } if (string === null || typeof string === 'undefined') { return string; } var buf = util.buffer.toBuffer(string); return buf.toString('base64'); }, decode: function decode64(string) { if (typeof string === 'number') { throw util.error(new Error('Cannot base64 decode number ' + string)); } if (string === null || typeof string === 'undefined') { return string; } return util.buffer.toBuffer(string, 'base64'); } }, buffer: {/** + */var util={environment:'nodejs',engine:function engine(){if(util.isBrowser()&&typeof navigator!=='undefined'){return navigator.userAgent;}else{var engine=process.platform+'/'+process.version;if(process.env.AWS_EXECUTION_ENV){engine+=' exec-env/'+process.env.AWS_EXECUTION_ENV;}return engine;}},userAgent:function userAgent(){var name=util.environment;var agent='aws-sdk-'+name+'/'+require('./core').VERSION;if(name==='nodejs')agent+=' '+util.engine();return agent;},uriEscape:function uriEscape(string){var output=encodeURIComponent(string);output=output.replace(/[^A-Za-z0-9_.~\-%]+/g,escape);// AWS percent-encodes some extra non-standard characters in a URI +output=output.replace(/[*]/g,function(ch){return'%'+ch.charCodeAt(0).toString(16).toUpperCase();});return output;},uriEscapePath:function uriEscapePath(string){var parts=[];util.arrayEach(string.split('/'),function(part){parts.push(util.uriEscape(part));});return parts.join('/');},urlParse:function urlParse(url){return util.url.parse(url);},urlFormat:function urlFormat(url){return util.url.format(url);},queryStringParse:function queryStringParse(qs){return util.querystring.parse(qs);},queryParamsToString:function queryParamsToString(params){var items=[];var escape=util.uriEscape;var sortedKeys=Object.keys(params).sort();util.arrayEach(sortedKeys,function(name){var value=params[name];var ename=escape(name);var result=ename+'=';if(Array.isArray(value)){var vals=[];util.arrayEach(value,function(item){vals.push(escape(item));});result=ename+'='+vals.sort().join('&'+ename+'=');}else if(value!==undefined&&value!==null){result=ename+'='+escape(value);}items.push(result);});return items.join('&');},readFileSync:function readFileSync(path){if(util.isBrowser())return null;return require('fs').readFileSync(path,'utf-8');},base64:{encode:function encode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 encode number '+string));}if(string===null||typeof string==='undefined'){return string;}var buf=util.buffer.toBuffer(string);return buf.toString('base64');},decode:function decode64(string){if(typeof string==='number'){throw util.error(new Error('Cannot base64 decode number '+string));}if(string===null||typeof string==='undefined'){return string;}return util.buffer.toBuffer(string,'base64');}},buffer:{/** * Buffer constructor for Node buffer and buffer pollyfill - */toBuffer: function toBuffer(data, encoding) { return typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from ? util.Buffer.from(data, encoding) : new util.Buffer(data, encoding); }, alloc: function alloc(size, fill, encoding) { if (typeof size !== 'number') { throw new Error('size passed to alloc must be a number.'); } if (typeof util.Buffer.alloc === 'function') { return util.Buffer.alloc(size, fill, encoding); } else { var buf = new util.Buffer(size); if (fill !== undefined && typeof buf.fill === 'function') { buf.fill(fill, undefined, undefined, encoding); } return buf; } }, toStream: function toStream(buffer) { if (!util.Buffer.isBuffer(buffer)) buffer = util.buffer.toBuffer(buffer); var readable = new util.stream.Readable(); var pos = 0; readable._read = function (size) { if (pos >= buffer.length) return readable.push(null); var end = pos + size; if (end > buffer.length) end = buffer.length; readable.push(buffer.slice(pos, end)); pos = end; }; return readable; },/** + */toBuffer:function toBuffer(data,encoding){return typeof util.Buffer.from==='function'&&util.Buffer.from!==Uint8Array.from?util.Buffer.from(data,encoding):new util.Buffer(data,encoding);},alloc:function alloc(size,fill,encoding){if(typeof size!=='number'){throw new Error('size passed to alloc must be a number.');}if(typeof util.Buffer.alloc==='function'){return util.Buffer.alloc(size,fill,encoding);}else{var buf=new util.Buffer(size);if(fill!==undefined&&typeof buf.fill==='function'){buf.fill(fill,undefined,undefined,encoding);}return buf;}},toStream:function toStream(buffer){if(!util.Buffer.isBuffer(buffer))buffer=util.buffer.toBuffer(buffer);var readable=new util.stream.Readable();var pos=0;readable._read=function(size){if(pos>=buffer.length)return readable.push(null);var end=pos+size;if(end>buffer.length)end=buffer.length;readable.push(buffer.slice(pos,end));pos=end;};return readable;},/** * Concatenates a list of Buffer objects. - */concat: function concat(buffers) { var length = 0, offset = 0, buffer = null, i; for (i = 0; i < buffers.length; i++) { length += buffers[i].length; } buffer = util.buffer.alloc(length); for (i = 0; i < buffers.length; i++) { buffers[i].copy(buffer, offset); offset += buffers[i].length; } return buffer; } - }, string: { byteLength: function byteLength(string) { if (string === null || string === undefined) return 0; if (typeof string === 'string') string = util.buffer.toBuffer(string); if (typeof string.byteLength === 'number') { return string.byteLength; } else if (typeof string.length === 'number') { return string.length; } else if (typeof string.size === 'number') { return string.size; } else if (typeof string.path === 'string') { return require('fs').lstatSync(string.path).size; } else { throw util.error(new Error('Cannot determine length of ' + string), { object: string }); } }, upperFirst: function upperFirst(string) { return string[0].toUpperCase() + string.substr(1); }, lowerFirst: function lowerFirst(string) { return string[0].toLowerCase() + string.substr(1); } }, ini: { - parse: function string(ini) { - var currentSection, map = {}; util.arrayEach(ini.split(/\r?\n/), function (line) { - line = line.split(/(^|\s)[;#]/)[0];// remove comments - var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/); if (section) { currentSection = section[1]; } else if (currentSection) { var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/); if (item) { map[currentSection] = map[currentSection] || {}; map[currentSection][item[1]] = item[2]; } } - }); return map; - } - }, fn: { - noop: function noop() { }, callback: function callback(err) { if (err) throw err; },/** + */concat:function concat(buffers){var length=0,offset=0,buffer=null,i;for(i=0;i>> 8 ^ tbl[(crc ^ code) & 0xFF]; } return (crc ^ -1) >>> 0; }, hmac: function hmac(key, string, digest, fn) { if (!digest) digest = 'binary'; if (digest === 'buffer') { digest = undefined; } if (!fn) fn = 'sha256'; if (typeof string === 'string') string = util.buffer.toBuffer(string); return util.crypto.lib.createHmac(fn, key).update(string).digest(digest); }, md5: function md5(data, digest, callback) { return util.crypto.hash('md5', data, digest, callback); }, sha256: function sha256(data, digest, callback) { return util.crypto.hash('sha256', data, digest, callback); }, hash: function hash(algorithm, data, digest, callback) { - var hash = util.crypto.createHash(algorithm); if (!digest) { digest = 'binary'; } if (digest === 'buffer') { digest = undefined; } if (typeof data === 'string') data = util.buffer.toBuffer(data); var sliceFn = util.arraySliceFn(data); var isBuffer = util.Buffer.isBuffer(data);//Identifying objects with an ArrayBuffer as buffers - if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true; if (callback && _typeof(data) === 'object' && typeof data.on === 'function' && !isBuffer) { data.on('data', function (chunk) { hash.update(chunk); }); data.on('error', function (err) { callback(err); }); data.on('end', function () { callback(null, hash.digest(digest)); }); } else if (callback && sliceFn && !isBuffer && typeof FileReader !== 'undefined') {// this might be a File/Blob - var index = 0, size = 1024 * 512; var reader = new FileReader(); reader.onerror = function () { callback(new Error('Failed to read data.')); }; reader.onload = function () { var buf = new util.Buffer(new Uint8Array(reader.result)); hash.update(buf); index += buf.length; reader._continueReading(); }; reader._continueReading = function () { if (index >= data.size) { callback(null, hash.digest(digest)); return; } var back = index + size; if (back > data.size) back = data.size; reader.readAsArrayBuffer(sliceFn.call(data, index, back)); }; reader._continueReading(); - } else { if (util.isBrowser() && _typeof(data) === 'object' && !isBuffer) { data = new util.Buffer(new Uint8Array(data)); } var out = hash.update(data).digest(digest); if (callback) callback(null, out); return out; } - }, toHex: function toHex(data) { var out = []; for (var i = 0; i < data.length; i++) { out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2)); } return out.join(''); }, createHash: function createHash(algorithm) { return util.crypto.lib.createHash(algorithm); } - },/** @!ignore */ /* Abort constant */abort: {}, each: function each(object, iterFunction) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { var ret = iterFunction.call(this, key, object[key]); if (ret === util.abort) break; } } }, arrayEach: function arrayEach(array, iterFunction) { for (var idx in array) { if (Object.prototype.hasOwnProperty.call(array, idx)) { var ret = iterFunction.call(this, array[idx], parseInt(idx, 10)); if (ret === util.abort) break; } } }, update: function update(obj1, obj2) { util.each(obj2, function iterator(key, item) { obj1[key] = item; }); return obj1; }, merge: function merge(obj1, obj2) { return util.update(util.copy(obj1), obj2); }, copy: function copy(object) { - if (object === null || object === undefined) return object; var dupe = {};// jshint forin:false - for (var key in object) { dupe[key] = object[key]; } return dupe; - }, isEmpty: function isEmpty(obj) { for (var prop in obj) { if (Object.prototype.hasOwnProperty.call(obj, prop)) { return false; } } return true; }, arraySliceFn: function arraySliceFn(obj) { var fn = obj.slice || obj.webkitSlice || obj.mozSlice; return typeof fn === 'function' ? fn : null; }, isType: function isType(obj, type) {// handle cross-"frame" objects - if (typeof type === 'function') type = util.typeName(type); return Object.prototype.toString.call(obj) === '[object ' + type + ']'; - }, typeName: function typeName(type) { if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name; var str = type.toString(); var match = str.match(/^\s*function (.+)\(/); return match ? match[1] : str; }, error: function error(err, options) { var originalError = null; if (typeof err.message === 'string' && err.message !== '') { if (typeof options === 'string' || options && options.message) { originalError = util.copy(err); originalError.message = err.message; } } err.message = err.message || null; if (typeof options === 'string') { err.message = options; } else if (_typeof(options) === 'object' && options !== null) { util.update(err, options); if (options.message) err.message = options.message; if (options.code || options.name) err.code = options.code || options.name; if (options.stack) err.stack = options.stack; } if (typeof Object.defineProperty === 'function') { Object.defineProperty(err, 'name', { writable: true, enumerable: false }); Object.defineProperty(err, 'message', { enumerable: true }); } err.name = options && options.name || err.name || err.code || 'Error'; err.time = new Date(); if (originalError) err.originalError = originalError; return err; },/** + */format:function format(date,formatter){if(!formatter)formatter='iso8601';return util.date[formatter](util.date.from(date));},parseTimestamp:function parseTimestamp(value){if(typeof value==='number'){// unix timestamp (number) +return new Date(value*1000);}else if(value.match(/^\d+$/)){// unix timestamp +return new Date(value*1000);}else if(value.match(/^\d{4}/)){// iso8601 +return new Date(value);}else if(value.match(/^\w{3},/)){// rfc822 +return new Date(value);}else{throw util.error(new Error('unhandled timestamp format: '+value),{code:'TimestampParserError'});}}},crypto:{crc32Table:[0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D],crc32:function crc32(data){var tbl=util.crypto.crc32Table;var crc=0^-1;if(typeof data==='string'){data=util.buffer.toBuffer(data);}for(var i=0;i>>8^tbl[(crc^code)&0xFF];}return(crc^-1)>>>0;},hmac:function hmac(key,string,digest,fn){if(!digest)digest='binary';if(digest==='buffer'){digest=undefined;}if(!fn)fn='sha256';if(typeof string==='string')string=util.buffer.toBuffer(string);return util.crypto.lib.createHmac(fn,key).update(string).digest(digest);},md5:function md5(data,digest,callback){return util.crypto.hash('md5',data,digest,callback);},sha256:function sha256(data,digest,callback){return util.crypto.hash('sha256',data,digest,callback);},hash:function hash(algorithm,data,digest,callback){var hash=util.crypto.createHash(algorithm);if(!digest){digest='binary';}if(digest==='buffer'){digest=undefined;}if(typeof data==='string')data=util.buffer.toBuffer(data);var sliceFn=util.arraySliceFn(data);var isBuffer=util.Buffer.isBuffer(data);//Identifying objects with an ArrayBuffer as buffers +if(util.isBrowser()&&typeof ArrayBuffer!=='undefined'&&data&&data.buffer instanceof ArrayBuffer)isBuffer=true;if(callback&&_typeof(data)==='object'&&typeof data.on==='function'&&!isBuffer){data.on('data',function(chunk){hash.update(chunk);});data.on('error',function(err){callback(err);});data.on('end',function(){callback(null,hash.digest(digest));});}else if(callback&&sliceFn&&!isBuffer&&typeof FileReader!=='undefined'){// this might be a File/Blob +var index=0,size=1024*512;var reader=new FileReader();reader.onerror=function(){callback(new Error('Failed to read data.'));};reader.onload=function(){var buf=new util.Buffer(new Uint8Array(reader.result));hash.update(buf);index+=buf.length;reader._continueReading();};reader._continueReading=function(){if(index>=data.size){callback(null,hash.digest(digest));return;}var back=index+size;if(back>data.size)back=data.size;reader.readAsArrayBuffer(sliceFn.call(data,index,back));};reader._continueReading();}else{if(util.isBrowser()&&_typeof(data)==='object'&&!isBuffer){data=new util.Buffer(new Uint8Array(data));}var out=hash.update(data).digest(digest);if(callback)callback(null,out);return out;}},toHex:function toHex(data){var out=[];for(var i=0;i= 300000, false); return AWS.config.isClockSkewed; } }, applyClockOffset: function applyClockOffset(serverTime) { if (serverTime) AWS.config.systemClockOffset = serverTime - new Date().getTime(); },/** + */isClockSkewed:function isClockSkewed(serverTime){if(serverTime){util.property(AWS.config,'isClockSkewed',Math.abs(new Date().getTime()-serverTime)>=300000,false);return AWS.config.isClockSkewed;}},applyClockOffset:function applyClockOffset(serverTime){if(serverTime)AWS.config.systemClockOffset=serverTime-new Date().getTime();},/** * @api private - */extractRequestId: function extractRequestId(resp) { var requestId = resp.httpResponse.headers['x-amz-request-id'] || resp.httpResponse.headers['x-amzn-requestid']; if (!requestId && resp.data && resp.data.ResponseMetadata) { requestId = resp.data.ResponseMetadata.RequestId; } if (requestId) { resp.requestId = requestId; } if (resp.error) { resp.error.requestId = requestId; } },/** + */extractRequestId:function extractRequestId(resp){var requestId=resp.httpResponse.headers['x-amz-request-id']||resp.httpResponse.headers['x-amzn-requestid'];if(!requestId&&resp.data&&resp.data.ResponseMetadata){requestId=resp.data.ResponseMetadata.RequestId;}if(requestId){resp.requestId=requestId;}if(resp.error){resp.error.requestId=requestId;}},/** * @api private - */addPromises: function addPromises(constructors, PromiseDependency) { var deletePromises = false; if (PromiseDependency === undefined && AWS && AWS.config) { PromiseDependency = AWS.config.getPromisesDependency(); } if (PromiseDependency === undefined && typeof Promise !== 'undefined') { PromiseDependency = Promise; } if (typeof PromiseDependency !== 'function') deletePromises = true; if (!Array.isArray(constructors)) constructors = [constructors]; for (var ind = 0; ind < constructors.length; ind++) { var constructor = constructors[ind]; if (deletePromises) { if (constructor.deletePromisesFromClass) { constructor.deletePromisesFromClass(); } } else if (constructor.addPromisesToClass) { constructor.addPromisesToClass(PromiseDependency); } } },/** + */addPromises:function addPromises(constructors,PromiseDependency){var deletePromises=false;if(PromiseDependency===undefined&&AWS&&AWS.config){PromiseDependency=AWS.config.getPromisesDependency();}if(PromiseDependency===undefined&&typeof Promise!=='undefined'){PromiseDependency=Promise;}if(typeof PromiseDependency!=='function')deletePromises=true;if(!Array.isArray(constructors))constructors=[constructors];for(var ind=0;ind= 500 || statusCode === 429 }); if (retryAfter && err.retryable) err.retryAfter = retryAfter; errCallback(err); } }); }, errCallback); }; AWS.util.defer(sendRequest); },/** + */handleRequestWithRetries:function handleRequestWithRetries(httpRequest,options,cb){if(!options)options={};var http=AWS.HttpClient.getInstance();var httpOptions=options.httpOptions||{};var retryCount=0;var errCallback=function errCallback(err){var maxRetries=options.maxRetries||0;if(err&&err.code==='TimeoutError')err.retryable=true;if(err&&err.retryable&&retryCount=500||statusCode===429});if(retryAfter&&err.retryable)err.retryAfter=retryAfter;errCallback(err);}});},errCallback);};AWS.util.defer(sendRequest);},/** * @api private - */uuid: { v4: function uuidV4() { return require('uuid').v4(); } },/** + */uuid:{v4:function uuidV4(){return require('uuid').v4();}},/** * @api private - */convertPayloadToString: function convertPayloadToString(resp) { var req = resp.request; var operation = req.operation; var rules = req.service.api.operations[operation].output || {}; if (rules.payload && resp.data[rules.payload]) { resp.data[rules.payload] = resp.data[rules.payload].toString(); } },/** + */convertPayloadToString:function convertPayloadToString(resp){var req=resp.request;var operation=req.operation;var rules=req.service.api.operations[operation].output||{};if(rules.payload&&resp.data[rules.payload]){resp.data[rules.payload]=resp.data[rules.payload].toString();}},/** * @api private - */defer: function defer(callback) { if (_typeof(process) === 'object' && typeof process.nextTick === 'function') { process.nextTick(callback); } else if (typeof setImmediate === 'function') { setImmediate(callback); } else { setTimeout(callback, 0); } },/** + */defer:function defer(callback){if(_typeof(process)==='object'&&typeof process.nextTick==='function'){process.nextTick(callback);}else if(typeof setImmediate==='function'){setImmediate(callback);}else{setTimeout(callback,0);}},/** * @api private - */getRequestPayloadShape: function getRequestPayloadShape(req) { var operations = req.service.api.operations; if (!operations) return undefined; var operation = (operations || {})[req.operation]; if (!operation || !operation.input || !operation.input.payload) return undefined; return operation.input.members[operation.input.payload]; }, getProfilesFromSharedConfig: function getProfilesFromSharedConfig(iniLoader, filename) { var profiles = {}; var profilesFromConfig = {}; if (process.env[util.configOptInEnv]) { var profilesFromConfig = iniLoader.loadFrom({ isConfig: true, filename: process.env[util.sharedConfigFileEnv] }); } var profilesFromCreds = iniLoader.loadFrom({ filename: filename || process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv] }); for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) { profiles[profileNames[i]] = profilesFromConfig[profileNames[i]]; } for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) { profiles[profileNames[i]] = profilesFromCreds[profileNames[i]]; } return profiles; },/** + */getRequestPayloadShape:function getRequestPayloadShape(req){var operations=req.service.api.operations;if(!operations)return undefined;var operation=(operations||{})[req.operation];if(!operation||!operation.input||!operation.input.payload)return undefined;return operation.input.members[operation.input.payload];},getProfilesFromSharedConfig:function getProfilesFromSharedConfig(iniLoader,filename){var profiles={};var profilesFromConfig={};if(process.env[util.configOptInEnv]){var profilesFromConfig=iniLoader.loadFrom({isConfig:true,filename:process.env[util.sharedConfigFileEnv]});}var profilesFromCreds=iniLoader.loadFrom({filename:filename||process.env[util.configOptInEnv]&&process.env[util.sharedCredentialsFileEnv]});for(var i=0,profileNames=Object.keys(profilesFromConfig);i 0 || noEmpty ? xml.toString() : ''; }; function serialize(xml, value, shape) { switch (shape.type) { case 'structure': return serializeStructure(xml, value, shape); case 'map': return serializeMap(xml, value, shape); case 'list': return serializeList(xml, value, shape); default: return serializeScalar(xml, value, shape); } } function serializeStructure(xml, params, shape) { util.arrayEach(shape.memberNames, function (memberName) { var memberShape = shape.members[memberName]; if (memberShape.location !== 'body') return; var value = params[memberName]; var name = memberShape.name; if (value !== undefined && value !== null) { if (memberShape.isXmlAttribute) { xml.addAttribute(name, value); } else if (memberShape.flattened) { serialize(xml, value, memberShape); } else { var element = new XmlNode(name); xml.addChildNode(element); applyNamespaces(element, memberShape); serialize(element, value, memberShape); } } }); } function serializeMap(xml, map, shape) { var xmlKey = shape.key.name || 'key'; var xmlValue = shape.value.name || 'value'; util.each(map, function (key, value) { var entry = new XmlNode(shape.flattened ? shape.name : 'entry'); xml.addChildNode(entry); var entryKey = new XmlNode(xmlKey); var entryValue = new XmlNode(xmlValue); entry.addChildNode(entryKey); entry.addChildNode(entryValue); serialize(entryKey, key, shape.key); serialize(entryValue, value, shape.value); }); } function serializeList(xml, list, shape) { if (shape.flattened) { util.arrayEach(list, function (value) { var name = shape.member.name || shape.name; var element = new XmlNode(name); xml.addChildNode(element); serialize(element, value, shape.member); }); } else { util.arrayEach(list, function (value) { var name = shape.member.name || 'member'; var element = new XmlNode(name); xml.addChildNode(element); serialize(element, value, shape.member); }); } } function serializeScalar(xml, value, shape) { xml.addChildNode(new XmlText(shape.toWireFormat(value))); } function applyNamespaces(xml, shape, isRoot) { var uri, prefix = 'xmlns'; if (shape.xmlNamespaceUri) { uri = shape.xmlNamespaceUri; if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix; } else if (isRoot && shape.api.xmlNamespaceUri) { uri = shape.api.xmlNamespaceUri; } if (uri) xml.addAttribute(prefix, uri); }/** + */module.exports=DomXmlParser;},{"../model/shape":43,"../util":71}],73:[function(require,module,exports){var util=require('../util');var XmlNode=require('./xml-node').XmlNode;var XmlText=require('./xml-text').XmlText;function XmlBuilder(){}XmlBuilder.prototype.toXML=function(params,shape,rootElement,noEmpty){var xml=new XmlNode(rootElement);applyNamespaces(xml,shape,true);serialize(xml,params,shape);return xml.children.length>0||noEmpty?xml.toString():'';};function serialize(xml,value,shape){switch(shape.type){case'structure':return serializeStructure(xml,value,shape);case'map':return serializeMap(xml,value,shape);case'list':return serializeList(xml,value,shape);default:return serializeScalar(xml,value,shape);}}function serializeStructure(xml,params,shape){util.arrayEach(shape.memberNames,function(memberName){var memberShape=shape.members[memberName];if(memberShape.location!=='body')return;var value=params[memberName];var name=memberShape.name;if(value!==undefined&&value!==null){if(memberShape.isXmlAttribute){xml.addAttribute(name,value);}else if(memberShape.flattened){serialize(xml,value,memberShape);}else{var element=new XmlNode(name);xml.addChildNode(element);applyNamespaces(element,memberShape);serialize(element,value,memberShape);}}});}function serializeMap(xml,map,shape){var xmlKey=shape.key.name||'key';var xmlValue=shape.value.name||'value';util.each(map,function(key,value){var entry=new XmlNode(shape.flattened?shape.name:'entry');xml.addChildNode(entry);var entryKey=new XmlNode(xmlKey);var entryValue=new XmlNode(xmlValue);entry.addChildNode(entryKey);entry.addChildNode(entryValue);serialize(entryKey,key,shape.key);serialize(entryValue,value,shape.value);});}function serializeList(xml,list,shape){if(shape.flattened){util.arrayEach(list,function(value){var name=shape.member.name||shape.name;var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}else{util.arrayEach(list,function(value){var name=shape.member.name||'member';var element=new XmlNode(name);xml.addChildNode(element);serialize(element,value,shape.member);});}}function serializeScalar(xml,value,shape){xml.addChildNode(new XmlText(shape.toWireFormat(value)));}function applyNamespaces(xml,shape,isRoot){var uri,prefix='xmlns';if(shape.xmlNamespaceUri){uri=shape.xmlNamespaceUri;if(shape.xmlNamespacePrefix)prefix+=':'+shape.xmlNamespacePrefix;}else if(isRoot&&shape.api.xmlNamespaceUri){uri=shape.api.xmlNamespaceUri;}if(uri)xml.addAttribute(prefix,uri);}/** * @api private - */module.exports = XmlBuilder; - }, { "../util": 71, "./xml-node": 76, "./xml-text": 77 }], 74: [function (require, module, exports) {/** + */module.exports=XmlBuilder;},{"../util":71,"./xml-node":76,"./xml-text":77}],74:[function(require,module,exports){/** * Escapes characters that can not be in an XML attribute. - */function escapeAttribute(value) { return value.replace(/&/g, '&').replace(/'/g, ''').replace(//g, '>').replace(/"/g, '"'); }/** + */function escapeAttribute(value){return value.replace(/&/g,'&').replace(/'/g,''').replace(//g,'>').replace(/"/g,'"');}/** * @api private - */module.exports = { escapeAttribute: escapeAttribute }; - }, {}], 75: [function (require, module, exports) {/** + */module.exports={escapeAttribute:escapeAttribute};},{}],75:[function(require,module,exports){/** * Escapes characters that can not be in an XML element. - */function escapeElement(value) { return value.replace(/&/g, '&').replace(//g, '>'); }/** + */function escapeElement(value){return value.replace(/&/g,'&').replace(//g,'>');}/** * @api private - */module.exports = { escapeElement: escapeElement }; - }, {}], 76: [function (require, module, exports) { - var escapeAttribute = require('./escape-attribute').escapeAttribute;/** + */module.exports={escapeElement:escapeElement};},{}],76:[function(require,module,exports){var escapeAttribute=require('./escape-attribute').escapeAttribute;/** * Represents an XML node. * @api private - */function XmlNode(name, children) { if (children === void 0) { children = []; } this.name = name; this.children = children; this.attributes = {}; } XmlNode.prototype.addAttribute = function (name, value) { this.attributes[name] = value; return this; }; XmlNode.prototype.addChildNode = function (child) { this.children.push(child); return this; }; XmlNode.prototype.removeAttribute = function (name) { delete this.attributes[name]; return this; }; XmlNode.prototype.toString = function () { - var hasChildren = Boolean(this.children.length); var xmlText = '<' + this.name;// add attributes - var attributes = this.attributes; for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) { var attributeName = attributeNames[i]; var attribute = attributes[attributeName]; if (typeof attribute !== 'undefined' && attribute !== null) { xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"'; } } return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + ''; - };/** + */function XmlNode(name,children){if(children===void 0){children=[];}this.name=name;this.children=children;this.attributes={};}XmlNode.prototype.addAttribute=function(name,value){this.attributes[name]=value;return this;};XmlNode.prototype.addChildNode=function(child){this.children.push(child);return this;};XmlNode.prototype.removeAttribute=function(name){delete this.attributes[name];return this;};XmlNode.prototype.toString=function(){var hasChildren=Boolean(this.children.length);var xmlText='<'+this.name;// add attributes +var attributes=this.attributes;for(var i=0,attributeNames=Object.keys(attributes);i':'>'+this.children.map(function(c){return c.toString();}).join('')+'';};/** * @api private - */module.exports = { XmlNode: XmlNode }; - }, { "./escape-attribute": 74 }], 77: [function (require, module, exports) { - var escapeElement = require('./escape-element').escapeElement;/** + */module.exports={XmlNode:XmlNode};},{"./escape-attribute":74}],77:[function(require,module,exports){var escapeElement=require('./escape-element').escapeElement;/** * Represents an XML text value. * @api private - */function XmlText(value) { this.value = value; } XmlText.prototype.toString = function () { return escapeElement('' + this.value); };/** + */function XmlText(value){this.value=value;}XmlText.prototype.toString=function(){return escapeElement(''+this.value);};/** * @api private - */module.exports = { XmlText: XmlText }; - }, { "./escape-element": 75 }], 78: [function (require, module, exports) { - 'use strict'; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; }// Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; function getLens(b64) { - var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); }// Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('='); if (validLen === -1) validLen = len; var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; - }// base64 is 4/3 + up to two characters of the original data - function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { - var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0;// if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; var i; for (i = 0; i < len; i += 4) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[curByte++] = tmp >> 16 & 0xFF; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[curByte++] = tmp & 0xFF; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[curByte++] = tmp >> 8 & 0xFF; arr[curByte++] = tmp & 0xFF; } return arr; - } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16 & 0xFF0000) + (uint8[i + 1] << 8 & 0xFF00) + (uint8[i + 2] & 0xFF); output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { - var tmp; var len = uint8.length; var extraBytes = len % 3;// if we have 1 byte left, pad 2 bytes - var parts = []; var maxChunkLength = 16383;// must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); }// pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { tmp = uint8[len - 1]; parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 0x3F] + '=='); } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 0x3F] + lookup[tmp << 2 & 0x3F] + '='); } return parts.join(''); - } - }, {}], 79: [function (require, module, exports) { }, {}], 80: [function (require, module, exports) { - (function (global) { - (function () {/*! https://mths.be/punycode v1.3.2 by @mathias */; (function (root) {/** Detect free variables */var freeExports = _typeof(exports) == 'object' && exports && !exports.nodeType && exports; var freeModule = _typeof(module) == 'object' && module && !module.nodeType && module; var freeGlobal = _typeof(global) == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal) { root = freeGlobal; }/** + */module.exports={XmlText:XmlText};},{"./escape-element":75}],78:[function(require,module,exports){'use strict';exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array;var code='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(var i=0,len=code.length;i0){throw new Error('Invalid string. Length must be a multiple of 4');}// Trim off extra bytes after placeholder bytes are found +// See: https://github.com/beatgammit/base64-js/issues/42 +var validLen=b64.indexOf('=');if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen];}// base64 is 4/3 + up to two characters of the original data +function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;// if there are placeholders, only get up to the last complete 4 chars +var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&0xFF;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}return arr;}function tripletToBase64(num){return lookup[num>>18&0x3F]+lookup[num>>12&0x3F]+lookup[num>>6&0x3F]+lookup[num&0x3F];}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength));}// pad the end with zeros, but make sure to not forget the extra bytes +if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&0x3F]+'==');}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&0x3F]+lookup[tmp<<2&0x3F]+'=');}return parts.join('');}},{}],79:[function(require,module,exports){},{}],80:[function(require,module,exports){(function(global){(function(){/*! https://mths.be/punycode v1.3.2 by @mathias */;(function(root){/** Detect free variables */var freeExports=_typeof(exports)=='object'&&exports&&!exports.nodeType&&exports;var freeModule=_typeof(module)=='object'&&module&&!module.nodeType&&module;var freeGlobal=_typeof(global)=='object'&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal){root=freeGlobal;}/** * The `punycode` object. * @name punycode * @type Object - */var punycode,/** Highest positive signed 32-bit float value */maxInt = 2147483647,// aka. 0x7FFFFFFF or 2^31-1 -/** Bootstring parameters */base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128,// 0x80 - delimiter = '-',// '\x2D' -/** Regular expressions */regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/,// unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g,// RFC 3490 separators -/** Error messages */errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' },/** Convenience shortcuts */baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*/ /** + */var punycode,/** Highest positive signed 32-bit float value */maxInt=2147483647,// aka. 0x7FFFFFFF or 2^31-1 +/** Bootstring parameters */base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,// 0x80 +delimiter='-',// '\x2D' +/** Regular expressions */regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,// unprintable ASCII chars + non-ASCII chars +regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,// RFC 3490 separators +/** Error messages */errors={'overflow':'Overflow: input needs wider integers to process','not-basic':'Illegal input >= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. - */function error(type) { throw RangeError(errors[type]); }/** + */function error(type){throw RangeError(errors[type]);}/** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. - */function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; }/** + */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private @@ -5447,13 +4856,10 @@ * character. * @returns {Array} A new string of characters returned by the callback * function. - */function mapDomain(string, fn) { - var parts = string.split('@'); var result = ''; if (parts.length > 1) {// In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; string = parts[1]; - }// Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; - }/** + */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave +// the local part (i.e. everything up to `@`) intact. +result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. +string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which @@ -5465,25 +4871,18 @@ * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. - */function ucs2decode(string) { - var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { - value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) {// high surrogate, and there is a next character - extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) {// low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else {// unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); counter--; - } - } else { output.push(value); } - } return output; - }/** + */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=0xD800&&value<=0xDBFF&&counter 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); }/** + */function ucs2encode(array){return map(array,function(value){var output='';if(value>0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private @@ -5491,7 +4890,7 @@ * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. - */function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; }/** + */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private @@ -5501,63 +4900,53 @@ * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. - */function digitToBasic(digit, flag) {// 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - }/** + */function digitToBasic(digit,flag){// 0..25 map to ASCII a..z or A..Z +// 26..35 map to ASCII 0..9 +return digit+22+75*(digit<26)-((flag!=0)<<5);}/** * Bias adaptation function as per section 3.4 of RFC 3492. * http://tools.ietf.org/html/rfc3492#section-3.4 * @private - */function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for/* no initialization */(; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }/** + */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for/* no initialization */(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. - */function decode(input) {// Don't use UCS-2 - var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) {// if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); - }// Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - for/* no final expression */(index = basic > 0 ? basic + 1 : 0; index < inputLength;) {// `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for/* no condition */(oldi = i, w = 1, k = base; ; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0);// `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out;// Insert `n` at position `i` of the output - output.splice(i++, 0, n); - } return ucs2encode(output); - }/** + */function decode(input){// Don't use UCS-2 +var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code +// points before the last delimiter, or `0` if there is none, then copy +// the first basic code points to the output. +basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code +// points were copied; start at the beginning otherwise. +for/* no final expression */(index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, +// incrementing `n` each time, so we'll fix that now: +if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output +output.splice(i++,0,n);}return ucs2encode(output);}/** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. - */function encode(input) { - var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne, baseMinusT, qMinusT;// Convert the input in UCS-2 to Unicode - input = ucs2decode(input);// Cache the length - inputLength = input.length;// Initialize the state - n = initialN; delta = 0; bias = initialBias;// Handle the basic code points - for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length;// `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { output.push(delimiter); }// Main encoding loop: - while (handledCPCount < inputLength) {// All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } }// Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) {// Represent delta as a generalized variable-length integer - for/* no condition */(q = delta, k = base; ; k += base) { t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; - } - } ++delta; ++n; - } return output.join(''); - }/** + */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode +input=ucs2decode(input);// Cache the length +inputLength=input.length;// Initialize the state +n=initialN;delta=0;bias=initialBias;// Handle the basic code points +for(j=0;j=n&¤tValue state to , +// but guard against overflow +handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer +for/* no condition */(q=delta,k=base;;k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q * @memberOf punycode * @type Object - */'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode - };/** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if (true && _typeof(__webpack_require__.amdO) == 'object' && __webpack_require__.amdO) { - !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return punycode; }).call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) {// in Node.js or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else {// in Narwhal or RingoJS v0.7.0- - for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } - } - } else {// in Rhino or a web browser - root.punycode = punycode; - } - })(this); - }).call(this); - }).call(this, typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); - }, {}], 81: [function (require, module, exports) { - (function (global, Buffer) { - (function () {/*! + */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns +// like the following: +if( true&&_typeof(__webpack_require__.amdO)=='object'&&__webpack_require__.amdO){!(__WEBPACK_AMD_DEFINE_RESULT__ = (function(){return punycode;}).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}else if(freeExports&&freeModule){if(module.exports==freeExports){// in Node.js or RingoJS v0.8.0+ +freeModule.exports=punycode;}else{// in Narwhal or RingoJS v0.7.0- +for(key in punycode){punycode.hasOwnProperty(key)&&(freeExports[key]=punycode[key]);}}}else{// in Rhino or a web browser +root.punycode=punycode;}})(this);}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{}],81:[function(require,module,exports){(function(global,Buffer){(function(){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */ /* eslint-disable no-proto */'use strict'; var base64 = require('base64-js'); var ieee754 = require('ieee754'); var isArray = require('isarray'); exports.Buffer = Buffer; exports.SlowBuffer = SlowBuffer; exports.INSPECT_MAX_BYTES = 50;/** + */ /* eslint-disable no-proto */'use strict';var base64=require('base64-js');var ieee754=require('ieee754');var isArray=require('isarray');exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;/** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) @@ -5635,21 +5010,14 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. - */Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport();/* + */Buffer.TYPED_ARRAY_SUPPORT=global.TYPED_ARRAY_SUPPORT!==undefined?global.TYPED_ARRAY_SUPPORT:typedArraySupport();/* * Export kMaxLength after typed array support is determined. - */exports.kMaxLength = kMaxLength(); function typedArraySupport() { - try { - var arr = new Uint8Array(1); arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function foo() { return 42; } }; return arr.foo() === 42 &&// typed array instances can be augmented - typeof arr.subarray === 'function' &&// chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0;// ie10 has broken `subarray` - } catch (e) { return false; } - } function kMaxLength() { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; } function createBuffer(that, length) { - if (kMaxLength() < length) { throw new RangeError('Invalid typed array length'); } if (Buffer.TYPED_ARRAY_SUPPORT) {// Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); that.__proto__ = Buffer.prototype; - } else {// Fallback: Return an object instance of the Buffer class - if (that === null) { that = new Buffer(length); } that.length = length; - } return that; - }/** + */exports.kMaxLength=kMaxLength();function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function foo(){return 42;}};return arr.foo()===42&&// typed array instances can be augmented +typeof arr.subarray==='function'&&// chrome 9-10 lack `subarray` +arr.subarray(1,1).byteLength===0;// ie10 has broken `subarray` +}catch(e){return false;}}function kMaxLength(){return Buffer.TYPED_ARRAY_SUPPORT?0x7fffffff:0x3fffffff;}function createBuffer(that,length){if(kMaxLength()= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); } return length | 0; - } function SlowBuffer(length) { - if (+length != length) {// eslint-disable-line eqeqeq - length = 0; - } return Buffer.alloc(+length); - } Buffer.isBuffer = function isBuffer(b) { return !!(b != null && b._isBuffer); }; Buffer.compare = function compare(a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { return string.length; } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength; } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0;// Use a for loop to avoid recursion - var loweredCase = false; for (; ;) { - switch (encoding) { - case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) return utf8ToBytes(string).length;// assume utf8 - encoding = ('' + encoding).toLowerCase(); loweredCase = true; - } - } - } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { - var loweredCase = false;// No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { start = 0; }// Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; }// Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } - }// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length | 0; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = exports.INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return ''; }; Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer'); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; };// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {// Empty buffer means no match - if (buffer.length === 0) return -1;// Normalize byteOffset - if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset;// Coerce to Number. - if (isNaN(byteOffset)) {// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - }// Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1; else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0; else return -1; }// Normalize val - if (typeof val === 'string') { val = Buffer.from(val, encoding); }// Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) {// Special case: looking for empty string/buffer always fails - if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF;// Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } throw new TypeError('val must be string, number or Buffer'); - } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } }// must be an even number of digits - var strLen = string.length; if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (isNaN(parsed)) return i; buf[offset + i] = parsed; } return i; - } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function latin1Write(buf, string, offset, length) { return asciiWrite(buf, string, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) {// Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; length = this.length; offset = 0;// Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; length = this.length; offset = 0;// Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; if (isFinite(length)) { length = length | 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; }// legacy write(string, encoding, offset, length) - remove in v0.13 - } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (; ;) { - switch (encoding) { - case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': return asciiWrite(this, string, offset, length); case 'latin1': case 'binary': return latin1Write(this, string, offset, length); case 'base64':// Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; - } - } - }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf); } else { return base64.fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { - var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) {// we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) {// encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; - } res.push(codePoint); i += bytesPerSequence; - } return decodeCodePointsArray(res); - }// Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { - var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints);// avoid extra slice() - }// Decode in chunks to avoid "call stack size exceeded". - var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; - } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf; if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); newBuf.__proto__ = Buffer.prototype; } else { var sliceLen = end - start; newBuf = new Buffer(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } } return newBuf; };/* + */Buffer.allocUnsafeSlow=function(size){return allocUnsafe(null,size);};function fromString(that,string,encoding){if(typeof encoding!=='string'||encoding===''){encoding='utf8';}if(!Buffer.isEncoding(encoding)){throw new TypeError('"encoding" must be a valid string encoding');}var length=byteLength(string,encoding)|0;that=createBuffer(that,length);var actual=that.write(string,encoding);if(actual!==length){// Writing a hex string, for example, that contains invalid characters will +// cause everything after the first invalid character to be ignored. (e.g. +// 'abxxcd' will be treated as 'ab') +that=that.slice(0,actual);}return that;}function fromArrayLike(that,array){var length=array.length<0?0:checked(array.length)|0;that=createBuffer(that,length);for(var i=0;i=kMaxLength()){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+kMaxLength().toString(16)+' bytes');}return length|0;}function SlowBuffer(length){if(+length!=length){// eslint-disable-line eqeqeq +length=0;}return Buffer.alloc(+length);}Buffer.isBuffer=function isBuffer(b){return!!(b!=null&&b._isBuffer);};Buffer.compare=function compare(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('Arguments must be Buffers');}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i>>1;case'base64':return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;// assume utf8 +encoding=(''+encoding).toLowerCase();loweredCase=true;}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;// No need to verify that "this.length <= MAX_UINT32" since it's a read-only +// property of a typed array. +// This behaves neither like String nor Uint8Array in that we set start/end +// to their upper/lower bounds if the value passed is out of range. +// undefined is handled specially as per ECMA-262 6th Edition, +// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. +if(start===undefined||start<0){start=0;}// Return early if start > this.length. Done here to prevent potential uint32 +// coercion fail below. +if(start>this.length){return'';}if(end===undefined||end>this.length){end=this.length;}if(end<=0){return'';}// Force coersion to uint32. This will also coerce falsey/NaN values to 0. +end>>>=0;start>>>=0;if(end<=start){return'';}if(!encoding)encoding='utf8';while(true){switch(encoding){case'hex':return hexSlice(this,start,end);case'utf8':case'utf-8':return utf8Slice(this,start,end);case'ascii':return asciiSlice(this,start,end);case'latin1':case'binary':return latin1Slice(this,start,end);case'base64':return base64Slice(this,start,end);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(encoding+'').toLowerCase();loweredCase=true;}}}// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i;}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError('Buffer size must be a multiple of 16-bits');}for(var i=0;i0){str=this.toString('hex',0,max).match(/.{2}/g).join(' ');if(this.length>max)str+=' ... ';}return'';};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(!Buffer.isBuffer(target)){throw new TypeError('Argument must be a Buffer');}if(start===undefined){start=0;}if(end===undefined){end=target?target.length:0;}if(thisStart===undefined){thisStart=0;}if(thisEnd===undefined){thisEnd=this.length;}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError('out of range index');}if(thisStart>=thisEnd&&start>=end){return 0;}if(thisStart>=thisEnd){return-1;}if(start>=end){return 1;}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){// Empty buffer means no match +if(buffer.length===0)return-1;// Normalize byteOffset +if(typeof byteOffset==='string'){encoding=byteOffset;byteOffset=0;}else if(byteOffset>0x7fffffff){byteOffset=0x7fffffff;}else if(byteOffset<-0x80000000){byteOffset=-0x80000000;}byteOffset=+byteOffset;// Coerce to Number. +if(isNaN(byteOffset)){// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer +byteOffset=dir?0:buffer.length-1;}// Normalize byteOffset: negative offsets start from the end of the buffer +if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1;}else if(byteOffset<0){if(dir)byteOffset=0;else return-1;}// Normalize val +if(typeof val==='string'){val=Buffer.from(val,encoding);}// Finally, search either indexOf (if dir is true) or lastIndexOf +if(Buffer.isBuffer(val)){// Special case: looking for empty string/buffer always fails +if(val.length===0){return-1;}return arrayIndexOf(buffer,val,byteOffset,encoding,dir);}else if(typeof val==='number'){val=val&0xFF;// Search for a byte value [0-255] +if(Buffer.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==='function'){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir);}throw new TypeError('val must be string, number or Buffer');}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==='ucs2'||encoding==='ucs-2'||encoding==='utf16le'||encoding==='utf-16le'){if(arr.length<2||val.length<2){return-1;}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2;}}function read(buf,i){if(indexSize===1){return buf[i];}else{return buf.readUInt16BE(i*indexSize);}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining;}}// must be an even number of digits +var strLen=string.length;if(strLen%2!==0)throw new TypeError('Invalid hex string');if(length>strLen/2){length=strLen/2;}for(var i=0;iremaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError('Attempt to write outside buffer bounds');}if(!encoding)encoding='utf8';var loweredCase=false;for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length);case'utf8':case'utf-8':return utf8Write(this,string,offset,length);case'ascii':return asciiWrite(this,string,offset,length);case'latin1':case'binary':return latin1Write(this,string,offset,length);case'base64':// Warning: maxLength not taken into account in base64Write +return base64Write(this,string,offset,length);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(''+encoding).toLowerCase();loweredCase=true;}}};Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)};};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf);}else{return base64.fromByteArray(buf.slice(start,end));}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i0xEF?4:firstByte>0xDF?3:firstByte>0xBF?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte;}break;case 2:secondByte=buf[i+1];if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|secondByte&0x3F;if(tempCodePoint>0x7F){codePoint=tempCodePoint;}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|thirdByte&0x3F;if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint;}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|fourthByte&0x3F;if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint;}}}}if(codePoint===null){// we did not generate a valid codePoint so insert a +// replacement char (U+FFFD) and advance only 1 byte +codePoint=0xFFFD;bytesPerSequence=1;}else if(codePoint>0xFFFF){// encode to utf16 (surrogate pair dance) +codePoint-=0x10000;res.push(codePoint>>>10&0x3FF|0xD800);codePoint=0xDC00|codePoint&0x3FF;}res.push(codePoint);i+=bytesPerSequence;}return decodeCodePointsArray(res);}// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH=0x1000;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints);// avoid extra slice() +}// Decode in chunks to avoid "call stack size exceeded". +var res='';var i=0;while(ilen)end=len;var out='';for(var i=start;ilen){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(end length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ieee754.read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return ieee754.read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = value & 0xff; return offset + 1; }; function objectWriteUInt16(buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; } } Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; function objectWriteUInt32(buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; } } Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38); } ieee754.write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308); } ieee754.write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); };// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy(target, targetStart, start, end) { - if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start;// Copy 0 bytes; we're done - if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0;// Fatal error conditions - if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); if (end < 0) throw new RangeError('sourceEnd out of bounds');// Are we oob? - if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; var i; if (this === target && start < targetStart && targetStart < end) {// descending copy from end - for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {// ascending copy from start - for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; } - } else { Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); } return len; - };// Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill(val, start, end, encoding) {// Handle string cases: - if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (val.length === 1) { var code = val.charCodeAt(0); if (code < 256) { val = code; } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } } else if (typeof val === 'number') { val = val & 255; }// Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; - };// HELPER FUNCTIONS - // ================ - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; function base64clean(str) {// Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '');// Node converts strings with length < 2 to '' - if (str.length < 2) return '';// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { str = str + '='; } return str; - } function stringtrim(str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(string, units) { - units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i);// is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) {// last char was a lead - if (!leadSurrogate) {// no lead yet - if (codePoint > 0xDBFF) {// unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; - } else if (i + 1 === length) {// unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; - }// valid lead - leadSurrogate = codePoint; continue; - }// 2 leads in a row - if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; }// valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) {// valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } leadSurrogate = null;// encode utf8 - if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } - } return bytes; - } function asciiToBytes(str) { - var byteArray = []; for (var i = 0; i < str.length; ++i) {// Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } return byteArray; - } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return base64.toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } function isnan(val) { - return val !== val;// eslint-disable-line no-self-compare - } - }).call(this); - }).call(this, typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}, require("buffer").Buffer); - }, { "base64-js": 78, "buffer": 81, "ieee754": 83, "isarray": 84 }], 82: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter;// Backwards-compat with node 0.10.x - EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined;// By default EventEmitters will print a warning if more than 10 listeners are - // added to it. This is a useful default which helps finding memory leaks. - EventEmitter.defaultMaxListeners = 10;// Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - EventEmitter.prototype.setMaxListeners = function (n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function (type) { - var er, handler, len, args, i, listeners; if (!this._events) this._events = {};// If there is no 'error' event listener then throw. - if (type === 'error') { - if (!this._events.error || isObject(this._events.error) && !this._events.error.length) { - er = arguments[1]; if (er instanceof Error) { - throw er;// Unhandled 'error' event - } else {// At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; - } - } - } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { - switch (arguments.length) {// fast cases - case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break;// slower - default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); - } - } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++)listeners[i].apply(this, args); } return true; - }; EventEmitter.prototype.addListener = function (type, listener) { - var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {};// To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type])// Optimize the case of one listener. Don't need the extra array object. - this._events[type] = listener; else if (isObject(this._events[type]))// If we've already got an array, just append. - this._events[type].push(listener); else// Adding the second element, need to change to array. - this._events[type] = [this._events[type], listener];// Check for listener leak - if (isObject(this._events[type]) && !this._events[type].warned) { - if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { - this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') {// not supported in IE 10 - console.trace(); - } - } - } return this; - }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function (type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; };// emits a 'removeListener' event iff the listener was removed - EventEmitter.prototype.removeListener = function (type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || isFunction(list.listener) && list.listener === listener) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || list[i].listener && list[i].listener === listener) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function (type) { - var key, listeners; if (!this._events) return this;// not listening for removeListener, no need to emit - if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; }// emit removeListener for all listeners on all events - if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) {// LIFO order - while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); - } delete this._events[type]; return this; - }; EventEmitter.prototype.listeners = function (type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function (type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function (emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return _typeof(arg) === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } - }, {}], 83: [function (require, module, exports) { exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { } m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { } if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); }; exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) { } e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) { } buffer[offset + i - d] |= s * 128; }; }, {}], 84: [function (require, module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; }, {}], 85: [function (require, module, exports) { - (function (exports) { - "use strict"; function isArray(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Array]"; } else { return false; } } function isObject(obj) { if (obj !== null) { return Object.prototype.toString.call(obj) === "[object Object]"; } else { return false; } } function strictDeepEqual(first, second) {// Check the scalar case first. - if (first === second) { return true; }// Check if they are the same type. - var firstType = Object.prototype.toString.call(first); if (firstType !== Object.prototype.toString.call(second)) { return false; }// We know that first and second have the same type so we can just check the - // first type from now on. - if (isArray(first) === true) {// Short circuit if they're not the same length; - if (first.length !== second.length) { return false; } for (var i = 0; i < first.length; i++) { if (strictDeepEqual(first[i], second[i]) === false) { return false; } } return true; - } if (isObject(first) === true) {// An object is equal if it has the same key/value pairs. - var keysSeen = {}; for (var key in first) { if (hasOwnProperty.call(first, key)) { if (strictDeepEqual(first[key], second[key]) === false) { return false; } keysSeen[key] = true; } }// Now check that there aren't any keys in second that weren't - // in first. - for (var key2 in second) { if (hasOwnProperty.call(second, key2)) { if (keysSeen[key2] !== true) { return false; } } } return true; - } return false; - } function isFalse(obj) {// From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value - // First check the scalar values. - if (obj === "" || obj === false || obj === null) { return true; } else if (isArray(obj) && obj.length === 0) {// Check for an empty array. - return true; - } else if (isObject(obj)) {// Check for an empty object. - for (var key in obj) {// If there are any keys, then - // the object is not empty so the object - // is not false. - if (obj.hasOwnProperty(key)) { return false; } - } return true; - } else { return false; } - } function objValues(obj) { var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; } function merge(a, b) { var merged = {}; for (var key in a) { merged[key] = a[key]; } for (var key2 in b) { merged[key2] = b[key2]; } return merged; } var trimLeft; if (typeof String.prototype.trimLeft === "function") { trimLeft = function trimLeft(str) { return str.trimLeft(); }; } else { trimLeft = function trimLeft(str) { return str.match(/^\s*(.*)/)[1]; }; }// Type constants used to define functions. - var TYPE_NUMBER = 0; var TYPE_ANY = 1; var TYPE_STRING = 2; var TYPE_ARRAY = 3; var TYPE_OBJECT = 4; var TYPE_BOOLEAN = 5; var TYPE_EXPREF = 6; var TYPE_NULL = 7; var TYPE_ARRAY_NUMBER = 8; var TYPE_ARRAY_STRING = 9; var TOK_EOF = "EOF"; var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; var TOK_RBRACKET = "Rbracket"; var TOK_RPAREN = "Rparen"; var TOK_COMMA = "Comma"; var TOK_COLON = "Colon"; var TOK_RBRACE = "Rbrace"; var TOK_NUMBER = "Number"; var TOK_CURRENT = "Current"; var TOK_EXPREF = "Expref"; var TOK_PIPE = "Pipe"; var TOK_OR = "Or"; var TOK_AND = "And"; var TOK_EQ = "EQ"; var TOK_GT = "GT"; var TOK_LT = "LT"; var TOK_GTE = "GTE"; var TOK_LTE = "LTE"; var TOK_NE = "NE"; var TOK_FLATTEN = "Flatten"; var TOK_STAR = "Star"; var TOK_FILTER = "Filter"; var TOK_DOT = "Dot"; var TOK_NOT = "Not"; var TOK_LBRACE = "Lbrace"; var TOK_LBRACKET = "Lbracket"; var TOK_LPAREN = "Lparen"; var TOK_LITERAL = "Literal";// The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. - var basicTokens = { ".": TOK_DOT, "*": TOK_STAR, ",": TOK_COMMA, ":": TOK_COLON, "{": TOK_LBRACE, "}": TOK_RBRACE, "]": TOK_RBRACKET, "(": TOK_LPAREN, ")": TOK_RPAREN, "@": TOK_CURRENT }; var operatorStartToken = { "<": true, ">": true, "=": true, "!": true }; var skipChars = { " ": true, "\t": true, "\n": true }; function isAlpha(ch) { return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch === "_"; } function isNum(ch) { return ch >= "0" && ch <= "9" || ch === "-"; } function isAlphaNum(ch) { return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z" || ch >= "0" && ch <= "9" || ch === "_"; } function Lexer() { } Lexer.prototype = { - tokenize: function tokenize(stream) { - var tokens = []; this._current = 0; var start; var identifier; var token; while (this._current < stream.length) { - if (isAlpha(stream[this._current])) { start = this._current; identifier = this._consumeUnquotedIdentifier(stream); tokens.push({ type: TOK_UNQUOTEDIDENTIFIER, value: identifier, start: start }); } else if (basicTokens[stream[this._current]] !== undefined) { tokens.push({ type: basicTokens[stream[this._current]], value: stream[this._current], start: this._current }); this._current++; } else if (isNum(stream[this._current])) { token = this._consumeNumber(stream); tokens.push(token); } else if (stream[this._current] === "[") {// No need to increment this._current. This happens - // in _consumeLBracket - token = this._consumeLBracket(stream); tokens.push(token); - } else if (stream[this._current] === "\"") { start = this._current; identifier = this._consumeQuotedIdentifier(stream); tokens.push({ type: TOK_QUOTEDIDENTIFIER, value: identifier, start: start }); } else if (stream[this._current] === "'") { start = this._current; identifier = this._consumeRawStringLiteral(stream); tokens.push({ type: TOK_LITERAL, value: identifier, start: start }); } else if (stream[this._current] === "`") { start = this._current; var literal = this._consumeLiteral(stream); tokens.push({ type: TOK_LITERAL, value: literal, start: start }); } else if (operatorStartToken[stream[this._current]] !== undefined) { tokens.push(this._consumeOperator(stream)); } else if (skipChars[stream[this._current]] !== undefined) {// Ignore whitespace. - this._current++; - } else if (stream[this._current] === "&") { start = this._current; this._current++; if (stream[this._current] === "&") { this._current++; tokens.push({ type: TOK_AND, value: "&&", start: start }); } else { tokens.push({ type: TOK_EXPREF, value: "&", start: start }); } } else if (stream[this._current] === "|") { start = this._current; this._current++; if (stream[this._current] === "|") { this._current++; tokens.push({ type: TOK_OR, value: "||", start: start }); } else { tokens.push({ type: TOK_PIPE, value: "|", start: start }); } } else { var error = new Error("Unknown character:" + stream[this._current]); error.name = "LexerError"; throw error; } - } return tokens; - }, _consumeUnquotedIdentifier: function _consumeUnquotedIdentifier(stream) { var start = this._current; this._current++; while (this._current < stream.length && isAlphaNum(stream[this._current])) { this._current++; } return stream.slice(start, this._current); }, _consumeQuotedIdentifier: function _consumeQuotedIdentifier(stream) { - var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "\"" && this._current < maxLength) {// You can escape a double quote and you can escape an escape. - var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "\"")) { current += 2; } else { current++; } this._current = current; - } this._current++; return JSON.parse(stream.slice(start, this._current)); - }, _consumeRawStringLiteral: function _consumeRawStringLiteral(stream) { - var start = this._current; this._current++; var maxLength = stream.length; while (stream[this._current] !== "'" && this._current < maxLength) {// You can escape a single quote and you can escape an escape. - var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "'")) { current += 2; } else { current++; } this._current = current; - } this._current++; var literal = stream.slice(start + 1, this._current - 1); return literal.replace("\\'", "'"); - }, _consumeNumber: function _consumeNumber(stream) { var start = this._current; this._current++; var maxLength = stream.length; while (isNum(stream[this._current]) && this._current < maxLength) { this._current++; } var value = parseInt(stream.slice(start, this._current)); return { type: TOK_NUMBER, value: value, start: start }; }, _consumeLBracket: function _consumeLBracket(stream) { var start = this._current; this._current++; if (stream[this._current] === "?") { this._current++; return { type: TOK_FILTER, value: "[?", start: start }; } else if (stream[this._current] === "]") { this._current++; return { type: TOK_FLATTEN, value: "[]", start: start }; } else { return { type: TOK_LBRACKET, value: "[", start: start }; } }, _consumeOperator: function _consumeOperator(stream) { var start = this._current; var startingChar = stream[start]; this._current++; if (startingChar === "!") { if (stream[this._current] === "=") { this._current++; return { type: TOK_NE, value: "!=", start: start }; } else { return { type: TOK_NOT, value: "!", start: start }; } } else if (startingChar === "<") { if (stream[this._current] === "=") { this._current++; return { type: TOK_LTE, value: "<=", start: start }; } else { return { type: TOK_LT, value: "<", start: start }; } } else if (startingChar === ">") { if (stream[this._current] === "=") { this._current++; return { type: TOK_GTE, value: ">=", start: start }; } else { return { type: TOK_GT, value: ">", start: start }; } } else if (startingChar === "=") { if (stream[this._current] === "=") { this._current++; return { type: TOK_EQ, value: "==", start: start }; } } }, _consumeLiteral: function _consumeLiteral(stream) { - this._current++; var start = this._current; var maxLength = stream.length; var literal; while (stream[this._current] !== "`" && this._current < maxLength) {// You can escape a literal char or you can escape the escape. - var current = this._current; if (stream[current] === "\\" && (stream[current + 1] === "\\" || stream[current + 1] === "`")) { current += 2; } else { current++; } this._current = current; - } var literalString = trimLeft(stream.slice(start, this._current)); literalString = literalString.replace("\\`", "`"); if (this._looksLikeJSON(literalString)) { literal = JSON.parse(literalString); } else {// Try to JSON parse it as "" - literal = JSON.parse("\"" + literalString + "\""); - }// +1 gets us to the ending "`", +1 to move on to the next char. - this._current++; return literal; - }, _looksLikeJSON: function _looksLikeJSON(literalString) { var startingChars = "[{\""; var jsonLiterals = ["true", "false", "null"]; var numberLooking = "-0123456789"; if (literalString === "") { return false; } else if (startingChars.indexOf(literalString[0]) >= 0) { return true; } else if (jsonLiterals.indexOf(literalString) >= 0) { return true; } else if (numberLooking.indexOf(literalString[0]) >= 0) { try { JSON.parse(literalString); return true; } catch (ex) { return false; } } else { return false; } } - }; var bindingPower = {}; bindingPower[TOK_EOF] = 0; bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; bindingPower[TOK_QUOTEDIDENTIFIER] = 0; bindingPower[TOK_RBRACKET] = 0; bindingPower[TOK_RPAREN] = 0; bindingPower[TOK_COMMA] = 0; bindingPower[TOK_RBRACE] = 0; bindingPower[TOK_NUMBER] = 0; bindingPower[TOK_CURRENT] = 0; bindingPower[TOK_EXPREF] = 0; bindingPower[TOK_PIPE] = 1; bindingPower[TOK_OR] = 2; bindingPower[TOK_AND] = 3; bindingPower[TOK_EQ] = 5; bindingPower[TOK_GT] = 5; bindingPower[TOK_LT] = 5; bindingPower[TOK_GTE] = 5; bindingPower[TOK_LTE] = 5; bindingPower[TOK_NE] = 5; bindingPower[TOK_FLATTEN] = 9; bindingPower[TOK_STAR] = 20; bindingPower[TOK_FILTER] = 21; bindingPower[TOK_DOT] = 40; bindingPower[TOK_NOT] = 45; bindingPower[TOK_LBRACE] = 50; bindingPower[TOK_LBRACKET] = 55; bindingPower[TOK_LPAREN] = 60; function Parser() { } Parser.prototype = { - parse: function parse(expression) { this._loadTokens(expression); this.index = 0; var ast = this.expression(0); if (this._lookahead(0) !== TOK_EOF) { var t = this._lookaheadToken(0); var error = new Error("Unexpected token type: " + t.type + ", value: " + t.value); error.name = "ParserError"; throw error; } return ast; }, _loadTokens: function _loadTokens(expression) { var lexer = new Lexer(); var tokens = lexer.tokenize(expression); tokens.push({ type: TOK_EOF, value: "", start: expression.length }); this.tokens = tokens; }, expression: function expression(rbp) { var leftToken = this._lookaheadToken(0); this._advance(); var left = this.nud(leftToken); var currentToken = this._lookahead(0); while (rbp < bindingPower[currentToken]) { this._advance(); left = this.led(currentToken, left); currentToken = this._lookahead(0); } return left; }, _lookahead: function _lookahead(number) { return this.tokens[this.index + number].type; }, _lookaheadToken: function _lookaheadToken(number) { return this.tokens[this.index + number]; }, _advance: function _advance() { this.index++; }, nud: function nud(token) { - var left; var right; var expression; switch (token.type) { - case TOK_LITERAL: return { type: "Literal", value: token.value }; case TOK_UNQUOTEDIDENTIFIER: return { type: "Field", name: token.value }; case TOK_QUOTEDIDENTIFIER: var node = { type: "Field", name: token.value }; if (this._lookahead(0) === TOK_LPAREN) { throw new Error("Quoted identifier not allowed for function names."); } else { return node; } break; case TOK_NOT: right = this.expression(bindingPower.Not); return { type: "NotExpression", children: [right] }; case TOK_STAR: left = { type: "Identity" }; right = null; if (this._lookahead(0) === TOK_RBRACKET) {// This can happen in a multiselect, - // [a, b, *] - right = { type: "Identity" }; - } else { right = this._parseProjectionRHS(bindingPower.Star); } return { type: "ValueProjection", children: [left, right] }; case TOK_FILTER: return this.led(token.type, { type: "Identity" }); case TOK_LBRACE: return this._parseMultiselectHash(); case TOK_FLATTEN: left = { type: TOK_FLATTEN, children: [{ type: "Identity" }] }; right = this._parseProjectionRHS(bindingPower.Flatten); return { type: "Projection", children: [left, right] }; case TOK_LBRACKET: if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice({ type: "Identity" }, right); } else if (this._lookahead(0) === TOK_STAR && this._lookahead(1) === TOK_RBRACKET) { this._advance(); this._advance(); right = this._parseProjectionRHS(bindingPower.Star); return { type: "Projection", children: [{ type: "Identity" }, right] }; } else { return this._parseMultiselectList(); } break; case TOK_CURRENT: return { type: TOK_CURRENT }; case TOK_EXPREF: expression = this.expression(bindingPower.Expref); return { type: "ExpressionReference", children: [expression] }; case TOK_LPAREN: var args = []; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = { type: TOK_CURRENT }; this._advance(); } else { expression = this.expression(0); } args.push(expression); } this._match(TOK_RPAREN); return args[0]; default: this._errorToken(token); - } - }, led: function led(tokenName, left) { - var right; switch (tokenName) { - case TOK_DOT: var rbp = bindingPower.Dot; if (this._lookahead(0) !== TOK_STAR) { right = this._parseDotRHS(rbp); return { type: "Subexpression", children: [left, right] }; } else {// Creating a projection. - this._advance(); right = this._parseProjectionRHS(rbp); return { type: "ValueProjection", children: [left, right] }; - } break; case TOK_PIPE: right = this.expression(bindingPower.Pipe); return { type: TOK_PIPE, children: [left, right] }; case TOK_OR: right = this.expression(bindingPower.Or); return { type: "OrExpression", children: [left, right] }; case TOK_AND: right = this.expression(bindingPower.And); return { type: "AndExpression", children: [left, right] }; case TOK_LPAREN: var name = left.name; var args = []; var expression, node; while (this._lookahead(0) !== TOK_RPAREN) { if (this._lookahead(0) === TOK_CURRENT) { expression = { type: TOK_CURRENT }; this._advance(); } else { expression = this.expression(0); } if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } args.push(expression); } this._match(TOK_RPAREN); node = { type: "Function", name: name, children: args }; return node; case TOK_FILTER: var condition = this.expression(0); this._match(TOK_RBRACKET); if (this._lookahead(0) === TOK_FLATTEN) { right = { type: "Identity" }; } else { right = this._parseProjectionRHS(bindingPower.Filter); } return { type: "FilterProjection", children: [left, right, condition] }; case TOK_FLATTEN: var leftNode = { type: TOK_FLATTEN, children: [left] }; var rightNode = this._parseProjectionRHS(bindingPower.Flatten); return { type: "Projection", children: [leftNode, rightNode] }; case TOK_EQ: case TOK_NE: case TOK_GT: case TOK_GTE: case TOK_LT: case TOK_LTE: return this._parseComparator(left, tokenName); case TOK_LBRACKET: var token = this._lookaheadToken(0); if (token.type === TOK_NUMBER || token.type === TOK_COLON) { right = this._parseIndexExpression(); return this._projectIfSlice(left, right); } else { this._match(TOK_STAR); this._match(TOK_RBRACKET); right = this._parseProjectionRHS(bindingPower.Star); return { type: "Projection", children: [left, right] }; } break; default: this._errorToken(this._lookaheadToken(0)); - } - }, _match: function _match(tokenType) { if (this._lookahead(0) === tokenType) { this._advance(); } else { var t = this._lookaheadToken(0); var error = new Error("Expected " + tokenType + ", got: " + t.type); error.name = "ParserError"; throw error; } }, _errorToken: function _errorToken(token) { var error = new Error("Invalid token (" + token.type + "): \"" + token.value + "\""); error.name = "ParserError"; throw error; }, _parseIndexExpression: function _parseIndexExpression() { if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { return this._parseSliceExpression(); } else { var node = { type: "Index", value: this._lookaheadToken(0).value }; this._advance(); this._match(TOK_RBRACKET); return node; } }, _projectIfSlice: function _projectIfSlice(left, right) { var indexExpr = { type: "IndexExpression", children: [left, right] }; if (right.type === "Slice") { return { type: "Projection", children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] }; } else { return indexExpr; } }, _parseSliceExpression: function _parseSliceExpression() {// [start:end:step] where each part is optional, as well as the last - // colon. - var parts = [null, null, null]; var index = 0; var currentToken = this._lookahead(0); while (currentToken !== TOK_RBRACKET && index < 3) { if (currentToken === TOK_COLON) { index++; this._advance(); } else if (currentToken === TOK_NUMBER) { parts[index] = this._lookaheadToken(0).value; this._advance(); } else { var t = this._lookahead(0); var error = new Error("Syntax error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "Parsererror"; throw error; } currentToken = this._lookahead(0); } this._match(TOK_RBRACKET); return { type: "Slice", children: parts }; - }, _parseComparator: function _parseComparator(left, comparator) { var right = this.expression(bindingPower[comparator]); return { type: "Comparator", name: comparator, children: [left, right] }; }, _parseDotRHS: function _parseDotRHS(rbp) { var lookahead = this._lookahead(0); var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; if (exprTokens.indexOf(lookahead) >= 0) { return this.expression(rbp); } else if (lookahead === TOK_LBRACKET) { this._match(TOK_LBRACKET); return this._parseMultiselectList(); } else if (lookahead === TOK_LBRACE) { this._match(TOK_LBRACE); return this._parseMultiselectHash(); } }, _parseProjectionRHS: function _parseProjectionRHS(rbp) { var right; if (bindingPower[this._lookahead(0)] < 10) { right = { type: "Identity" }; } else if (this._lookahead(0) === TOK_LBRACKET) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_FILTER) { right = this.expression(rbp); } else if (this._lookahead(0) === TOK_DOT) { this._match(TOK_DOT); right = this._parseDotRHS(rbp); } else { var t = this._lookaheadToken(0); var error = new Error("Sytanx error, unexpected token: " + t.value + "(" + t.type + ")"); error.name = "ParserError"; throw error; } return right; }, _parseMultiselectList: function _parseMultiselectList() { var expressions = []; while (this._lookahead(0) !== TOK_RBRACKET) { var expression = this.expression(0); expressions.push(expression); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); if (this._lookahead(0) === TOK_RBRACKET) { throw new Error("Unexpected token Rbracket"); } } } this._match(TOK_RBRACKET); return { type: "MultiSelectList", children: expressions }; }, _parseMultiselectHash: function _parseMultiselectHash() { var pairs = []; var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; var keyToken, keyName, value, node; for (; ;) { keyToken = this._lookaheadToken(0); if (identifierTypes.indexOf(keyToken.type) < 0) { throw new Error("Expecting an identifier token, got: " + keyToken.type); } keyName = keyToken.value; this._advance(); this._match(TOK_COLON); value = this.expression(0); node = { type: "KeyValuePair", name: keyName, value: value }; pairs.push(node); if (this._lookahead(0) === TOK_COMMA) { this._match(TOK_COMMA); } else if (this._lookahead(0) === TOK_RBRACE) { this._match(TOK_RBRACE); break; } } return { type: "MultiSelectHash", children: pairs }; } - }; function TreeInterpreter(runtime) { this.runtime = runtime; } TreeInterpreter.prototype = { - search: function search(node, value) { return this.visit(node, value); }, visit: function visit(node, value) { - var matched, current, result, first, second, field, left, right, collected, i; switch (node.type) { - case "Field": if (value === null) { return null; } else if (isObject(value)) { field = value[node.name]; if (field === undefined) { return null; } else { return field; } } else { return null; } break; case "Subexpression": result = this.visit(node.children[0], value); for (i = 1; i < node.children.length; i++) { result = this.visit(node.children[1], result); if (result === null) { return null; } } return result; case "IndexExpression": left = this.visit(node.children[0], value); right = this.visit(node.children[1], left); return right; case "Index": if (!isArray(value)) { return null; } var index = node.value; if (index < 0) { index = value.length + index; } result = value[index]; if (result === undefined) { result = null; } return result; case "Slice": if (!isArray(value)) { return null; } var sliceParams = node.children.slice(0); var computed = this.computeSliceParams(value.length, sliceParams); var start = computed[0]; var stop = computed[1]; var step = computed[2]; result = []; if (step > 0) { for (i = start; i < stop; i += step) { result.push(value[i]); } } else { for (i = start; i > stop; i += step) { result.push(value[i]); } } return result; case "Projection":// Evaluate left child. - var base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } collected = []; for (i = 0; i < base.length; i++) { current = this.visit(node.children[1], base[i]); if (current !== null) { collected.push(current); } } return collected; case "ValueProjection":// Evaluate left child. - base = this.visit(node.children[0], value); if (!isObject(base)) { return null; } collected = []; var values = objValues(base); for (i = 0; i < values.length; i++) { current = this.visit(node.children[1], values[i]); if (current !== null) { collected.push(current); } } return collected; case "FilterProjection": base = this.visit(node.children[0], value); if (!isArray(base)) { return null; } var filtered = []; var finalResults = []; for (i = 0; i < base.length; i++) { matched = this.visit(node.children[2], base[i]); if (!isFalse(matched)) { filtered.push(base[i]); } } for (var j = 0; j < filtered.length; j++) { current = this.visit(node.children[1], filtered[j]); if (current !== null) { finalResults.push(current); } } return finalResults; case "Comparator": first = this.visit(node.children[0], value); second = this.visit(node.children[1], value); switch (node.name) { case TOK_EQ: result = strictDeepEqual(first, second); break; case TOK_NE: result = !strictDeepEqual(first, second); break; case TOK_GT: result = first > second; break; case TOK_GTE: result = first >= second; break; case TOK_LT: result = first < second; break; case TOK_LTE: result = first <= second; break; default: throw new Error("Unknown comparator: " + node.name); }return result; case TOK_FLATTEN: var original = this.visit(node.children[0], value); if (!isArray(original)) { return null; } var merged = []; for (i = 0; i < original.length; i++) { current = original[i]; if (isArray(current)) { merged.push.apply(merged, current); } else { merged.push(current); } } return merged; case "Identity": return value; case "MultiSelectList": if (value === null) { return null; } collected = []; for (i = 0; i < node.children.length; i++) { collected.push(this.visit(node.children[i], value)); } return collected; case "MultiSelectHash": if (value === null) { return null; } collected = {}; var child; for (i = 0; i < node.children.length; i++) { child = node.children[i]; collected[child.name] = this.visit(child.value, value); } return collected; case "OrExpression": matched = this.visit(node.children[0], value); if (isFalse(matched)) { matched = this.visit(node.children[1], value); } return matched; case "AndExpression": first = this.visit(node.children[0], value); if (isFalse(first) === true) { return first; } return this.visit(node.children[1], value); case "NotExpression": first = this.visit(node.children[0], value); return isFalse(first); case "Literal": return node.value; case TOK_PIPE: left = this.visit(node.children[0], value); return this.visit(node.children[1], left); case TOK_CURRENT: return value; case "Function": var resolvedArgs = []; for (i = 0; i < node.children.length; i++) { resolvedArgs.push(this.visit(node.children[i], value)); } return this.runtime.callFunction(node.name, resolvedArgs); case "ExpressionReference": var refNode = node.children[0];// Tag the node with a specific attribute so the type - // checker verify the type. - refNode.jmespathType = TOK_EXPREF; return refNode; default: throw new Error("Unknown node type: " + node.type); - } - }, computeSliceParams: function computeSliceParams(arrayLength, sliceParams) { var start = sliceParams[0]; var stop = sliceParams[1]; var step = sliceParams[2]; var computed = [null, null, null]; if (step === null) { step = 1; } else if (step === 0) { var error = new Error("Invalid slice, step cannot be 0"); error.name = "RuntimeError"; throw error; } var stepValueNegative = step < 0 ? true : false; if (start === null) { start = stepValueNegative ? arrayLength - 1 : 0; } else { start = this.capSliceRange(arrayLength, start, step); } if (stop === null) { stop = stepValueNegative ? -1 : arrayLength; } else { stop = this.capSliceRange(arrayLength, stop, step); } computed[0] = start; computed[1] = stop; computed[2] = step; return computed; }, capSliceRange: function capSliceRange(arrayLength, actualValue, step) { if (actualValue < 0) { actualValue += arrayLength; if (actualValue < 0) { actualValue = step < 0 ? -1 : 0; } } else if (actualValue >= arrayLength) { actualValue = step < 0 ? arrayLength - 1 : arrayLength; } return actualValue; } - }; function Runtime(interpreter) { - this._interpreter = interpreter; this.functionTable = {// name: [function, ] - // The can be: - // - // { - // args: [[type1, type2], [type1, type2]], - // variadic: true|false - // } - // - // Each arg in the arg list is a list of valid types - // (if the function is overloaded and supports multiple - // types. If the type is "any" then no type checking - // occurs on the argument. Variadic is optional - // and if not provided is assumed to be false. - abs: { _func: this._functionAbs, _signature: [{ types: [TYPE_NUMBER] }] }, avg: { _func: this._functionAvg, _signature: [{ types: [TYPE_ARRAY_NUMBER] }] }, ceil: { _func: this._functionCeil, _signature: [{ types: [TYPE_NUMBER] }] }, contains: { _func: this._functionContains, _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] }, { types: [TYPE_ANY] }] }, "ends_with": { _func: this._functionEndsWith, _signature: [{ types: [TYPE_STRING] }, { types: [TYPE_STRING] }] }, floor: { _func: this._functionFloor, _signature: [{ types: [TYPE_NUMBER] }] }, length: { _func: this._functionLength, _signature: [{ types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT] }] }, map: { _func: this._functionMap, _signature: [{ types: [TYPE_EXPREF] }, { types: [TYPE_ARRAY] }] }, max: { _func: this._functionMax, _signature: [{ types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING] }] }, "merge": { _func: this._functionMerge, _signature: [{ types: [TYPE_OBJECT], variadic: true }] }, "max_by": { _func: this._functionMaxBy, _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }] }, sum: { _func: this._functionSum, _signature: [{ types: [TYPE_ARRAY_NUMBER] }] }, "starts_with": { _func: this._functionStartsWith, _signature: [{ types: [TYPE_STRING] }, { types: [TYPE_STRING] }] }, min: { _func: this._functionMin, _signature: [{ types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING] }] }, "min_by": { _func: this._functionMinBy, _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }] }, type: { _func: this._functionType, _signature: [{ types: [TYPE_ANY] }] }, keys: { _func: this._functionKeys, _signature: [{ types: [TYPE_OBJECT] }] }, values: { _func: this._functionValues, _signature: [{ types: [TYPE_OBJECT] }] }, sort: { _func: this._functionSort, _signature: [{ types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER] }] }, "sort_by": { _func: this._functionSortBy, _signature: [{ types: [TYPE_ARRAY] }, { types: [TYPE_EXPREF] }] }, join: { _func: this._functionJoin, _signature: [{ types: [TYPE_STRING] }, { types: [TYPE_ARRAY_STRING] }] }, reverse: { _func: this._functionReverse, _signature: [{ types: [TYPE_STRING, TYPE_ARRAY] }] }, "to_array": { _func: this._functionToArray, _signature: [{ types: [TYPE_ANY] }] }, "to_string": { _func: this._functionToString, _signature: [{ types: [TYPE_ANY] }] }, "to_number": { _func: this._functionToNumber, _signature: [{ types: [TYPE_ANY] }] }, "not_null": { _func: this._functionNotNull, _signature: [{ types: [TYPE_ANY], variadic: true }] } - }; - } Runtime.prototype = { - callFunction: function callFunction(name, resolvedArgs) { var functionEntry = this.functionTable[name]; if (functionEntry === undefined) { throw new Error("Unknown function: " + name + "()"); } this._validateArgs(name, resolvedArgs, functionEntry._signature); return functionEntry._func.call(this, resolvedArgs); }, _validateArgs: function _validateArgs(name, args, signature) {// Validating the args requires validating - // the correct arity and the correct type of each arg. - // If the last argument is declared as variadic, then we need - // a minimum number of args to be required. Otherwise it has to - // be an exact amount. - var pluralized; if (signature[signature.length - 1].variadic) { if (args.length < signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes at least" + signature.length + pluralized + " but received " + args.length); } } else if (args.length !== signature.length) { pluralized = signature.length === 1 ? " argument" : " arguments"; throw new Error("ArgumentError: " + name + "() " + "takes " + signature.length + pluralized + " but received " + args.length); } var currentSpec; var actualType; var typeMatched; for (var i = 0; i < signature.length; i++) { typeMatched = false; currentSpec = signature[i].types; actualType = this._getTypeName(args[i]); for (var j = 0; j < currentSpec.length; j++) { if (this._typeMatches(actualType, currentSpec[j], args[i])) { typeMatched = true; break; } } if (!typeMatched) { throw new Error("TypeError: " + name + "() " + "expected argument " + (i + 1) + " to be type " + currentSpec + " but received type " + actualType + " instead."); } } - }, _typeMatches: function _typeMatches(actual, expected, argValue) { - if (expected === TYPE_ANY) { return true; } if (expected === TYPE_ARRAY_STRING || expected === TYPE_ARRAY_NUMBER || expected === TYPE_ARRAY) {// The expected type can either just be array, - // or it can require a specific subtype (array of numbers). - // - // The simplest case is if "array" with no subtype is specified. - if (expected === TYPE_ARRAY) { return actual === TYPE_ARRAY; } else if (actual === TYPE_ARRAY) {// Otherwise we need to check subtypes. - // I think this has potential to be improved. - var subtype; if (expected === TYPE_ARRAY_NUMBER) { subtype = TYPE_NUMBER; } else if (expected === TYPE_ARRAY_STRING) { subtype = TYPE_STRING; } for (var i = 0; i < argValue.length; i++) { if (!this._typeMatches(this._getTypeName(argValue[i]), subtype, argValue[i])) { return false; } } return true; - } - } else { return actual === expected; } - }, _getTypeName: function _getTypeName(obj) { - switch (Object.prototype.toString.call(obj)) { - case "[object String]": return TYPE_STRING; case "[object Number]": return TYPE_NUMBER; case "[object Array]": return TYPE_ARRAY; case "[object Boolean]": return TYPE_BOOLEAN; case "[object Null]": return TYPE_NULL; case "[object Object]":// Check if it's an expref. If it has, it's been - // tagged with a jmespathType attr of 'Expref'; - if (obj.jmespathType === TOK_EXPREF) { return TYPE_EXPREF; } else { return TYPE_OBJECT; } - } - }, _functionStartsWith: function _functionStartsWith(resolvedArgs) { return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; }, _functionEndsWith: function _functionEndsWith(resolvedArgs) { var searchStr = resolvedArgs[0]; var suffix = resolvedArgs[1]; return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; }, _functionReverse: function _functionReverse(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); if (typeName === TYPE_STRING) { var originalStr = resolvedArgs[0]; var reversedStr = ""; for (var i = originalStr.length - 1; i >= 0; i--) { reversedStr += originalStr[i]; } return reversedStr; } else { var reversedArray = resolvedArgs[0].slice(0); reversedArray.reverse(); return reversedArray; } }, _functionAbs: function _functionAbs(resolvedArgs) { return Math.abs(resolvedArgs[0]); }, _functionCeil: function _functionCeil(resolvedArgs) { return Math.ceil(resolvedArgs[0]); }, _functionAvg: function _functionAvg(resolvedArgs) { var sum = 0; var inputArray = resolvedArgs[0]; for (var i = 0; i < inputArray.length; i++) { sum += inputArray[i]; } return sum / inputArray.length; }, _functionContains: function _functionContains(resolvedArgs) { return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; }, _functionFloor: function _functionFloor(resolvedArgs) { return Math.floor(resolvedArgs[0]); }, _functionLength: function _functionLength(resolvedArgs) { - if (!isObject(resolvedArgs[0])) { return resolvedArgs[0].length; } else {// As far as I can tell, there's no way to get the length - // of an object without O(n) iteration through the object. - return Object.keys(resolvedArgs[0]).length; - } - }, _functionMap: function _functionMap(resolvedArgs) { var mapped = []; var interpreter = this._interpreter; var exprefNode = resolvedArgs[0]; var elements = resolvedArgs[1]; for (var i = 0; i < elements.length; i++) { mapped.push(interpreter.visit(exprefNode, elements[i])); } return mapped; }, _functionMerge: function _functionMerge(resolvedArgs) { var merged = {}; for (var i = 0; i < resolvedArgs.length; i++) { var current = resolvedArgs[i]; for (var key in current) { merged[key] = current[key]; } } return merged; }, _functionMax: function _functionMax(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.max.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var maxElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (maxElement.localeCompare(elements[i]) < 0) { maxElement = elements[i]; } } return maxElement; } } else { return null; } }, _functionMin: function _functionMin(resolvedArgs) { if (resolvedArgs[0].length > 0) { var typeName = this._getTypeName(resolvedArgs[0][0]); if (typeName === TYPE_NUMBER) { return Math.min.apply(Math, resolvedArgs[0]); } else { var elements = resolvedArgs[0]; var minElement = elements[0]; for (var i = 1; i < elements.length; i++) { if (elements[i].localeCompare(minElement) < 0) { minElement = elements[i]; } } return minElement; } } else { return null; } }, _functionSum: function _functionSum(resolvedArgs) { var sum = 0; var listToSum = resolvedArgs[0]; for (var i = 0; i < listToSum.length; i++) { sum += listToSum[i]; } return sum; }, _functionType: function _functionType(resolvedArgs) { switch (this._getTypeName(resolvedArgs[0])) { case TYPE_NUMBER: return "number"; case TYPE_STRING: return "string"; case TYPE_ARRAY: return "array"; case TYPE_OBJECT: return "object"; case TYPE_BOOLEAN: return "boolean"; case TYPE_EXPREF: return "expref"; case TYPE_NULL: return "null"; } }, _functionKeys: function _functionKeys(resolvedArgs) { return Object.keys(resolvedArgs[0]); }, _functionValues: function _functionValues(resolvedArgs) { var obj = resolvedArgs[0]; var keys = Object.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { values.push(obj[keys[i]]); } return values; }, _functionJoin: function _functionJoin(resolvedArgs) { var joinChar = resolvedArgs[0]; var listJoin = resolvedArgs[1]; return listJoin.join(joinChar); }, _functionToArray: function _functionToArray(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { return resolvedArgs[0]; } else { return [resolvedArgs[0]]; } }, _functionToString: function _functionToString(resolvedArgs) { if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { return resolvedArgs[0]; } else { return JSON.stringify(resolvedArgs[0]); } }, _functionToNumber: function _functionToNumber(resolvedArgs) { var typeName = this._getTypeName(resolvedArgs[0]); var convertedValue; if (typeName === TYPE_NUMBER) { return resolvedArgs[0]; } else if (typeName === TYPE_STRING) { convertedValue = +resolvedArgs[0]; if (!isNaN(convertedValue)) { return convertedValue; } } return null; }, _functionNotNull: function _functionNotNull(resolvedArgs) { for (var i = 0; i < resolvedArgs.length; i++) { if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { return resolvedArgs[i]; } } return null; }, _functionSort: function _functionSort(resolvedArgs) { var sortedArray = resolvedArgs[0].slice(0); sortedArray.sort(); return sortedArray; }, _functionSortBy: function _functionSortBy(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); if (sortedArray.length === 0) { return sortedArray; } var interpreter = this._interpreter; var exprefNode = resolvedArgs[1]; var requiredType = this._getTypeName(interpreter.visit(exprefNode, sortedArray[0])); if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { throw new Error("TypeError"); } var that = this;// In order to get a stable sort out of an unstable - // sort algorithm, we decorate/sort/undecorate (DSU) - // by creating a new list of [index, element] pairs. - // In the cmp function, if the evaluated elements are - // equal, then the index will be used as the tiebreaker. - // After the decorated list has been sorted, it will be - // undecorated to extract the original elements. - var decorated = []; for (var i = 0; i < sortedArray.length; i++) { decorated.push([i, sortedArray[i]]); } decorated.sort(function (a, b) { - var exprA = interpreter.visit(exprefNode, a[1]); var exprB = interpreter.visit(exprefNode, b[1]); if (that._getTypeName(exprA) !== requiredType) { throw new Error("TypeError: expected " + requiredType + ", received " + that._getTypeName(exprA)); } else if (that._getTypeName(exprB) !== requiredType) { throw new Error("TypeError: expected " + requiredType + ", received " + that._getTypeName(exprB)); } if (exprA > exprB) { return 1; } else if (exprA < exprB) { return -1; } else {// If they're equal compare the items by their - // order to maintain relative order of equal keys - // (i.e. to get a stable sort). - return a[0] - b[0]; - } - });// Undecorate: extract out the original list elements. - for (var j = 0; j < decorated.length; j++) { sortedArray[j] = decorated[j][1]; } return sortedArray; - }, _functionMaxBy: function _functionMaxBy(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var maxNumber = -Infinity; var maxRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current > maxNumber) { maxNumber = current; maxRecord = resolvedArray[i]; } } return maxRecord; }, _functionMinBy: function _functionMinBy(resolvedArgs) { var exprefNode = resolvedArgs[1]; var resolvedArray = resolvedArgs[0]; var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); var minNumber = Infinity; var minRecord; var current; for (var i = 0; i < resolvedArray.length; i++) { current = keyFunction(resolvedArray[i]); if (current < minNumber) { minNumber = current; minRecord = resolvedArray[i]; } } return minRecord; }, createKeyFunction: function createKeyFunction(exprefNode, allowedTypes) { var that = this; var interpreter = this._interpreter; var keyFunc = function keyFunc(x) { var current = interpreter.visit(exprefNode, x); if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { var msg = "TypeError: expected one of " + allowedTypes + ", received " + that._getTypeName(current); throw new Error(msg); } return current; }; return keyFunc; } - }; function compile(stream) { var parser = new Parser(); var ast = parser.parse(stream); return ast; } function tokenize(stream) { var lexer = new Lexer(); return lexer.tokenize(stream); } function search(data, expression) { - var parser = new Parser();// This needs to be improved. Both the interpreter and runtime depend on - // each other. The runtime needs the interpreter to support exprefs. - // There's likely a clean way to avoid the cyclic dependency. - var runtime = new Runtime(); var interpreter = new TreeInterpreter(runtime); runtime._interpreter = interpreter; var node = parser.parse(expression); return interpreter.search(node, data); - } exports.tokenize = tokenize; exports.compile = compile; exports.search = search; exports.strictDeepEqual = strictDeepEqual; - })(typeof exports === "undefined" ? this.jmespath = {} : exports); - }, {}], 86: [function (require, module, exports) {// shim for using process in browser - var process = module.exports = {};// cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) {//normal enviroments in sane situations - return setTimeout(fun, 0); - }// if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try {// when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try {// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) {// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - } function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) {//normal enviroments in sane situations - return clearTimeout(marker); - }// if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try {// when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try {// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) {// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } };// v8 likes predictible objects - function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = '';// empty string to avoid regexp issues - process.versions = {}; function noop() { } process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return []; }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; - }, {}], 87: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - 'use strict';// If obj.hasOwnProperty has been overridden, then calling - // obj.hasOwnProperty(prop) will break. - // See: https://github.com/joyent/node/issues/1707 - function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function (qs, sep, eq, options) { - sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length;// maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; - }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; - }, {}], 88: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - 'use strict'; var stringifyPrimitive = function stringifyPrimitive(v) { switch (_typeof(v)) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function (obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (_typeof(obj) === 'object') { return map(objectKeys(obj), function (k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function (v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map(xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; - }, {}], 89: [function (require, module, exports) { 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); }, { "./decode": 87, "./encode": 88 }], 90: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - 'use strict';// If obj.hasOwnProperty has been overridden, then calling - // obj.hasOwnProperty(prop) will break. - // See: https://github.com/joyent/node/issues/1707 - function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function (qs, sep, eq, options) { - sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length;// maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (Array.isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; - }; - }, {}], 91: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - 'use strict'; var stringifyPrimitive = function stringifyPrimitive(v) { switch (_typeof(v)) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function (obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (_typeof(obj) === 'object') { return Object.keys(obj).map(function (k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (Array.isArray(obj[k])) { return obj[k].map(function (v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; - }, {}], 92: [function (require, module, exports) { arguments[4][89][0].apply(exports, arguments); }, { "./decode": 90, "./encode": 91, "dup": 89 }], 93: [function (require, module, exports) { - (function (setImmediate, clearImmediate) { - (function () { - var nextTick = require('process/browser.js').nextTick; var apply = Function.prototype.apply; var slice = Array.prototype.slice; var immediateIds = {}; var nextImmediateId = 0;// DOM APIs, for completeness - exports.setTimeout = function () { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }; exports.setInterval = function () { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }; exports.clearTimeout = exports.clearInterval = function (timeout) { timeout.close(); }; function Timeout(id, clearFn) { this._id = id; this._clearFn = clearFn; } Timeout.prototype.unref = Timeout.prototype.ref = function () { }; Timeout.prototype.close = function () { this._clearFn.call(window, this._id); };// Does not start the time, just sets up the members needed. - exports.enroll = function (item, msecs) { clearTimeout(item._idleTimeoutId); item._idleTimeout = msecs; }; exports.unenroll = function (item) { clearTimeout(item._idleTimeoutId); item._idleTimeout = -1; }; exports._unrefActive = exports.active = function (item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; if (msecs >= 0) { item._idleTimeoutId = setTimeout(function onTimeout() { if (item._onTimeout) item._onTimeout(); }, msecs); } };// That's not how node.js implements it but the exposed api is the same. - exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function (fn) { - var id = nextImmediateId++; var args = arguments.length < 2 ? false : slice.call(arguments, 1); immediateIds[id] = true; nextTick(function onNextTick() { - if (immediateIds[id]) {// fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { fn.apply(null, args); } else { fn.call(null); }// Prevent ids from leaking - exports.clearImmediate(id); - } - }); return id; - }; exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function (id) { delete immediateIds[id]; }; - }).call(this); - }).call(this, require("timers").setImmediate, require("timers").clearImmediate); - }, { "process/browser.js": 86, "timers": 93 }], 94: [function (require, module, exports) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - var punycode = require('punycode'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; }// Reference: RFC 3986, RFC 1808, RFC 2396 - // define these here so at least they only have to be - // compiled once on the first module load. - var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/,// RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],// RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise),// Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { 'javascript': true, 'javascript:': true },// protocols that never have a hostname. - hostlessProtocol = { 'javascript': true, 'javascript:': true },// protocols that always contain a // bit. - slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && isObject(url) && url instanceof Url) return url; var u = new Url(); u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { - if (!isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + _typeof(url)); } var rest = url;// trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); }// figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {// there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - // find the first instance of any hostEndingChars - var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; }// at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; if (hostEnd === -1) {// atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else {// atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - }// Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); }// the host is the remaining to the left of the first non-host char - hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; }// if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd);// pull out port. - this.parseHost();// we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || '';// if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']';// validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { - var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) {// we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { newpart += part[j]; } - }// we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } - } - } - } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else {// hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } if (!ipv6Hostname) {// IDNA Support: Returns a puny coded representation of "domain". - // It only converts the part of the domain name that - // has non ASCII characters. I.e. it dosent matter if - // you call it with a domain that already is in ASCII. - var domainArray = this.hostname.split('.'); var newOut = []; for (var i = 0; i < domainArray.length; ++i) { var s = domainArray[i]; newOut.push(s.match(/[^A-Za-z0-9_-]/) ? 'xn--' + punycode.encode(s) : s); } this.hostname = newOut.join('.'); - } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host;// strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } - }// now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) {// First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } - }// chop off from the tail first. - var hash = rest.indexOf('#'); if (hash !== -1) {// got a fragment string. - this.hash = rest.substr(hash); rest = rest.slice(0, hash); - } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) {// no query string, but parseQueryString still requested - this.search = ''; this.query = {}; - } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; }//to support http.request - if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; }// finally, reconstruct the href based on what has been validated. - this.href = this.format(); return this; - };// format a parsed object into a url string - function urlFormat(obj) {// ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); - } Url.prototype.format = function () { - var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || query && '?' + query || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':';// only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function (match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; - }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function (relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function (relative) { - if (isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); Object.keys(this).forEach(function (k) { result[k] = this[k]; }, this);// hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash;// if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { result.href = result.format(); return result; }// hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) {// take everything except the protocol from relative - Object.keys(relative).forEach(function (k) { if (k !== 'protocol') result[k] = relative[k]; });//urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; - } if (relative.protocol && relative.protocol !== result.protocol) {// if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { Object.keys(relative).forEach(function (k) { result[k] = relative[k]; }); result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port;// to support http.request - if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; - } var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', mustEndAbs = isRelAbs || isSourceAbs || result.host && relative.pathname, removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol];// if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) {// it's absolute. - result.host = relative.host || relative.host === '' ? relative.host : result.host; result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath;// fall through to the dot-handling below. - } else if (relPath.length) {// it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; - } else if (!isNullOrUndefined(relative.search)) {// just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift();//occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } - } result.search = relative.search; result.query = relative.query;//to support http.request - if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; - } if (!srcPath.length) {// no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null;//to support http.request - if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; - }// if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; var hasTrailingSlash = (result.host || relative.host) && (last === '.' || last === '..') || last === '';// strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last == '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } }// if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && srcPath.join('/').substr(-1) !== '/') { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || srcPath[0] && srcPath[0].charAt(0) === '/';// put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : '';//occationaly the auth can get stuck only in host - //this especialy happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } - } mustEndAbs = mustEndAbs || result.host && srcPath.length; if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); }//to support request.http - if (!isNull(result.pathname) || !isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; - }; Url.prototype.parseHost = function () { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; function isString(arg) { return typeof arg === "string"; } function isObject(arg) { return _typeof(arg) === 'object' && arg !== null; } function isNull(arg) { return arg === null; } function isNullOrUndefined(arg) { return arg == null; } - }, { "punycode": 80, "querystring": 89 }], 95: [function (require, module, exports) { - if (typeof Object.create === 'function') {// implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; - } else {// old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function TempCtor() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; - } - }, {}], 96: [function (require, module, exports) { module.exports = function isBuffer(arg) { return arg && _typeof(arg) === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; }, {}], 97: [function (require, module, exports) { - (function (process, global) { - (function () {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - var formatRegExp = /%[sdj%]/g; exports.format = function (f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function (x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; };// Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function (fn, msg) {// Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { return function () { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; - }; var debugs = {}; var debugEnviron; exports.debuglog = function (set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function () { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function () { }; } } return debugs[set]; };/** + */function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError('offset is not uint');if(offset+ext>length)throw new RangeError('Trying to access beyond buffer length');}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul;}return val;};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset];};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8;};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1];};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*0x1000000;};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*0x1000000+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3]);};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset|0;byteLength=byteLength|0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readInt8=function readInt8(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&0x80))return this[offset];return(0xff-this[offset]+1)*-1;};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24;};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3];};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4);};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4);};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8);};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8);};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError('Index out of range');}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;byteLength=byteLength|0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0);}var mul=1;var i=0;this[offset]=value&0xFF;while(++i=0&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0xff,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value&0xff;return offset+1;};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=0xffff+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i>>(littleEndian?i:1-i)*8;}}Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=0xffffffff+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i>>(littleEndian?i:3-i)*8&0xff;}}Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&0xff;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=0;var mul=1;var sub=0;this[offset]=value&0xFF;while(++i>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset|0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1;}this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=0xff+value+1;this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;}else{objectWriteUInt16(this,value,offset,true);}return offset+2;};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value&0xff;}else{objectWriteUInt16(this,value,offset,false);}return offset+2;};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value&0xff;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;}else{objectWriteUInt32(this,value,offset,true);}return offset+4;};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset|0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(value<0)value=0xffffffff+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;}else{objectWriteUInt32(this,value,offset,false);}return offset+4;};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError('Index out of range');if(offset<0)throw new RangeError('Index out of range');}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38);}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4;}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert);};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert);};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308);}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8;}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert);};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert);};// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError('sourceStart out of bounds');if(end<0)throw new RangeError('sourceEnd out of bounds');// Are we oob? +if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start];}}else if(len<1000||!Buffer.TYPED_ARRAY_SUPPORT){// ascending copy from start +for(i=0;i>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==='number'){for(i=start;i0xD7FF&&codePoint<0xE000){// last char was a lead +if(!leadSurrogate){// no lead yet +if(codePoint>0xDBFF){// unexpected trail +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}else if(i+1===length){// unpaired lead +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}// valid lead +leadSurrogate=codePoint;continue;}// 2 leads in a row +if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);leadSurrogate=codePoint;continue;}// valid surrogate pair +codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000;}else if(leadSurrogate){// valid bmp char, but last char was a lead +if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);}leadSurrogate=null;// encode utf8 +if(codePoint<0x80){if((units-=1)<0)break;bytes.push(codePoint);}else if(codePoint<0x800){if((units-=2)<0)break;bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80);}else if(codePoint<0x10000){if((units-=3)<0)break;bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else if(codePoint<0x110000){if((units-=4)<0)break;bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else{throw new Error('Invalid code point');}}return bytes;}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi);}return byteArray;}function base64ToBytes(str){return base64.toByteArray(base64clean(str));}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i];}return i;}function isnan(val){return val!==val;// eslint-disable-line no-self-compare +}}).call(this);}).call(this,typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{},require("buffer").Buffer);},{"base64-js":78,"buffer":81,"ieee754":83,"isarray":84}],82:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined;}module.exports=EventEmitter;// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners=10;// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError('n must be a positive number');this._maxListeners=n;return this;};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};// If there is no 'error' event listener then throw. +if(type==='error'){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er;// Unhandled 'error' event +}else{// At least give some kind of context to the user +var err=new Error('Uncaught, unspecified "error" event. ('+er+')');err.context=er;throw err;}}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){// fast cases +case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;// slower +default:args=Array.prototype.slice.call(arguments,1);handler.apply(this,args);}}else if(isObject(handler)){args=Array.prototype.slice.call(arguments,1);listeners=handler.slice();len=listeners.length;for(i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error('(node) warning: possible EventEmitter memory '+'leak detected. %d listeners added. '+'Use emitter.setMaxListeners() to increase limit.',this._events[type].length);if(typeof console.trace==='function'){// not supported in IE 10 +console.trace();}}}return this;};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError('listener must be a function');var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments);}}g.listener=listener;this.on(type,g);return this;};// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError('listener must be a function');if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit('removeListener',type,listener);}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break;}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type];}else{list.splice(position,1);}if(this._events.removeListener)this.emit('removeListener',type,listener);}return this;};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;// not listening for removeListener, no need to emit +if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this;}// emit removeListener for all listeners on all events +if(arguments.length===0){for(key in this._events){if(key==='removeListener')continue;this.removeAllListeners(key);}this.removeAllListeners('removeListener');this._events={};return this;}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners);}else if(listeners){// LIFO order +while(listeners.length)this.removeListener(type,listeners[listeners.length-1]);}delete this._events[type];return this;};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret;};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length;}return 0;};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type);};function isFunction(arg){return typeof arg==='function';}function isNumber(arg){return typeof arg==='number';}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isUndefined(arg){return arg===void 0;}},{}],83:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias;}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity;}else{m=m+Math.pow(2,mLen);e=e-eBias;}return(s?-1:1)*m*Math.pow(2,e-mLen);};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax;}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2;}if(e+eBias>=1){value+=rt/c;}else{value+=rt*Math.pow(2,1-eBias);}if(value*c>=2){e++;c/=2;}if(e+eBias>=eMax){m=0;e=eMax;}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias;}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0;}}for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128;};},{}],84:[function(require,module,exports){var toString={}.toString;module.exports=Array.isArray||function(arr){return toString.call(arr)=='[object Array]';};},{}],85:[function(require,module,exports){(function(exports){"use strict";function isArray(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Array]";}else{return false;}}function isObject(obj){if(obj!==null){return Object.prototype.toString.call(obj)==="[object Object]";}else{return false;}}function strictDeepEqual(first,second){// Check the scalar case first. +if(first===second){return true;}// Check if they are the same type. +var firstType=Object.prototype.toString.call(first);if(firstType!==Object.prototype.toString.call(second)){return false;}// We know that first and second have the same type so we can just check the +// first type from now on. +if(isArray(first)===true){// Short circuit if they're not the same length; +if(first.length!==second.length){return false;}for(var i=0;i" tokens +// are not in basicToken because +// there are two token variants +// ("&&", "[?", "<=", ">="). This is specially handled +// below. +var basicTokens={".":TOK_DOT,"*":TOK_STAR,",":TOK_COMMA,":":TOK_COLON,"{":TOK_LBRACE,"}":TOK_RBRACE,"]":TOK_RBRACKET,"(":TOK_LPAREN,")":TOK_RPAREN,"@":TOK_CURRENT};var operatorStartToken={"<":true,">":true,"=":true,"!":true};var skipChars={" ":true,"\t":true,"\n":true};function isAlpha(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_";}function isNum(ch){return ch>="0"&&ch<="9"||ch==="-";}function isAlphaNum(ch){return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="_";}function Lexer(){}Lexer.prototype={tokenize:function tokenize(stream){var tokens=[];this._current=0;var start;var identifier;var token;while(this._current"){if(stream[this._current]==="="){this._current++;return{type:TOK_GTE,value:">=",start:start};}else{return{type:TOK_GT,value:">",start:start};}}else if(startingChar==="="){if(stream[this._current]==="="){this._current++;return{type:TOK_EQ,value:"==",start:start};}}},_consumeLiteral:function _consumeLiteral(stream){this._current++;var start=this._current;var maxLength=stream.length;var literal;while(stream[this._current]!=="`"&&this._current" +literal=JSON.parse("\""+literalString+"\"");}// +1 gets us to the ending "`", +1 to move on to the next char. +this._current++;return literal;},_looksLikeJSON:function _looksLikeJSON(literalString){var startingChars="[{\"";var jsonLiterals=["true","false","null"];var numberLooking="-0123456789";if(literalString===""){return false;}else if(startingChars.indexOf(literalString[0])>=0){return true;}else if(jsonLiterals.indexOf(literalString)>=0){return true;}else if(numberLooking.indexOf(literalString[0])>=0){try{JSON.parse(literalString);return true;}catch(ex){return false;}}else{return false;}}};var bindingPower={};bindingPower[TOK_EOF]=0;bindingPower[TOK_UNQUOTEDIDENTIFIER]=0;bindingPower[TOK_QUOTEDIDENTIFIER]=0;bindingPower[TOK_RBRACKET]=0;bindingPower[TOK_RPAREN]=0;bindingPower[TOK_COMMA]=0;bindingPower[TOK_RBRACE]=0;bindingPower[TOK_NUMBER]=0;bindingPower[TOK_CURRENT]=0;bindingPower[TOK_EXPREF]=0;bindingPower[TOK_PIPE]=1;bindingPower[TOK_OR]=2;bindingPower[TOK_AND]=3;bindingPower[TOK_EQ]=5;bindingPower[TOK_GT]=5;bindingPower[TOK_LT]=5;bindingPower[TOK_GTE]=5;bindingPower[TOK_LTE]=5;bindingPower[TOK_NE]=5;bindingPower[TOK_FLATTEN]=9;bindingPower[TOK_STAR]=20;bindingPower[TOK_FILTER]=21;bindingPower[TOK_DOT]=40;bindingPower[TOK_NOT]=45;bindingPower[TOK_LBRACE]=50;bindingPower[TOK_LBRACKET]=55;bindingPower[TOK_LPAREN]=60;function Parser(){}Parser.prototype={parse:function parse(expression){this._loadTokens(expression);this.index=0;var ast=this.expression(0);if(this._lookahead(0)!==TOK_EOF){var t=this._lookaheadToken(0);var error=new Error("Unexpected token type: "+t.type+", value: "+t.value);error.name="ParserError";throw error;}return ast;},_loadTokens:function _loadTokens(expression){var lexer=new Lexer();var tokens=lexer.tokenize(expression);tokens.push({type:TOK_EOF,value:"",start:expression.length});this.tokens=tokens;},expression:function expression(rbp){var leftToken=this._lookaheadToken(0);this._advance();var left=this.nud(leftToken);var currentToken=this._lookahead(0);while(rbp=0){return this.expression(rbp);}else if(lookahead===TOK_LBRACKET){this._match(TOK_LBRACKET);return this._parseMultiselectList();}else if(lookahead===TOK_LBRACE){this._match(TOK_LBRACE);return this._parseMultiselectHash();}},_parseProjectionRHS:function _parseProjectionRHS(rbp){var right;if(bindingPower[this._lookahead(0)]<10){right={type:"Identity"};}else if(this._lookahead(0)===TOK_LBRACKET){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_FILTER){right=this.expression(rbp);}else if(this._lookahead(0)===TOK_DOT){this._match(TOK_DOT);right=this._parseDotRHS(rbp);}else{var t=this._lookaheadToken(0);var error=new Error("Sytanx error, unexpected token: "+t.value+"("+t.type+")");error.name="ParserError";throw error;}return right;},_parseMultiselectList:function _parseMultiselectList(){var expressions=[];while(this._lookahead(0)!==TOK_RBRACKET){var expression=this.expression(0);expressions.push(expression);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);if(this._lookahead(0)===TOK_RBRACKET){throw new Error("Unexpected token Rbracket");}}}this._match(TOK_RBRACKET);return{type:"MultiSelectList",children:expressions};},_parseMultiselectHash:function _parseMultiselectHash(){var pairs=[];var identifierTypes=[TOK_UNQUOTEDIDENTIFIER,TOK_QUOTEDIDENTIFIER];var keyToken,keyName,value,node;for(;;){keyToken=this._lookaheadToken(0);if(identifierTypes.indexOf(keyToken.type)<0){throw new Error("Expecting an identifier token, got: "+keyToken.type);}keyName=keyToken.value;this._advance();this._match(TOK_COLON);value=this.expression(0);node={type:"KeyValuePair",name:keyName,value:value};pairs.push(node);if(this._lookahead(0)===TOK_COMMA){this._match(TOK_COMMA);}else if(this._lookahead(0)===TOK_RBRACE){this._match(TOK_RBRACE);break;}}return{type:"MultiSelectHash",children:pairs};}};function TreeInterpreter(runtime){this.runtime=runtime;}TreeInterpreter.prototype={search:function search(node,value){return this.visit(node,value);},visit:function visit(node,value){var matched,current,result,first,second,field,left,right,collected,i;switch(node.type){case"Field":if(value===null){return null;}else if(isObject(value)){field=value[node.name];if(field===undefined){return null;}else{return field;}}else{return null;}break;case"Subexpression":result=this.visit(node.children[0],value);for(i=1;i0){for(i=start;istop;i+=step){result.push(value[i]);}}return result;case"Projection":// Evaluate left child. +var base=this.visit(node.children[0],value);if(!isArray(base)){return null;}collected=[];for(i=0;isecond;break;case TOK_GTE:result=first>=second;break;case TOK_LT:result=first=arrayLength){actualValue=step<0?arrayLength-1:arrayLength;}return actualValue;}};function Runtime(interpreter){this._interpreter=interpreter;this.functionTable={// name: [function, ] +// The can be: +// +// { +// args: [[type1, type2], [type1, type2]], +// variadic: true|false +// } +// +// Each arg in the arg list is a list of valid types +// (if the function is overloaded and supports multiple +// types. If the type is "any" then no type checking +// occurs on the argument. Variadic is optional +// and if not provided is assumed to be false. +abs:{_func:this._functionAbs,_signature:[{types:[TYPE_NUMBER]}]},avg:{_func:this._functionAvg,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},ceil:{_func:this._functionCeil,_signature:[{types:[TYPE_NUMBER]}]},contains:{_func:this._functionContains,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]},{types:[TYPE_ANY]}]},"ends_with":{_func:this._functionEndsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},floor:{_func:this._functionFloor,_signature:[{types:[TYPE_NUMBER]}]},length:{_func:this._functionLength,_signature:[{types:[TYPE_STRING,TYPE_ARRAY,TYPE_OBJECT]}]},map:{_func:this._functionMap,_signature:[{types:[TYPE_EXPREF]},{types:[TYPE_ARRAY]}]},max:{_func:this._functionMax,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"merge":{_func:this._functionMerge,_signature:[{types:[TYPE_OBJECT],variadic:true}]},"max_by":{_func:this._functionMaxBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},sum:{_func:this._functionSum,_signature:[{types:[TYPE_ARRAY_NUMBER]}]},"starts_with":{_func:this._functionStartsWith,_signature:[{types:[TYPE_STRING]},{types:[TYPE_STRING]}]},min:{_func:this._functionMin,_signature:[{types:[TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING]}]},"min_by":{_func:this._functionMinBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},type:{_func:this._functionType,_signature:[{types:[TYPE_ANY]}]},keys:{_func:this._functionKeys,_signature:[{types:[TYPE_OBJECT]}]},values:{_func:this._functionValues,_signature:[{types:[TYPE_OBJECT]}]},sort:{_func:this._functionSort,_signature:[{types:[TYPE_ARRAY_STRING,TYPE_ARRAY_NUMBER]}]},"sort_by":{_func:this._functionSortBy,_signature:[{types:[TYPE_ARRAY]},{types:[TYPE_EXPREF]}]},join:{_func:this._functionJoin,_signature:[{types:[TYPE_STRING]},{types:[TYPE_ARRAY_STRING]}]},reverse:{_func:this._functionReverse,_signature:[{types:[TYPE_STRING,TYPE_ARRAY]}]},"to_array":{_func:this._functionToArray,_signature:[{types:[TYPE_ANY]}]},"to_string":{_func:this._functionToString,_signature:[{types:[TYPE_ANY]}]},"to_number":{_func:this._functionToNumber,_signature:[{types:[TYPE_ANY]}]},"not_null":{_func:this._functionNotNull,_signature:[{types:[TYPE_ANY],variadic:true}]}};}Runtime.prototype={callFunction:function callFunction(name,resolvedArgs){var functionEntry=this.functionTable[name];if(functionEntry===undefined){throw new Error("Unknown function: "+name+"()");}this._validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs);},_validateArgs:function _validateArgs(name,args,signature){// Validating the args requires validating +// the correct arity and the correct type of each arg. +// If the last argument is declared as variadic, then we need +// a minimum number of args to be required. Otherwise it has to +// be an exact amount. +var pluralized;if(signature[signature.length-1].variadic){if(args.length=0;i--){reversedStr+=originalStr[i];}return reversedStr;}else{var reversedArray=resolvedArgs[0].slice(0);reversedArray.reverse();return reversedArray;}},_functionAbs:function _functionAbs(resolvedArgs){return Math.abs(resolvedArgs[0]);},_functionCeil:function _functionCeil(resolvedArgs){return Math.ceil(resolvedArgs[0]);},_functionAvg:function _functionAvg(resolvedArgs){var sum=0;var inputArray=resolvedArgs[0];for(var i=0;i=0;},_functionFloor:function _functionFloor(resolvedArgs){return Math.floor(resolvedArgs[0]);},_functionLength:function _functionLength(resolvedArgs){if(!isObject(resolvedArgs[0])){return resolvedArgs[0].length;}else{// As far as I can tell, there's no way to get the length +// of an object without O(n) iteration through the object. +return Object.keys(resolvedArgs[0]).length;}},_functionMap:function _functionMap(resolvedArgs){var mapped=[];var interpreter=this._interpreter;var exprefNode=resolvedArgs[0];var elements=resolvedArgs[1];for(var i=0;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.max.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var maxElement=elements[0];for(var i=1;i0){var typeName=this._getTypeName(resolvedArgs[0][0]);if(typeName===TYPE_NUMBER){return Math.min.apply(Math,resolvedArgs[0]);}else{var elements=resolvedArgs[0];var minElement=elements[0];for(var i=1;iexprB){return 1;}else if(exprAmaxNumber){maxNumber=current;maxRecord=resolvedArray[i];}}return maxRecord;},_functionMinBy:function _functionMinBy(resolvedArgs){var exprefNode=resolvedArgs[1];var resolvedArray=resolvedArgs[0];var keyFunction=this.createKeyFunction(exprefNode,[TYPE_NUMBER,TYPE_STRING]);var minNumber=Infinity;var minRecord;var current;for(var i=0;i1){for(var i=1;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],88:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(Array.isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};},{}],91:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if(_typeof(obj)==='object'){return Object.keys(obj).map(function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(Array.isArray(obj[k])){return obj[k].map(function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};},{}],92:[function(require,module,exports){arguments[4][89][0].apply(exports,arguments);},{"./decode":90,"./encode":91,"dup":89}],93:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require('process/browser.js').nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;// DOM APIs, for completeness +exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout);};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval);};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close();};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn;}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id);};// Does not start the time, just sets up the members needed. +exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs;};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1;};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout(function onTimeout(){if(item._onTimeout)item._onTimeout();},msecs);}};// That's not how node.js implements it but the exposed api is the same. +exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick(function onNextTick(){if(immediateIds[id]){// fn.call() is faster so we optimize for the common use-case +// @see http://jsperf.com/call-apply-segu +if(args){fn.apply(null,args);}else{fn.call(null);}// Prevent ids from leaking +exports.clearImmediate(id);}});return id;};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id];};}).call(this);}).call(this,require("timers").setImmediate,require("timers").clearImmediate);},{"process/browser.js":86,"timers":93}],94:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var punycode=require('punycode');exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url;function Url(){this.protocol=null;this.slashes=null;this.auth=null;this.host=null;this.port=null;this.hostname=null;this.hash=null;this.search=null;this.query=null;this.pathname=null;this.path=null;this.href=null;}// Reference: RFC 3986, RFC 1808, RFC 2396 +// define these here so at least they only have to be +// compiled once on the first module load. +var protocolPattern=/^([a-z0-9.+-]+:)/i,portPattern=/:[0-9]*$/,// RFC 2396: characters reserved for delimiting URLs. +// We actually just auto-escape these. +delims=['<','>','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons. +unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. +autoEscape=['\''].concat(unwise),// Characters that are never ever allowed in a hostname. +// Note that any invalid chars are also handled, but these +// are the ones that are *expected* to be seen, so we fast-path +// them. +nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. +unsafeProtocol={'javascript':true,'javascript:':true},// protocols that never have a hostname. +hostlessProtocol={'javascript':true,'javascript:':true},// protocols that always contain a // bit. +slashedProtocol={'http':true,'https':true,'ftp':true,'gopher':true,'file':true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=require('querystring');function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&isObject(url)&&url instanceof Url)return url;var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(!isString(url)){throw new TypeError("Parameter 'url' must be a string, not "+_typeof(url));}var rest=url;// trim before proceeding. +// This is to support parse stuff like " http://foo.com \n" +rest=rest.trim();var proto=protocolPattern.exec(rest);if(proto){proto=proto[0];var lowerProto=proto.toLowerCase();this.protocol=lowerProto;rest=rest.substr(proto.length);}// figure out if it's got a host +// user@server is *always* interpreted as a hostname, and url +// resolution will treat //foo/bar as host=foo,path=bar because that's +// how the browser resolves relative URLs. +if(slashesDenoteHost||proto||rest.match(/^\/\/[^@\/]+@[^@\/]+/)){var slashes=rest.substr(0,2)==='//';if(slashes&&!(proto&&hostlessProtocol[proto])){rest=rest.substr(2);this.slashes=true;}}if(!hostlessProtocol[proto]&&(slashes||proto&&!slashedProtocol[proto])){// there's a hostname. +// the first instance of /, ?, ;, or # ends the host. +// +// If there is an @ in the hostname, then non-host chars *are* allowed +// to the left of the last @ sign, unless some host-ending character +// comes *before* the @-sign. +// URLs are obnoxious. +// +// ex: +// http://a@b@c/ => user:a@b host:c +// http://a@b?@c => user:a host:c path:/?@c +// v0.12 TODO(isaacs): This is not quite how Chrome does things. +// Review our test case against browsers more comprehensively. +// find the first instance of any hostEndingChars +var hostEnd=-1;for(var i=0;i host:b auth:a path:/c@d +atSign=rest.lastIndexOf('@',hostEnd);}// Now we have a portion which is definitely the auth. +// Pull that off. +if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char +hostEnd=-1;for(var i=0;i127){// we replace non-ASCII char with a temporary placeholder +// we need this to make sure size of hostname is not +// broken by replacing non-ASCII by nothing +newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only +if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case. +this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){// IDNA Support: Returns a puny coded representation of "domain". +// It only converts the part of the domain name that +// has non ASCII characters. I.e. it dosent matter if +// you call it with a domain that already is in ASCII. +var domainArray=this.hostname.split('.');var newOut=[];for(var i=0;i0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}result.search=relative.search;result.query=relative.query;//to support http.request +if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){// no path at all. easy. +// we've already handled the other stuff above. +result.pathname=null;//to support http.request +if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}// if a url ENDs in . or .., then it must get a trailing slash. +// however, if it ends in anything else non-slashy, +// then it must NOT get a trailing slash. +var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host)&&(last==='.'||last==='..')||last==='';// strip single dots, resolve double dots to parent dir +// if the path tries to go above the root, `up` ends up > 0 +var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last=='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s +if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back +if(psychotic){result.hostname=result.host=isAbsolute?'':srcPath.length?srcPath.shift():'';//occationaly the auth can get stuck only in host +//this especialy happens in cases like +//url.resolveObject('mailto:local1@domain1', 'local2@domain2') +var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.host=result.hostname=authInHost.shift();}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(!srcPath.length){result.pathname=null;result.path=null;}else{result.pathname=srcPath.join('/');}//to support request.http +if(!isNull(result.pathname)||!isNull(result.search)){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host)this.hostname=host;};function isString(arg){return typeof arg==="string";}function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}function isNull(arg){return arg===null;}function isNullOrUndefined(arg){return arg==null;}},{"punycode":80,"querystring":89}],95:[function(require,module,exports){if(typeof Object.create==='function'){// implementation from standard node.js 'util' module +module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}});};}else{// old school shim for old browsers +module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function TempCtor(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor();ctor.prototype.constructor=ctor;};}},{}],96:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&_typeof(arg)==='object'&&typeof arg.copy==='function'&&typeof arg.fill==='function'&&typeof arg.readUInt8==='function';};},{}],97:[function(require,module,exports){(function(process,global){(function(){// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case'%s':return String(args[i++]);case'%d':return Number(args[i++]);case'%j':try{return JSON.stringify(args[i++]);}catch(_){return'[Circular]';}default:return x;}});for(var x=args[i];i= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) {// legacy... - ctx.showHidden = opts; - } else if (opts) {// got an "options" object - exports._extend(ctx, opts); - }// set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); - } exports.inspect = inspect;// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { 'bold': [1, 22], 'italic': [3, 23], 'underline': [4, 24], 'inverse': [7, 27], 'white': [37, 39], 'grey': [90, 39], 'black': [30, 39], 'blue': [34, 39], 'cyan': [36, 39], 'green': [32, 39], 'magenta': [35, 39], 'red': [31, 39], 'yellow': [33, 39] };// Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta',// "name": intentionally not styling - 'regexp': 'red' - }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function (val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) {// Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && value && isFunction(value.inspect) &&// Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect &&// Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; }// Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; }// Look up the keys of the object. - var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); }// IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); }// Some type of object without properties can be shortcutted. - if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}'];// Make Array say that they are Array - if (isArray(value)) { array = true; braces = ['[', ']']; }// Make functions say that they are functions - if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; }// Make RegExps say that they are RegExps - if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); }// Make dates with properties first say the date - if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); }// Make error with message first say the error - if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function (key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); - } function formatPrimitive(ctx, value) { - if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean');// For some reason typeof null is "object", so special case here. - if (isNull(value)) return ctx.stylize('null', 'null'); - } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function (key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function (line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function (line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function (prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; }// NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return _typeof(arg) === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return _typeof(arg) === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { - return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' ||// ES6 symbol - typeof arg === 'undefined'; - } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];// 26 Feb 16:19:34 - function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); }// log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function () { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); };/** + */ /* legacy: obj, showHidden, depth, colors*/function inspect(obj,opts){// default options +var ctx={seen:[],stylize:stylizeNoColor};// legacy... +if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){// legacy... +ctx.showHidden=opts;}else if(opts){// got an "options" object +exports._extend(ctx,opts);}// set default options +if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth);}exports.inspect=inspect;// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors={'bold':[1,22],'italic':[3,23],'underline':[4,24],'inverse':[7,27],'white':[37,39],'grey':[90,39],'black':[30,39],'blue':[34,39],'cyan':[36,39],'green':[32,39],'magenta':[35,39],'red':[31,39],'yellow':[33,39]};// Don't use 'blue' not visible on cmd.exe +inspect.styles={'special':'cyan','number':'yellow','boolean':'yellow','undefined':'grey','null':'bold','string':'green','date':'magenta',// "name": intentionally not styling +'regexp':'red'};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"\x1B["+inspect.colors[style][0]+'m'+str+"\x1B["+inspect.colors[style][1]+'m';}else{return str;}}function stylizeNoColor(str,styleType){return str;}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true;});return hash;}function formatValue(ctx,value,recurseTimes){// Provide a hook for user-specified inspect functions. +// Check that value is an object with an inspect function on it +if(ctx.customInspect&&value&&isFunction(value.inspect)&&// Filter out the util module, it's inspect function is special +value.inspect!==exports.inspect&&// Also filter out any prototype objects using the circular check. +!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes);}return ret;}// Primitive types cannot have properties +var primitive=formatPrimitive(ctx,value);if(primitive){return primitive;}// Look up the keys of the object. +var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value);}// IE doesn't make error fields non-enumerable +// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx +if(isError(value)&&(keys.indexOf('message')>=0||keys.indexOf('description')>=0)){return formatError(value);}// Some type of object without properties can be shortcutted. +if(keys.length===0){if(isFunction(value)){var name=value.name?': '+value.name:'';return ctx.stylize('[Function'+name+']','special');}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),'date');}if(isError(value)){return formatError(value);}}var base='',array=false,braces=['{','}'];// Make Array say that they are Array +if(isArray(value)){array=true;braces=['[',']'];}// Make functions say that they are functions +if(isFunction(value)){var n=value.name?': '+value.name:'';base=' [Function'+n+']';}// Make RegExps say that they are RegExps +if(isRegExp(value)){base=' '+RegExp.prototype.toString.call(value);}// Make dates with properties first say the date +if(isDate(value)){base=' '+Date.prototype.toUTCString.call(value);}// Make error with message first say the error +if(isError(value)){base=' '+formatError(value);}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1];}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}else{return ctx.stylize('[Object]','special');}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array);});}ctx.seen.pop();return reduceToSingleString(output,base,braces);}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize('undefined','undefined');if(isString(value)){var simple='\''+JSON.stringify(value).replace(/^"|"$/g,'').replace(/'/g,"\\'").replace(/\\"/g,'"')+'\'';return ctx.stylize(simple,'string');}if(isNumber(value))return ctx.stylize(''+value,'number');if(isBoolean(value))return ctx.stylize(''+value,'boolean');// For some reason typeof null is "object", so special case here. +if(isNull(value))return ctx.stylize('null','null');}function formatError(value){return'['+Error.prototype.toString.call(value)+']';}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split('\n').map(function(line){return' '+line;}).join('\n').substr(2);}else{str='\n'+str.split('\n').map(function(line){return' '+line;}).join('\n');}}}else{str=ctx.stylize('[Circular]','special');}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str;}name=JSON.stringify(''+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,'name');}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,'string');}}return name+': '+str;}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf('\n')>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,'').length+1;},0);if(length>60){return braces[0]+(base===''?'':base+'\n ')+' '+output.join(',\n ')+' '+braces[1];}return braces[0]+base+' '+output.join(', ')+' '+braces[1];}// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar){return Array.isArray(ar);}exports.isArray=isArray;function isBoolean(arg){return typeof arg==='boolean';}exports.isBoolean=isBoolean;function isNull(arg){return arg===null;}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null;}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==='number';}exports.isNumber=isNumber;function isString(arg){return typeof arg==='string';}exports.isString=isString;function isSymbol(arg){return _typeof(arg)==='symbol';}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0;}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==='[object RegExp]';}exports.isRegExp=isRegExp;function isObject(arg){return _typeof(arg)==='object'&&arg!==null;}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==='[object Date]';}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==='[object Error]'||e instanceof Error);}exports.isError=isError;function isFunction(arg){return typeof arg==='function';}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==='boolean'||typeof arg==='number'||typeof arg==='string'||_typeof(arg)==='symbol'||// ES6 symbol +typeof arg==='undefined';}exports.isPrimitive=isPrimitive;exports.isBuffer=require('./support/isBuffer');function objectToString(o){return Object.prototype.toString.call(o);}function pad(n){return n<10?'0'+n.toString(10):n.toString(10);}var months=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];// 26 Feb 16:19:34 +function timestamp(){var d=new Date();var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(':');return[d.getDate(),months[d.getMonth()],time].join(' ');}// log is just a thin wrapper to console.log that prepends a timestamp +exports.log=function(){console.log('%s - %s',timestamp(),exports.format.apply(exports,arguments));};/** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */exports.inherits = require('inherits'); exports._extend = function (origin, add) {// Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; - }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } - }).call(this); - }).call(this, require('_process'), typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); - }, { "./support/isBuffer": 96, "_process": 86, "inherits": 95 }], 98: [function (require, module, exports) { var v1 = require('./v1'); var v4 = require('./v4'); var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; module.exports = uuid; }, { "./v1": 101, "./v4": 102 }], 99: [function (require, module, exports) {/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */var byteToHex = []; for (var i = 0; i < 256; ++i) { byteToHex[i] = (i + 0x100).toString(16).substr(1); } function bytesToUuid(buf, offset) { - var i = offset || 0; var bth = byteToHex;// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 - return [bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], '-', bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]], bth[buf[i++]]].join(''); - } module.exports = bytesToUuid; - }, {}], 100: [function (require, module, exports) {// Unique ID creation requires a high quality random # generator. In the - // browser this is a little complicated due to unknown quality of Math.random() - // and inconsistent support for the `crypto` API. We do the best we can via - // feature-detection - // getRandomValues needs to be invoked in a context where "this" is a Crypto - // implementation. Also, find the complete implementation of crypto on IE11. - var getRandomValues = typeof crypto != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto); if (getRandomValues) {// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto - var rnds8 = new Uint8Array(16);// eslint-disable-line no-undef - module.exports = function whatwgRNG() { getRandomValues(rnds8); return rnds8; }; - } else {// Math.random()-based (RNG) - // - // If all else fails, use Math.random(). It's fast, but is of unspecified - // quality. - var rnds = new Array(16); module.exports = function mathRNG() { for (var i = 0, r; i < 16; i++) { if ((i & 0x03) === 0) r = Math.random() * 0x100000000; rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } return rnds; }; - } - }, {}], 101: [function (require, module, exports) { - var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid');// **`v1()` - Generate time-based UUID** - // - // Inspired by https://github.com/LiosK/UUID.js - // and http://docs.python.org/library/uuid.html - var _nodeId; var _clockseq;// Previous uuid creation time - var _lastMSecs = 0; var _lastNSecs = 0;// See https://github.com/broofa/node-uuid for API details - function v1(options, buf, offset) { - var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;// node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - if (node == null || clockseq == null) { - var seedBytes = rng(); if (node == null) {// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } if (clockseq == null) {// Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - }// UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();// Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;// Time since last uuid creation (in msecs) - var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000;// Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; }// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; }// Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq;// Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000;// `time_low` - var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff;// `time_mid` - var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff;// `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10;// include version - b[i++] = tmh >>> 16 & 0xff;// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80;// `clock_seq_low` - b[i++] = clockseq & 0xff;// `node` - for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf ? buf : bytesToUuid(b); - } module.exports = v1; - }, { "./lib/bytesToUuid": 99, "./lib/rng": 100 }], 102: [function (require, module, exports) { - var rng = require('./lib/rng'); var bytesToUuid = require('./lib/bytesToUuid'); function v4(options, buf, offset) { - var i = buf && offset || 0; if (typeof options == 'string') { buf = options === 'binary' ? new Array(16) : null; options = null; } options = options || {}; var rnds = options.random || (options.rng || rng)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; rnds[8] = rnds[8] & 0x3f | 0x80;// Copy bytes to buffer, if provided - if (buf) { for (var ii = 0; ii < 16; ++ii) { buf[i + ii] = rnds[ii]; } } return buf || bytesToUuid(rnds); - } module.exports = v4; - }, { "./lib/bytesToUuid": 99, "./lib/rng": 100 }], 103: [function (require, module, exports) { - "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LRU_1 = require("./utils/LRU"); var CACHE_SIZE = 1000;/** - * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache] - */var EndpointCache =/** @class */function () { function EndpointCache(maxSize) { if (maxSize === void 0) { maxSize = CACHE_SIZE; } this.maxSize = maxSize; this.cache = new LRU_1.LRUCache(maxSize); }; Object.defineProperty(EndpointCache.prototype, "size", { get: function get() { return this.cache.length; }, enumerable: true, configurable: true }); EndpointCache.prototype.put = function (key, value) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; var endpointRecord = this.populateValue(value); this.cache.put(keyString, endpointRecord); }; EndpointCache.prototype.get = function (key) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; var now = Date.now(); var records = this.cache.get(keyString); if (records) { for (var i = 0; i < records.length; i++) { var record = records[i]; if (record.Expire < now) { this.cache.remove(keyString); return undefined; } } } return records; }; EndpointCache.getKeyString = function (key) { var identifiers = []; var identifierNames = Object.keys(key).sort(); for (var i = 0; i < identifierNames.length; i++) { var identifierName = identifierNames[i]; if (key[identifierName] === undefined) continue; identifiers.push(key[identifierName]); } return identifiers.join(' '); }; EndpointCache.prototype.populateValue = function (endpoints) { var now = Date.now(); return endpoints.map(function (endpoint) { return { Address: endpoint.Address || '', Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000 }; }); }; EndpointCache.prototype.empty = function () { this.cache.empty(); }; EndpointCache.prototype.remove = function (key) { var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key; this.cache.remove(keyString); }; return EndpointCache; }(); exports.EndpointCache = EndpointCache; - }, { "./utils/LRU": 104 }], 104: [function (require, module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var LinkedListNode =/** @class */function () { function LinkedListNode(key, value) { this.key = key; this.value = value; } return LinkedListNode; }(); var LRUCache =/** @class */function () { function LRUCache(size) { this.nodeMap = {}; this.size = 0; if (typeof size !== 'number' || size < 1) { throw new Error('Cache size can only be positive number'); } this.sizeLimit = size; } Object.defineProperty(LRUCache.prototype, "length", { get: function get() { return this.size; }, enumerable: true, configurable: true }); LRUCache.prototype.prependToList = function (node) { if (!this.headerNode) { this.tailNode = node; } else { this.headerNode.prev = node; node.next = this.headerNode; } this.headerNode = node; this.size++; }; LRUCache.prototype.removeFromTail = function () { if (!this.tailNode) { return undefined; } var node = this.tailNode; var prevNode = node.prev; if (prevNode) { prevNode.next = undefined; } node.prev = undefined; this.tailNode = prevNode; this.size--; return node; }; LRUCache.prototype.detachFromList = function (node) { if (this.headerNode === node) { this.headerNode = node.next; } if (this.tailNode === node) { this.tailNode = node.prev; } if (node.prev) { node.prev.next = node.next; } if (node.next) { node.next.prev = node.prev; } node.next = undefined; node.prev = undefined; this.size--; }; LRUCache.prototype.get = function (key) { if (this.nodeMap[key]) { var node = this.nodeMap[key]; this.detachFromList(node); this.prependToList(node); return node.value; } }; LRUCache.prototype.remove = function (key) { if (this.nodeMap[key]) { var node = this.nodeMap[key]; this.detachFromList(node); delete this.nodeMap[key]; } }; LRUCache.prototype.put = function (key, value) { if (this.nodeMap[key]) { this.remove(key); } else if (this.size === this.sizeLimit) { var tailNode = this.removeFromTail(); var key_1 = tailNode.key; delete this.nodeMap[key_1]; } var newNode = new LinkedListNode(key, value); this.nodeMap[key] = newNode; this.prependToList(newNode); }; LRUCache.prototype.empty = function () { var keys = Object.keys(this.nodeMap); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var node = this.nodeMap[key]; this.detachFromList(node); delete this.nodeMap[key]; } }; return LRUCache; }(); exports.LRUCache = LRUCache; }, {}], 105: [function (require, module, exports) {// AWS SDK for JavaScript v2.553.0 - // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - // License at https://sdk.amazonaws.com/js/BUNDLE_LICENSE.txt - require('./browser_loader'); var AWS = require('./core'); if (typeof window !== 'undefined') window.AWS = AWS; if (typeof module !== 'undefined') {/** - * @api private - */module.exports = AWS; - } if (typeof self !== 'undefined') self.AWS = AWS;/** - * @private - * DO NOT REMOVE - * browser builder will strip out this line if services are supplied on the command line. - */if (!Object.prototype.hasOwnProperty.call(AWS, 'Connect')) { AWS.apiLoader.services['connect'] = {}; AWS.Connect = AWS.Service.defineService('connect', ['2017-02-15']); } AWS.apiLoader.services['connect']['2017-02-15'] = require('../apis/connect-2017-02-15.min'); if (!Object.prototype.hasOwnProperty.call(AWS, 'STS')) { AWS.apiLoader.services['sts'] = {}; AWS.STS = AWS.Service.defineService('sts', ['2011-06-15']); require('./services/sts'); } AWS.apiLoader.services['sts']['2011-06-15'] = require('../apis/sts-2011-06-15.min'); - }, { "../apis/connect-2017-02-15.min": 3, "../apis/sts-2011-06-15.min": 5, "./browser_loader": 16, "./core": 18, "./services/sts": 61 }] - }, {}, [105]); - - /***/ -}), - -/***/ 417: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /**--------------------------------------------------------------- - * enum ClientMethods - */ - connect.ClientMethods = connect.makeEnum(['getAgentSnapshot', 'putAgentState', 'getAgentStates', 'getDialableCountryCodes', 'getRoutingProfileQueues', 'getAgentPermissions', 'getAgentConfiguration', 'updateAgentConfiguration', 'acceptContact', 'createOutboundContact', 'createTaskContact', 'clearContact', 'completeContact', 'destroyContact', 'rejectContact', 'notifyContactIssue', 'updateContactAttributes', 'createAdditionalConnection', 'destroyConnection', 'holdConnection', 'resumeConnection', 'toggleActiveConnections', 'conferenceConnections', 'sendClientLogs', 'sendDigits', 'sendSoftphoneCallReport', 'sendSoftphoneCallMetrics', 'getEndpoints', 'getNewAuthToken', 'createTransport', 'muteParticipant', 'unmuteParticipant']); - - /**--------------------------------------------------------------- - * enum AgentAppClientMethods - */ - connect.AgentAppClientMethods = { - GET_CONTACT: "AgentAppService.Lcms.getContact", - DELETE_SPEAKER: "AgentAppService.VoiceId.deleteSpeaker", - ENROLL_BY_SESSION: "AgentAppService.VoiceId.enrollBySession", - EVALUATE_SESSION: "AgentAppService.VoiceId.evaluateSession", - DESCRIBE_SPEAKER: "AgentAppService.VoiceId.describeSpeaker", - OPT_OUT_SPEAKER: "AgentAppService.VoiceId.optOutSpeaker", - UPDATE_VOICE_ID_DATA: "AgentAppService.Lcms.updateVoiceIdData", - DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", - UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", - START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", - LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" - }; - - /**--------------------------------------------------------------- - * enum MasterMethods - */ - connect.MasterMethods = connect.makeEnum(['becomeMaster', 'checkMaster']); - - /**--------------------------------------------------------------- - * abstract class ClientBase - */ - var ClientBase = function ClientBase() { }; - ClientBase.EMPTY_CALLBACKS = { - success: function success() { }, - failure: function failure() { } - }; - ClientBase.prototype.call = function (method, paramsIn, callbacksIn) { - connect.assertNotNull(method, 'method'); - var params = paramsIn || {}; - var callbacks = callbacksIn || ClientBase.EMPTY_CALLBACKS; - this._callImpl(method, params, callbacks); - }; - ClientBase.prototype._callImpl = function (method, params, callbacks) { - throw new connect.NotImplementedError(); - }; - - /**--------------------------------------------------------------- - * class NullClient extends ClientBase - */ - var NullClient = function NullClient() { - ClientBase.call(this); - }; - NullClient.prototype = Object.create(ClientBase.prototype); - NullClient.prototype.constructor = NullClient; - NullClient.prototype._callImpl = function (method, params, callbacks) { - if (callbacks && callbacks.failure) { - var message = connect.sprintf('No such method exists on NULL client: %s', method); - callbacks.failure(new connect.ValueError(message), { - message: message - }); - } - }; - - /**--------------------------------------------------------------- - * abstract class UpstreamConduitClientBase extends ClientBase - */ - var UpstreamConduitClientBase = function UpstreamConduitClientBase(conduit, requestEvent, responseEvent) { - ClientBase.call(this); - this.conduit = conduit; - this.requestEvent = requestEvent; - this.responseEvent = responseEvent; - this._requestIdCallbacksMap = {}; - this.conduit.onUpstream(responseEvent, connect.hitch(this, this._handleResponse)); - }; - UpstreamConduitClientBase.prototype = Object.create(ClientBase.prototype); - UpstreamConduitClientBase.prototype.constructor = UpstreamConduitClientBase; - UpstreamConduitClientBase.prototype._callImpl = function (method, params, callbacks) { - var request = connect.EventFactory.createRequest(this.requestEvent, method, params); - this._requestIdCallbacksMap[request.requestId] = callbacks; - this.conduit.sendUpstream(request.event, request); - }; - UpstreamConduitClientBase.prototype._getCallbacksForRequest = function (requestId) { - var callbacks = this._requestIdCallbacksMap[requestId] || null; - if (callbacks != null) { - delete this._requestIdCallbacksMap[requestId]; - } - return callbacks; - }; - UpstreamConduitClientBase.prototype._handleResponse = function (data) { - var callbacks = this._getCallbacksForRequest(data.requestId); - if (callbacks == null) { - return; - } - if (data.err && callbacks.failure) { - callbacks.failure(data.err, data.data); - } else if (callbacks.success) { - callbacks.success(data.data); - } - }; - - /**--------------------------------------------------------------- - * class UpstreamConduitClient extends ClientBase - */ - var UpstreamConduitClient = function UpstreamConduitClient(conduit) { - UpstreamConduitClientBase.call(this, conduit, connect.EventType.API_REQUEST, connect.EventType.API_RESPONSE); - }; - UpstreamConduitClient.prototype = Object.create(UpstreamConduitClientBase.prototype); - UpstreamConduitClient.prototype.constructor = UpstreamConduitClient; - - /**--------------------------------------------------------------- - * class UpstreamConduitMasterClient extends ClientBase - */ - var UpstreamConduitMasterClient = function UpstreamConduitMasterClient(conduit) { - UpstreamConduitClientBase.call(this, conduit, connect.EventType.MASTER_REQUEST, connect.EventType.MASTER_RESPONSE); - }; - UpstreamConduitMasterClient.prototype = Object.create(UpstreamConduitClientBase.prototype); - UpstreamConduitMasterClient.prototype.constructor = UpstreamConduitMasterClient; - - /**--------------------------------------------------------------- - * class AgentAppClient extends ClientBase - */ - var AgentAppClient = function AgentAppClient(authCookieName, authToken, endpoint) { - connect.assertNotNull(authCookieName, 'authCookieName'); - connect.assertNotNull(authToken, 'authToken'); - connect.assertNotNull(endpoint, 'endpoint'); - ClientBase.call(this); - this.endpointUrl = connect.getUrlWithProtocol(endpoint); - this.authToken = authToken; - this.authCookieName = authCookieName; - }; - AgentAppClient.prototype = Object.create(ClientBase.prototype); - AgentAppClient.prototype.constructor = AgentAppClient; - AgentAppClient.prototype._callImpl = function (method, params, callbacks) { - var self = this; - var bear = {}; - bear[self.authCookieName] = self.authToken; - var options = { - method: 'post', - body: JSON.stringify(params || {}), - headers: { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - 'X-Amz-target': method, - 'X-Amz-Bearer': JSON.stringify(bear) - } - }; - connect.fetch(self.endpointUrl, options).then(function (res) { - callbacks.success(res); - })["catch"](function (err) { - var reader = err.body.getReader(); - var body = ''; - var decoder = new TextDecoder(); - reader.read().then(function processText(_ref) { - var done = _ref.done, - value = _ref.value; - if (done) { - var error = JSON.parse(body); - error.status = err.status; - callbacks.failure(error); - return; - } - body += decoder.decode(value); - return reader.read().then(processText); - }); - }); - }; - /**--------------------------------------------------------------- - * class AWSClient extends ClientBase - */ - var AWSClient = function AWSClient(authToken, region, endpointIn) { - connect.assertNotNull(authToken, 'authToken'); - connect.assertNotNull(region, 'region'); - ClientBase.call(this); - AWS.config.credentials = new AWS.Credentials({}); - AWS.config.region = region; - this.authToken = authToken; - var baseUrl = connect.getBaseUrl(); - var endpointUrl = endpointIn || (baseUrl.includes(".awsapps.com") ? baseUrl + '/connect/api' : baseUrl + '/api'); - var endpoint = new AWS.Endpoint(endpointUrl); - this.client = new AWS.Connect({ - endpoint: endpoint - }); - }; - AWSClient.prototype = Object.create(ClientBase.prototype); - AWSClient.prototype.constructor = AWSClient; - AWSClient.prototype._callImpl = function (method, params, callbacks) { - var self = this; - var log = connect.getLog(); - if (!connect.contains(this.client, method)) { - var message = connect.sprintf('No such method exists on AWS client: %s', method); - callbacks.failure(new connect.ValueError(message), { - message: message - }); - } else { - params = this._translateParams(method, params); - log.trace("AWSClient: --> Calling operation '%s'", method).sendInternalLogToServer(); - this.client[method](params).on('build', function (request) { - request.httpRequest.headers['X-Amz-Bearer'] = self.authToken; - }).send(function (err, data) { - try { - if (err) { - if (err.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION) { - callbacks.authFailure(); - } else if (callbacks.accessDenied && (err.code === connect.CTIExceptions.ACCESS_DENIED_EXCEPTION || err.statusCode === 403)) { - callbacks.accessDenied(); - } else { - // Can't pass err directly to postMessage - // postMessage() tries to clone the err object and failed. - // Refer to https://github.com/goatslacker/alt-devtool/issues/5 - var error = {}; - error.type = err.code; - error.message = err.message; - error.stack = err.stack ? err.stack.split('\n') : []; - callbacks.failure(error, data); - } - log.trace("AWSClient: <-- Operation '%s' failed: %s", method, JSON.stringify(err)).sendInternalLogToServer(); - } else { - log.trace("AWSClient: <-- Operation '%s' succeeded.", method).withObject(data).sendInternalLogToServer(); - callbacks.success(data); - } - } catch (e) { - connect.getLog().error("Failed to handle AWS API request for method %s", method).withException(e).sendInternalLogToServer(); - } - }); - } - }; - AWSClient.prototype._requiresAuthenticationParam = function (method) { - return method !== connect.ClientMethods.COMPLETE_CONTACT && method !== connect.ClientMethods.CLEAR_CONTACT && method !== connect.ClientMethods.REJECT_CONTACT && method !== connect.ClientMethods.CREATE_TASK_CONTACT; - }; - AWSClient.prototype._translateParams = function (method, params) { - switch (method) { - case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: - params.configuration = this._translateAgentConfiguration(params.configuration); - break; - case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: - params.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(params.softphoneStreamStatistics); - break; - case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: - params.report = this._translateSoftphoneCallReport(params.report); - break; - default: - break; - } - if (this._requiresAuthenticationParam(method)) { - params.authentication = { - authToken: this.authToken - }; - } - return params; - }; - AWSClient.prototype._translateAgentConfiguration = function (config) { - return { - name: config.name, - softphoneEnabled: config.softphoneEnabled, - softphoneAutoAccept: config.softphoneAutoAccept, - extension: config.extension, - routingProfile: this._translateRoutingProfile(config.routingProfile), - agentPreferences: config.agentPreferences - }; - }; - AWSClient.prototype._translateRoutingProfile = function (profile) { - return { - name: profile.name, - routingProfileARN: profile.routingProfileARN, - defaultOutboundQueue: this._translateQueue(profile.defaultOutboundQueue) - }; - }; - AWSClient.prototype._translateQueue = function (queue) { - return { - queueARN: queue.queueARN, - name: queue.name - }; - }; - AWSClient.prototype._translateSoftphoneStreamStatistics = function (stats) { - stats.forEach(function (stat) { - if ('packetsCount' in stat) { - stat.packetCount = stat.packetsCount; - delete stat.packetsCount; - } - }); - return stats; - }; - AWSClient.prototype._translateSoftphoneCallReport = function (report) { - if ('handshakingTimeMillis' in report) { - report.handshakeTimeMillis = report.handshakingTimeMillis; - delete report.handshakingTimeMillis; - } - if ('preTalkingTimeMillis' in report) { - report.preTalkTimeMillis = report.preTalkingTimeMillis; - delete report.preTalkingTimeMillis; - } - if ('handshakingFailure' in report) { - report.handshakeFailure = report.handshakingFailure; - delete report.handshakingFailure; - } - if ('talkingTimeMillis' in report) { - report.talkTimeMillis = report.talkingTimeMillis; - delete report.talkingTimeMillis; - } - report.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(report.softphoneStreamStatistics); - return report; - }; - connect.ClientBase = ClientBase; - connect.NullClient = NullClient; - connect.UpstreamConduitClient = UpstreamConduitClient; - connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; - connect.AWSClient = AWSClient; - connect.AgentAppClient = AgentAppClient; - })(); - - /***/ -}), - -/***/ 531: -/***/ (() => { - - function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() { }; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - connect.core = {}; - connect.core.initialized = false; - connect.version = "1.7.6"; - connect.DEFAULT_BATCH_SIZE = 500; - var CCP_SYN_TIMEOUT = 1000; // 1 sec - var CCP_ACK_TIMEOUT = 3000; // 3 sec - var CCP_LOAD_TIMEOUT = 5000; // 5 sec - var CCP_IFRAME_REFRESH_INTERVAL = 5000; // 5 sec - - var LEGACY_LOGIN_URL_PATTERN = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}"; - var CLIENT_ID_MAP = { - "us-east-1": "06919f4fd8ed324e" - }; - var AUTHORIZE_ENDPOINT = "/auth/authorize"; - var LEGACY_AUTHORIZE_ENDPOINT = "/connect/auth/authorize"; - var AUTHORIZE_RETRY_INTERVAL = 2000; - var AUTHORIZE_MAX_RETRY = 5; - var LEGACY_WHITELISTED_ORIGINS_ENDPOINT = "/connect/whitelisted-origins"; - var WHITELISTED_ORIGINS_ENDPOINT = "/whitelisted-origins"; - var WHITELISTED_ORIGINS_RETRY_INTERVAL = 2000; - var WHITELISTED_ORIGINS_MAX_RETRY = 5; - connect.numberOfConnectedCCPs = 0; - var CCP_IFRAME_NAME = 'Amazon Connect CCP'; - - /** - * @deprecated - * This function was only meant for internal use. - * The name is misleading for what it should do. - * Internally we have replaced its usage with `getLoginUrl`. - */ - var createLoginUrl = function createLoginUrl(params) { - var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; - connect.assertNotNull(redirect); - if (params.loginUrl) { - return params.loginUrl; - } else if (params.alias) { - log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); - return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); - } else { - return params.ccpUrl; - } - }; - - /** - * Replaces `createLoginUrl`, as that function's name was misleading. - * The `params.alias` parameter is deprecated. Please refrain from using it. - */ - var getLoginUrl = function getLoginUrl(params) { - var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; - connect.assertNotNull(redirect); - if (params.loginUrl) { - return params.loginUrl; - } else if (params.alias) { - log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); - return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); - } else { - return params.ccpUrl; - } - }; - - /**------------------------------------------------------------------------- - * Returns scheme://host:port for a given url - */ - function sanitizeDomain(url) { - var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/ig); - return domain.length ? domain[0] : ""; - } - - /**------------------------------------------------------------------------- - * Print a warning message if the Connect core is not initialized. - */ - connect.core.checkNotInitialized = function () { - if (connect.core.initialized) { - var log = connect.getLog(); - log.warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer(); - } - }; - - /**------------------------------------------------------------------------- - * Basic Connect client initialization. - * Should be used only by the API Shared Worker. - */ - connect.core.init = function (params) { - connect.core.eventBus = new connect.EventBus(); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.initClient(params); - connect.core.initAgentAppClient(params); - connect.core.initialized = true; - }; - - /**------------------------------------------------------------------------- - * Initialized AWS client - * Should be used by Shared Worker to update AWS client with new credentials - * after refreshed authentication. - */ - connect.core.initClient = function (params) { - connect.assertNotNull(params, 'params'); - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var region = connect.assertNotNull(params.region, 'params.region'); - var endpoint = params.endpoint || null; - connect.core.client = new connect.AWSClient(authToken, region, endpoint); - }; - - /**------------------------------------------------------------------------- - * Initialized AgentApp client - * Should be used by Shared Worker to update AgentApp client with new credentials - * after refreshed authentication. - */ - connect.core.initAgentAppClient = function (params) { - connect.assertNotNull(params, 'params'); - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var authCookieName = connect.assertNotNull(params.authCookieName, 'params.authCookieName'); - var endpoint = connect.assertNotNull(params.agentAppEndpoint, 'params.agentAppEndpoint'); - connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); - }; - - /**------------------------------------------------------------------------- - * Uninitialize Connect. - */ - connect.core.terminate = function () { - connect.core.client = new connect.NullClient(); - connect.core.agentAppClient = new connect.NullClient(); - connect.core.masterClient = new connect.NullClient(); - var bus = connect.core.getEventBus(); - if (bus) bus.unsubscribeAll(); - connect.core.bus = new connect.EventBus(); - connect.core.agentDataProvider = null; - connect.core.softphoneManager = null; - connect.core.upstream = null; - connect.core.keepaliveManager = null; - connect.agent.initialized = false; - connect.core.initialized = false; - }; - - /**------------------------------------------------------------------------- - * Setup the SoftphoneManager to be initialized when the agent - * is determined to have softphone enabled. - */ - connect.core.softphoneUserMediaStream = null; - connect.core.getSoftphoneUserMediaStream = function () { - return connect.core.softphoneUserMediaStream; - }; - connect.core.setSoftphoneUserMediaStream = function (stream) { - connect.core.softphoneUserMediaStream = stream; - }; - connect.core.initRingtoneEngines = function (params) { - connect.assertNotNull(params, "params"); - var setupRingtoneEngines = function setupRingtoneEngines(ringtoneSettings) { - connect.assertNotNull(ringtoneSettings, "ringtoneSettings"); - connect.assertNotNull(ringtoneSettings.voice, "ringtoneSettings.voice"); - connect.assertTrue(ringtoneSettings.voice.ringtoneUrl || ringtoneSettings.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"); - connect.assertNotNull(ringtoneSettings.queue_callback, "ringtoneSettings.queue_callback"); - connect.assertTrue(ringtoneSettings.queue_callback.ringtoneUrl || ringtoneSettings.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"); - connect.core.ringtoneEngines = {}; - connect.agent(function (agent) { - agent.onRefresh(function () { - connect.ifMaster(connect.MasterTopics.RINGTONE, function () { - if (!ringtoneSettings.voice.disabled && !connect.core.ringtoneEngines.voice) { - connect.core.ringtoneEngines.voice = new connect.VoiceRingtoneEngine(ringtoneSettings.voice); - connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer(); - } - if (!ringtoneSettings.chat.disabled && !connect.core.ringtoneEngines.chat) { - connect.core.ringtoneEngines.chat = new connect.ChatRingtoneEngine(ringtoneSettings.chat); - connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer(); - } - if (!ringtoneSettings.task.disabled && !connect.core.ringtoneEngines.task) { - connect.core.ringtoneEngines.task = new connect.TaskRingtoneEngine(ringtoneSettings.task); - connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer(); - } - if (!ringtoneSettings.queue_callback.disabled && !connect.core.ringtoneEngines.queue_callback) { - connect.core.ringtoneEngines.queue_callback = new connect.QueueCallbackRingtoneEngine(ringtoneSettings.queue_callback); - connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer(); - } - }); - }); - }); - handleRingerDeviceChange(); - }; - var mergeParams = function mergeParams(params, otherParams) { - // For backwards compatibility: support pulling disabled flag and ringtoneUrl - // from softphone config if it exists from downstream into the ringtone config. - params.ringtone = params.ringtone || {}; - params.ringtone.voice = params.ringtone.voice || {}; - params.ringtone.queue_callback = params.ringtone.queue_callback || {}; - params.ringtone.chat = params.ringtone.chat || { - disabled: true - }; - params.ringtone.task = params.ringtone.task || { - disabled: true - }; - if (otherParams.softphone) { - if (otherParams.softphone.disableRingtone) { - params.ringtone.voice.disabled = true; - params.ringtone.queue_callback.disabled = true; - } - if (otherParams.softphone.ringtoneUrl) { - params.ringtone.voice.ringtoneUrl = otherParams.softphone.ringtoneUrl; - params.ringtone.queue_callback.ringtoneUrl = otherParams.softphone.ringtoneUrl; - } - } - if (otherParams.chat) { - if (otherParams.chat.disableRingtone) { - params.ringtone.chat.disabled = true; - } - if (otherParams.chat.ringtoneUrl) { - params.ringtone.chat.ringtoneUrl = otherParams.chat.ringtoneUrl; - } - } - - // Merge in ringtone settings from downstream. - if (otherParams.ringtone) { - params.ringtone.voice = connect.merge(params.ringtone.voice, otherParams.ringtone.voice || {}); - params.ringtone.queue_callback = connect.merge(params.ringtone.queue_callback, otherParams.ringtone.voice || {}); - params.ringtone.chat = connect.merge(params.ringtone.chat, otherParams.ringtone.chat || {}); - } - }; - - // Merge params from params.softphone and params.chat into params.ringtone - // for embedded and non-embedded use cases so that defaults are picked up. - mergeParams(params, params); - if (connect.isFramed()) { - // If the CCP is in a frame, wait for configuration from downstream. - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - this.unsubscribe(); - // Merge all params from data into params for any overridden - // values in either legacy "softphone" or "ringtone" settings. - mergeParams(params, data); - setupRingtoneEngines(params.ringtone); - }); - } else { - setupRingtoneEngines(params.ringtone); - } - }; - var handleRingerDeviceChange = function handleRingerDeviceChange() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, setRingerDevice); - }; - var setRingerDevice = function setRingerDevice(data) { - if (connect.keys(connect.core.ringtoneEngines).length === 0 || !data || !data.deviceId) { - return; - } - var deviceId = data.deviceId; - for (var ringtoneType in connect.core.ringtoneEngines) { - connect.core.ringtoneEngines[ringtoneType].setOutputDevice(deviceId); - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, - data: { - deviceId: deviceId - } - }); - }; - connect.core.initSoftphoneManager = function (paramsIn) { - connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); - var params = paramsIn || {}; - var competeForMasterOnAgentUpdate = function competeForMasterOnAgentUpdate(softphoneParamsIn) { - var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); - connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(); - connect.agent(function (agent) { - if (!agent.getChannelConcurrency(connect.ChannelType.VOICE)) { - return; - } - agent.onRefresh(function () { - var sub = this; - connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(); - connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { - connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(); - if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { - // Become master to send logs, since we need logs from softphone tab. - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); - sub.unsubscribe(); - } - }); - }); - }); - }; - - /** - * If the window is framed, we need to wait for a CONFIGURE message from - * downstream before we try to initialize, unless params.allowFramedSoftphone is true. - */ - if (connect.isFramed() && !params.allowFramedSoftphone) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - connect.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(); - if (data.softphone && data.softphone.allowFramedSoftphone) { - this.unsubscribe(); - competeForMasterOnAgentUpdate(data.softphone); - } - setupEventListenersForMultiTabUseInFirefox(data.softphone); - }); - } else { - competeForMasterOnAgentUpdate(params); - setupEventListenersForMultiTabUseInFirefox(params); - } - connect.agent(function (agent) { - // Sync mute across all tabs - if (agent.isSoftphoneEnabled() && agent.getChannelConcurrency(connect.ChannelType.VOICE)) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.MUTE - }); - } - }); - function setupEventListenersForMultiTabUseInFirefox(softphoneParamsIn) { - var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); - - // keep the softphone params for external use - connect.core.softphoneParams = softphoneParams; - if (connect.isFirefoxBrowser()) { - // In Firefox, when a tab takes over another tab's softphone primary, - // the previous primary tab should delete sofphone manager and stop microphone - connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, function (res) { - if (res.data && res.data.topic === connect.MasterTopics.SOFTPHONE && res.data.takeOver && res.data.masterId !== connect.core.portStreamId) { - if (connect.core.softphoneManager) { - connect.core.softphoneManager.onInitContactSub.unsubscribe(); - delete connect.core.softphoneManager; - } - var userMediaStream = connect.core.getSoftphoneUserMediaStream(); - if (userMediaStream) { - userMediaStream.getTracks().forEach(function (track) { - track.stop(); - }); - connect.core.setSoftphoneUserMediaStream(null); - } - } - }); - - // In Firefox, when multiple tabs are open, - // webrtc session is not started until READY_TO_START_SESSION event is triggered - connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, function () { - connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { - if (connect.core.softphoneManager) { - connect.core.softphoneManager.startSession(); - } - }, function () { - connect.becomeMaster(connect.MasterTopics.SOFTPHONE, function () { - connect.agent(function (agent) { - if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); - connect.core.softphoneManager.startSession(); - } - }); - }); - }); - }); - - // handling outbound-call and auto-accept cases for pending session - connect.contact(function (c) { - connect.agent(function (agent) { - c.onRefresh(function (contact) { - if (connect.hasOtherConnectedCCPs() && document.visibilityState === 'visible' && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { - var isOutBoundCall = contact.isSoftphoneCall() && !contact.isInbound(); - var isAutoAcceptEnabled = contact.isSoftphoneCall() && agent.getConfiguration().softphoneAutoAccept; - var isQueuedCallback = contact.getType() === connect.ContactType.QUEUE_CALLBACK; - if (isOutBoundCall || isAutoAcceptEnabled || isQueuedCallback) { - connect.core.triggerReadyToStartSessionEvent(); - } - } - }); - }); - }); - } - } - }; - - // trigger READY_TO_START_SESSION event in a context with Softphone Manager - // internal use only - connect.core.triggerReadyToStartSessionEvent = function () { - var allowFramedSoftphone = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; - if (connect.isCCP()) { - if (allowFramedSoftphone) { - // the event is triggered in this iframed CCP context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - if (connect.isFramed()) { - // if this is an iframed CCP, the event is send to downstream (CRM) - connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - // if this is a standalone CCP, trigger this event in this CCP context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } - } - } else { - if (allowFramedSoftphone) { - // the event is send to the upstream (iframed CCP) - connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION); - } else { - // the event is triggered in this CRM context - connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); - } - } - }; - connect.core.initPageOptions = function (params) { - connect.assertNotNull(params, "params"); - if (connect.isFramed()) { - // If the CCP is in a frame, wait for configuration from downstream. - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.CONFIGURE, function (data) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.CONFIGURE, - data: data - }); - }); - // Listen for iframe media devices request from CRM - bus.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, function () { - function sendDevices(devices) { - connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, devices); - } - if (navigator && navigator.mediaDevices) { - navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { - devices = devicesIn || []; - devices = devices.map(function (d) { - return d.toJSON(); - }); - sendDevices(devices); - })["catch"](function (err) { - sendDevices({ - error: err.message - }); - }); - } else { - sendDevices({ - error: "No navigator or navigator.mediaDevices object found" - }); - } - }); - } - }; - - /**------------------------------------------------------------------------- - * Get the list of media devices from iframed CCP - * Timeout for the request is passed an an optional argument - * The default timeout is 1000ms - */ - connect.core.getFrameMediaDevices = function (timeoutIn) { - var sub = null; - var timeout = timeoutIn || 1000; - var timeoutPromise = new Promise(function (resolve, reject) { - setTimeout(function () { - reject(new Error("Timeout exceeded")); - }, timeout); - }); - var mediaDevicesPromise = new Promise(function (resolve, reject) { - if (connect.isFramed() || connect.isCCP()) { - if (navigator && navigator.mediaDevices) { - navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { - devices = devicesIn || []; - devices = devices.map(function (d) { - return d.toJSON(); - }); - resolve(devices); - }); - } else { - reject(new Error("No navigator or navigator.mediaDevices object found")); - } - } else { - var bus = connect.core.getEventBus(); - sub = bus.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, function (data) { - if (data.error) { - reject(new Error(data.error)); - } else { - resolve(data); - } - }); - connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST); - } - }); - return Promise.race([mediaDevicesPromise, timeoutPromise])["finally"](function () { - if (sub) { - sub.unsubscribe(); - } - }); - }; - - //Internal use only. - connect.core.authorize = function (endpoint) { - var options = { - credentials: 'include' - }; - var authorizeEndpoint = endpoint; - if (!authorizeEndpoint) { - authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; - } - return connect.fetch(authorizeEndpoint, options, AUTHORIZE_RETRY_INTERVAL, AUTHORIZE_MAX_RETRY); - }; - - /** - * @deprecated - * This used to be used internally, but is no longer needed. - */ - connect.core.verifyDomainAccess = function (authToken, endpoint) { - connect.getLog().warn("This API will be deprecated in the next major version release"); - if (!connect.isFramed()) { - return Promise.resolve(); - } - var options = { - headers: { - 'X-Amz-Bearer': authToken - } - }; - var whitelistedOriginsEndpoint = null; - if (endpoint) { - whitelistedOriginsEndpoint = endpoint; - } else { - whitelistedOriginsEndpoint = connect.core.isLegacyDomain() ? LEGACY_WHITELISTED_ORIGINS_ENDPOINT : WHITELISTED_ORIGINS_ENDPOINT; - } - return connect.fetch(whitelistedOriginsEndpoint, options, WHITELISTED_ORIGINS_RETRY_INTERVAL, WHITELISTED_ORIGINS_MAX_RETRY).then(function (response) { - var topDomain = sanitizeDomain(window.document.referrer); - var isAllowed = response.whitelistedOrigins.some(function (origin) { - return topDomain === sanitizeDomain(origin); - }); - return isAllowed ? Promise.resolve() : Promise.reject(); - }); - }; - - /**------------------------------------------------------------------------- - * Returns true if this window's href is on the legacy connect domain. - * Only useful for internal use. - */ - connect.core.isLegacyDomain = function (url) { - url = url || window.location.href; - return url.includes('.awsapps.com'); - }; - - /**------------------------------------------------------------------------- - * Initializes Connect by creating or connecting to the API Shared Worker. - * Used only by the CCP - */ - connect.core.initSharedWorker = function (params) { - connect.core.checkNotInitialized(); - if (connect.core.initialized) { - return; - } - connect.assertNotNull(params, 'params'); - var sharedWorkerUrl = connect.assertNotNull(params.sharedWorkerUrl, 'params.sharedWorkerUrl'); - var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); - var refreshToken = connect.assertNotNull(params.refreshToken, 'params.refreshToken'); - var authTokenExpiration = connect.assertNotNull(params.authTokenExpiration, 'params.authTokenExpiration'); - var region = connect.assertNotNull(params.region, 'params.region'); - var endpoint = params.endpoint || null; - var authorizeEndpoint = params.authorizeEndpoint; - if (!authorizeEndpoint) { - authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; - } - var agentAppEndpoint = params.agentAppEndpoint || null; - var authCookieName = params.authCookieName || null; - try { - // Initialize the event bus and agent data providers. - connect.core.eventBus = new connect.EventBus({ - logEvents: true - }); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.mediaFactory = new connect.MediaFactory(params); - - // Create the shared worker and upstream conduit. - var worker = new SharedWorker(sharedWorkerUrl, "ConnectSharedWorker"); - var conduit = new connect.Conduit("ConnectSharedWorkerConduit", new connect.PortStream(worker.port), new connect.WindowIOStream(window, parent)); - - // Set the global upstream conduit for external use. - connect.core.upstream = conduit; - connect.core.webSocketProvider = new WebSocketProvider(); - - // Close our port to the shared worker before the window closes. - global.onunload = function () { - conduit.sendUpstream(connect.EventType.CLOSE); - worker.port.close(); - }; - connect.getLog().scheduleUpstreamLogPush(conduit); - connect.getLog().scheduleDownstreamClientSideLogsPush(); - // Bridge all upstream messages into the event bus. - conduit.onAllUpstream(connect.core.getEventBus().bridge()); - // Pass all upstream messages (from shared worker) downstream (to CCP consumer). - conduit.onAllUpstream(conduit.passDownstream()); - if (connect.isFramed()) { - // Bridge all downstream messages into the event bus. - conduit.onAllDownstream(connect.core.getEventBus().bridge()); - // Pass all downstream messages (from CCP consumer) upstream (to shared worker). - conduit.onAllDownstream(conduit.passUpstream()); - } - // Send configuration up to the shared worker. - conduit.sendUpstream(connect.EventType.CONFIGURE, { - authToken: authToken, - authTokenExpiration: authTokenExpiration, - endpoint: endpoint, - refreshToken: refreshToken, - region: region, - authorizeEndpoint: authorizeEndpoint, - agentAppEndpoint: agentAppEndpoint, - authCookieName: authCookieName - }); - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { - connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); - connect.core.initialized = true; - connect.core.portStreamId = data.id; - this.unsubscribe(); - }); - // Add all upstream log entries to our own logger. - conduit.onUpstream(connect.EventType.LOG, function (logEntry) { - if (logEntry.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); - } - }); - // Get worker logs - conduit.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logEntry) { - connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(logEntry)); - }); - // Get outer context logs - conduit.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logs) { - if (connect.isFramed() && Array.isArray(logs)) { - logs.forEach(function (log) { - connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(log)); - }); - } - }); - // Get log from outer context - conduit.onDownstream(connect.EventType.LOG, function (log) { - if (connect.isFramed() && log.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); - } - }); - // Reload the page if the shared worker detects an API auth failure. - conduit.onUpstream(connect.EventType.AUTH_FAIL, function (logEntry) { - location.reload(); - }); - connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); - connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); - connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(); - connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, function (data) { - var streamsVersion = data.streamsVersion; - connect.getLog().info("StreamsJS Version: " + streamsVersion).sendInternalLogToServer(); - }); - conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { - connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); - connect.numberOfConnectedCCPs = data.length; - }); - connect.core.client = new connect.UpstreamConduitClient(conduit); - connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - - // Pass the TERMINATE request upstream to the shared worker. - connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, conduit.passUpstream()); - - // Refresh the page when we receive the TERMINATED response from the - // shared worker. - connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { - window.location.reload(true); - }); - worker.port.start(); - conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { - if (data && data.domainId) { - connect.core.voiceIdDomainId = data.domainId; - } - }); - - // try fetching voiceId's domainId once the agent is initialized - connect.agent(function () { - var voiceId = new connect.VoiceId(); - voiceId.getDomainId().then(function (domainId) { - connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + domainId).sendInternalLogToServer(); - })["catch"](function (err) { - connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ - err: err - }).sendInternalLogToServer(); - }); - }); - - // Attempt to get permission to show notifications. - var nm = connect.core.getNotificationManager(); - nm.requestPermission(); - } catch (e) { - connect.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer(); - } - }; - connect.core._getCCPIframe = function () { - var _iterator = _createForOfIteratorHelper(window.document.getElementsByTagName('iframe')), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var iframe = _step.value; - if (iframe.name === CCP_IFRAME_NAME) { - return iframe; - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - return null; - }; - - /**------------------------------------------------------------------------- - * Initializes Connect by creating or connecting to the API Shared Worker. - * Initializes Connect by loading the CCP in an iframe and connecting to it. - */ - connect.core.initCCP = function (containerDiv, paramsIn) { - connect.core.checkNotInitialized(); - if (connect.core.initialized) { - return; - } - - // For backwards compatibility, when instead of taking a params object - // as input we only accepted ccpUrl. - var params = {}; - if (typeof paramsIn === 'string') { - params.ccpUrl = paramsIn; - } else { - params = paramsIn; - } - connect.assertNotNull(containerDiv, 'containerDiv'); - connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); - connect.storageAccess.init(params.ccpUrl, containerDiv, params.storageAccess || {}); - - // Create the CCP iframe and append it to the container div. - var iframe = document.createElement('iframe'); - iframe.src = params.ccpUrl; - iframe.allow = "microphone; autoplay"; - iframe.style = "width: 100%; height: 100%"; - iframe.title = 'Amazon Connect CCP'; - iframe.name = CCP_IFRAME_NAME; - - //for Storage Access follow the rsa path - if (connect.storageAccess.canRequest()) { - iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); - iframe.addEventListener('load', connect.storageAccess.request); - } - containerDiv.appendChild(iframe); - - // Build the upstream conduit communicating with the CCP iframe. - var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); - - // Set the global upstream conduit for external use. - connect.core.upstream = conduit; - - // Initialize the event bus and agent data providers. - // NOTE: Setting logEvents here to FALSE in order to avoid duplicating - // events which are logged in CCP. - connect.core.eventBus = new connect.EventBus({ - logEvents: false - }); - connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); - connect.core.mediaFactory = new connect.MediaFactory(params); - if (connect.storageAccess.canRequest()) { - // Create the Iframe and load the RSA banner and append it to the container div. - connect.storageAccess.setupRequestHandlers({ - onGrant: setupInitCCP - }); - } else { - setupInitCCP(); - } - function setupInitCCP() { - // Let CCP know if iframe is visible - iframe.onload = setTimeout(function () { - var style = window.getComputedStyle(iframe, null); - var data = { - display: style.display, - offsetWidth: iframe.offsetWidth, - offsetHeight: iframe.offsetHeight, - clientRectsLength: iframe.getClientRects().length - }; - conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); - }, 10000); - - // Init webSocketProvider - connect.core.webSocketProvider = new WebSocketProvider(); - conduit.onAllUpstream(connect.core.getEventBus().bridge()); - - // Initialize the keepalive manager. - connect.core.keepaliveManager = new KeepaliveManager(conduit, connect.core.getEventBus(), params.ccpSynTimeout || CCP_SYN_TIMEOUT, params.ccpAckTimeout || CCP_ACK_TIMEOUT); - connect.core.iframeRefreshInterval = null; - - // Allow 5 sec (default) before receiving the first ACK from the CCP. - connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { - connect.core.ccpLoadTimeoutInstance = null; - connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); - }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); - connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); - connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); - - // Once we receive the first ACK, setup our upstream API client and establish - // the SYN/ACK refresh flow. - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { - connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); - connect.core.client = new connect.UpstreamConduitClient(conduit); - connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); - connect.core.portStreamId = data.id; - if (params.softphone || params.chat || params.pageOptions) { - // Send configuration up to the CCP. - //set it to false if secondary - conduit.sendUpstream(connect.EventType.CONFIGURE, { - softphone: params.softphone, - chat: params.chat, - pageOptions: params.pageOptions - }); - } - if (connect.core.ccpLoadTimeoutInstance) { - global.clearTimeout(connect.core.ccpLoadTimeoutInstance); - connect.core.ccpLoadTimeoutInstance = null; - } - conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { - streamsVersion: connect.version - }); - connect.core.keepaliveManager.start(); - this.unsubscribe(); - connect.core.initialized = true; - connect.core.getEventBus().trigger(connect.EventType.INIT); - }); - - // Add any logs from the upstream to our own logger. - conduit.onUpstream(connect.EventType.LOG, function (logEntry) { - if (logEntry.loggerId !== connect.getLog().getLoggerId()) { - connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); - } - }); - - // Pop a login page when we encounter an ACK timeout. - connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { - // loginPopup is true by default, only false if explicitly set to false. - if (params.loginPopup !== false) { - try { - var loginUrl = getLoginUrl(params); - connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); - // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT - if (params.loginUrl) { - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - } - connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); - } catch (e) { - connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); - } - } - if (connect.core.iframeRefreshInterval == null) { - connect.core.iframeRefreshInterval = window.setInterval(function () { - if (connect.storageAccess.canRequest()) { - iframe.removeEventListener('load', connect.storageAccess.request); - iframe.addEventListener('load', connect.storageAccess.request); - iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); - } else { - iframe.src = params.ccpUrl; - } - }, CCP_IFRAME_REFRESH_INTERVAL); - conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { - this.unsubscribe(); - global.clearInterval(connect.core.iframeRefreshInterval); - connect.core.iframeRefreshInterval = null; - connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); - if ((params.loginPopupAutoClose || params.loginOptions && params.loginOptions.autoClose) && connect.core.loginWindow) { - connect.core.loginWindow.close(); - connect.core.loginWindow = null; - } - }); - } - }); - if (params.onViewContact) { - connect.core.onViewContact(params.onViewContact); - } - conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { - connect.numberOfConnectedCCPs = data.length; - }); - conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { - if (data && data.domainId) { - connect.core.voiceIdDomainId = data.domainId; - } - }); - - // keep the softphone params for external use - connect.core.softphoneParams = params.softphone; - } - }; - - /**-----------------------------------------------------------------------*/ - var KeepaliveManager = function KeepaliveManager(conduit, eventBus, synTimeout, ackTimeout) { - this.conduit = conduit; - this.eventBus = eventBus; - this.synTimeout = synTimeout; - this.ackTimeout = ackTimeout; - this.ackTimer = null; - this.synTimer = null; - this.ackSub = null; - }; - KeepaliveManager.prototype.start = function () { - var self = this; - this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE); - this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { - this.unsubscribe(); - global.clearTimeout(self.ackTimer); - self._deferStart(); - }); - this.ackTimer = global.setTimeout(function () { - self.ackSub.unsubscribe(); - self.eventBus.trigger(connect.EventType.ACK_TIMEOUT); - self._deferStart(); - }, this.ackTimeout); - }; - - //Fixes the keepalivemanager. - KeepaliveManager.prototype._deferStart = function () { - this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); - }; - - // For backwards compatibility only, in case customers are using this to start the keepalivemanager for some reason. - KeepaliveManager.prototype.deferStart = function () { - if (this.synTimer == null) { - this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); - } - }; - - /**-----------------------------------------------------------------------*/ - - var WebSocketProvider = function WebSocketProvider() { - var callbacks = { - initFailure: new Set(), - subscriptionUpdate: new Set(), - subscriptionFailure: new Set(), - topic: new Map(), - allMessage: new Set(), - connectionGain: new Set(), - connectionLost: new Set(), - connectionOpen: new Set(), - connectionClose: new Set() - }; - var invokeCallbacks = function invokeCallbacks(callbacks, response) { - callbacks.forEach(function (callback) { - callback(response); - }); - }; - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, function () { - invokeCallbacks(callbacks.initFailure); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, function (response) { - invokeCallbacks(callbacks.connectionOpen, response); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, function (response) { - invokeCallbacks(callbacks.connectionClose, response); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, function () { - invokeCallbacks(callbacks.connectionGain); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, function (response) { - invokeCallbacks(callbacks.connectionLost, response); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, function (response) { - invokeCallbacks(callbacks.subscriptionUpdate, response); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, function (response) { - invokeCallbacks(callbacks.subscriptionFailure, response); - }); - connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, function (response) { - invokeCallbacks(callbacks.allMessage, response); - if (callbacks.topic.has(response.topic)) { - invokeCallbacks(callbacks.topic.get(response.topic), response); - } - }); - this.sendMessage = function (webSocketPayload) { - connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, webSocketPayload); - }; - this.onInitFailure = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.initFailure.add(cb); - return function () { - return callbacks.initFailure["delete"](cb); - }; - }; - this.onConnectionOpen = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionOpen.add(cb); - return function () { - return callbacks.connectionOpen["delete"](cb); - }; - }; - this.onConnectionClose = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionClose.add(cb); - return function () { - return callbacks.connectionClose["delete"](cb); - }; - }; - this.onConnectionGain = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionGain.add(cb); - return function () { - return callbacks.connectionGain["delete"](cb); - }; - }; - this.onConnectionLost = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.connectionLost.add(cb); - return function () { - return callbacks.connectionLost["delete"](cb); - }; - }; - this.onSubscriptionUpdate = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.subscriptionUpdate.add(cb); - return function () { - return callbacks.subscriptionUpdate["delete"](cb); - }; - }; - this.onSubscriptionFailure = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.subscriptionFailure.add(cb); - return function () { - return callbacks.subscriptionFailure["delete"](cb); - }; - }; - this.subscribeTopics = function (topics) { - connect.assertNotNull(topics, 'topics'); - connect.assertTrue(connect.isArray(topics), 'topics must be a array'); - connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, topics); - }; - this.onMessage = function (topicName, cb) { - connect.assertNotNull(topicName, 'topicName'); - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - if (callbacks.topic.has(topicName)) { - callbacks.topic.get(topicName).add(cb); - } else { - callbacks.topic.set(topicName, new Set([cb])); - } - return function () { - return callbacks.topic.get(topicName)["delete"](cb); - }; - }; - this.onAllMessage = function (cb) { - connect.assertTrue(connect.isFunction(cb), 'method must be a function'); - callbacks.allMessage.add(cb); - return function () { - return callbacks.allMessage["delete"](cb); - }; - }; - }; - - /**-----------------------------------------------------------------------*/ - var AgentDataProvider = function AgentDataProvider(bus) { - var agentData = null; - this.bus = bus; - this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)); - }; - AgentDataProvider.prototype.updateAgentData = function (agentData) { - var oldAgentData = this.agentData; - this.agentData = agentData; - if (oldAgentData == null) { - connect.agent.initialized = true; - this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent()); - } - this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent()); - this._fireAgentUpdateEvents(oldAgentData); - }; - AgentDataProvider.prototype.getAgentData = function () { - if (this.agentData == null) { - throw new connect.StateError('No agent data is available yet!'); - } - return this.agentData; - }; - AgentDataProvider.prototype.getContactData = function (contactId) { - var agentData = this.getAgentData(); - var contactData = connect.find(agentData.snapshot.contacts, function (ctdata) { - return ctdata.contactId === contactId; - }); - if (contactData == null) { - throw new connect.StateError('Contact %s no longer exists.', contactId); - } - return contactData; - }; - AgentDataProvider.prototype.getConnectionData = function (contactId, connectionId) { - var contactData = this.getContactData(contactId); - var connectionData = connect.find(contactData.connections, function (cdata) { - return cdata.connectionId === connectionId; - }); - if (connectionData == null) { - throw new connect.StateError('Connection %s for contact %s no longer exists.', connectionId, contactId); - } - return connectionData; - }; - AgentDataProvider.prototype.getInstanceId = function () { - return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]; - }; - AgentDataProvider.prototype.getAWSAccountId = function () { - return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]; - }; - AgentDataProvider.prototype._diffContacts = function (oldAgentData) { - var diff = { - added: {}, - removed: {}, - common: {}, - oldMap: connect.index(oldAgentData == null ? [] : oldAgentData.snapshot.contacts, function (contact) { - return contact.contactId; - }), - newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { - return contact.contactId; - }) - }; - connect.keys(diff.oldMap).forEach(function (contactId) { - if (connect.contains(diff.newMap, contactId)) { - diff.common[contactId] = diff.newMap[contactId]; - } else { - diff.removed[contactId] = diff.oldMap[contactId]; - } - }); - connect.keys(diff.newMap).forEach(function (contactId) { - if (!connect.contains(diff.oldMap, contactId)) { - diff.added[contactId] = diff.newMap[contactId]; - } - }); - return diff; - }; - AgentDataProvider.prototype._fireAgentUpdateEvents = function (oldAgentData) { - var self = this; - var diff = null; - var oldAgentState = oldAgentData == null ? connect.AgentAvailStates.INIT : oldAgentData.snapshot.state.name; - var newAgentState = this.agentData.snapshot.state.name; - var oldRoutingState = oldAgentData == null ? connect.AgentStateType.INIT : oldAgentData.snapshot.state.type; - var newRoutingState = this.agentData.snapshot.state.type; - if (oldRoutingState !== newRoutingState) { - connect.core.getAgentRoutingEventGraph().getAssociations(this, oldRoutingState, newRoutingState).forEach(function (event) { - self.bus.trigger(event, new connect.Agent()); - }); - } - if (oldAgentState !== newAgentState) { - this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { - agent: new connect.Agent(), - oldState: oldAgentState, - newState: newAgentState - }); - connect.core.getAgentStateEventGraph().getAssociations(this, oldAgentState, newAgentState).forEach(function (event) { - self.bus.trigger(event, new connect.Agent()); - }); - } - var oldNextState = oldAgentData && oldAgentData.snapshot.nextState ? oldAgentData.snapshot.nextState.name : null; - var newNextState = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; - if (oldNextState !== newNextState && newNextState) { - self.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent()); - } - if (oldAgentData !== null) { - diff = this._diffContacts(oldAgentData); - } else { - diff = { - added: connect.index(this.agentData.snapshot.contacts, function (contact) { - return contact.contactId; - }), - removed: {}, - common: {}, - oldMap: {}, - newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { - return contact.contactId; - }) - }; - } - connect.values(diff.added).forEach(function (contactData) { - self.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(contactData.contactId)); - self._fireContactUpdateEvents(contactData.contactId, connect.ContactStateType.INIT, contactData.state.type); - }); - connect.values(diff.removed).forEach(function (contactData) { - self.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(contactData)); - self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, contactData.contactId), new connect.ContactSnapshot(contactData)); - self._unsubAllContactEventsForContact(contactData.contactId); - }); - connect.keys(diff.common).forEach(function (contactId) { - self._fireContactUpdateEvents(contactId, diff.oldMap[contactId].state.type, diff.newMap[contactId].state.type); - }); - }; - AgentDataProvider.prototype._fireContactUpdateEvents = function (contactId, oldContactState, newContactState) { - var self = this; - if (oldContactState !== newContactState) { - connect.core.getContactEventGraph().getAssociations(this, oldContactState, newContactState).forEach(function (event) { - self.bus.trigger(event, new connect.Contact(contactId)); - self.bus.trigger(connect.core.getContactEventName(event, contactId), new connect.Contact(contactId)); - }); - } - self.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(contactId)); - self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, contactId), new connect.Contact(contactId)); - }; - AgentDataProvider.prototype._unsubAllContactEventsForContact = function (contactId) { - var self = this; - connect.values(connect.ContactEvents).forEach(function (eventName) { - self.bus.getSubscriptions(connect.core.getContactEventName(eventName, contactId)).map(function (sub) { - sub.unsubscribe(); - }); - }); - }; - - /** ----- minimal view layer event handling **/ - - connect.core.onViewContact = function (f) { - connect.core.getUpstream().onUpstream(connect.ContactEvents.VIEW, f); - }; - - /** - * Used of agent interface control. - * connect.core.viewContact("contactId") -> this is curently programmed to get the contact into view. - */ - connect.core.viewContact = function (contactId) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.VIEW, - data: { - contactId: contactId - } - }); - }; - - /** ----- minimal view layer event handling **/ - - connect.core.onActivateChannelWithViewType = function (f) { - connect.core.getUpstream().onUpstream(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, f); - }; - - /** - * Used of agent interface control. - * connect.core.activateChannelWithViewType() -> this is curently programmed to get either the number pad, quick connects, or create task into view. - * the valid combinations are ("create_task", "task"), ("number_pad", "softphone"), ("create_task", "softphone"), ("quick_connects", "softphone") - * the softphone with create_task combo is a special case in the channel view to allow all three view type buttons to appear on the softphone screen - * - * The 'source' is an optional parameter which indicates the requester. For example, if invoked with ("create_task", "task", "agentapp") we would know agentapp requested open task view. - */ - connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { - var data = { - viewType: viewType, - mediaType: mediaType - }; - if (source) { - data.source = source; - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, - data: data - }); - }; - - /** - * Used to publish 'task created' event - */ - connect.core.triggerTaskCreated = function (data) { - connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, data); - }; - - /** ------------------------------------------------- */ - - /** - * This will be helpful for the custom and embedded CCPs - * to handle the access denied use case. - */ - connect.core.onAccessDenied = function (f) { - connect.core.getUpstream().onUpstream(connect.EventType.ACCESS_DENIED, f); - }; - - /** - * This will be helpful for SAML use cases to handle the custom logins. - */ - connect.core.onAuthFail = function (f) { - connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); - }; - - /** ------------------------------------------------- */ - - /** - * Used for handling the rtc session stats. - * Usage - * connect.core.onSoftphoneSessionInit(function({ connectionId }) { - * var softphoneManager = connect.core.getSoftphoneManager(); - * if(softphoneManager){ - * // access session - * var session = softphoneManager.getSession(connectionId); - * } - * }); - */ - - connect.core.onSoftphoneSessionInit = function (f) { - connect.core.getUpstream().onUpstream(connect.ConnectionEvents.SESSION_INIT, f); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.onConfigure = function (f) { - connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.CONFIGURE, f); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.onInitialized = function (f) { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.INIT, f); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getContactEventName = function (eventName, contactId) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(contactId, 'contactId'); - if (!connect.contains(connect.values(connect.ContactEvents), eventName)) { - throw new connect.ValueError('%s is not a valid contact event.', eventName); - } - return connect.sprintf('%s::%s', eventName, contactId); - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getEventBus = function () { - return connect.core.eventBus; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getWebSocketManager = function () { - return connect.core.webSocketProvider; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentDataProvider = function () { - return connect.core.agentDataProvider; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getLocalTimestamp = function () { - return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getSkew = function () { - return connect.core.getAgentDataProvider().getAgentData().snapshot.skew; - }; - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentRoutingEventGraph = function () { - return connect.core.agentRoutingEventGraph; - }; - connect.core.agentRoutingEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, connect.AgentEvents.ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, connect.AgentEvents.NOT_ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, connect.AgentEvents.OFFLINE); - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentStateEventGraph = function () { - return connect.core.agentStateEventGraph; - }; - connect.core.agentStateEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.AgentEvents.ERROR).assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, connect.AgentEvents.ACW); - - /**-----------------------------------------------------------------------*/ - connect.core.getContactEventGraph = function () { - return connect.core.contactEventGraph; - }; - connect.core.contactEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.ContactStateType.INCOMING, connect.ContactEvents.INCOMING).assoc(connect.EventGraph.ANY, connect.ContactStateType.PENDING, connect.ContactEvents.PENDING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTING, connect.ContactEvents.CONNECTING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTED, connect.ContactEvents.CONNECTED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ENDED, connect.ContactEvents.ACW).assoc(connect.values(connect.CONTACT_ACTIVE_STATES), connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), connect.ContactEvents.ENDED).assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.ContactEvents.ERROR).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED); - - /**-----------------------------------------------------------------------*/ - connect.core.getClient = function () { - if (!connect.core.client) { - throw new connect.StateError('The connect core has not been initialized!'); - } - return connect.core.client; - }; - connect.core.client = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getAgentAppClient = function () { - if (!connect.core.agentAppClient) { - throw new connect.StateError('The connect AgentApp Client has not been initialized!'); - } - return connect.core.agentAppClient; - }; - connect.core.agentAppClient = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getMasterClient = function () { - if (!connect.core.masterClient) { - throw new connect.StateError('The connect master client has not been initialized!'); - } - return connect.core.masterClient; - }; - connect.core.masterClient = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getSoftphoneManager = function () { - return connect.core.softphoneManager; - }; - connect.core.softphoneManager = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getNotificationManager = function () { - if (!connect.core.notificationManager) { - connect.core.notificationManager = new connect.NotificationManager(); - } - return connect.core.notificationManager; - }; - connect.core.notificationManager = null; - - /**-----------------------------------------------------------------------*/ - connect.core.getPopupManager = function () { - return connect.core.popupManager; - }; - connect.core.popupManager = new connect.PopupManager(); - - /**-----------------------------------------------------------------------*/ - connect.core.getUpstream = function () { - if (!connect.core.upstream) { - throw new connect.StateError('There is no upstream conduit!'); - } - return connect.core.upstream; - }; - connect.core.upstream = null; - - /**-----------------------------------------------------------------------*/ - connect.core.AgentDataProvider = AgentDataProvider; - })(); - - /***/ -}), - -/***/ 547: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - var ALL_EVENTS = '<>'; - - /**--------------------------------------------------------------- - * enum EventType - */ - var EventType = connect.makeEnum(['acknowledge', 'ack_timeout', 'init', 'api_request', 'api_response', 'auth_fail', 'access_denied', 'close', 'configure', 'log', 'master_request', 'master_response', 'synchronize', 'terminate', 'terminated', 'send_logs', 'reload_agent_configuration', 'broadcast', 'api_metric', 'client_metric', 'softphone_stats', 'softphone_report', 'client_side_logs', 'server_bound_internal_log', 'mute', "iframe_style", "update_connected_ccps", "outer_context_info", "media_device_request", "media_device_response"]); - - /**--------------------------------------------------------------- - * enum MasterTopics - */ - var MasterTopics = connect.makeNamespacedEnum('connect', ['loginPopup', 'sendLogs', 'softphone', 'ringtone', 'metrics']); - - /**--------------------------------------------------------------- - * enum AgentEvents - */ - var AgentEvents = connect.makeNamespacedEnum('agent', ['init', 'update', 'refresh', 'routable', 'not_routable', 'pending', 'contact_pending', 'offline', 'error', 'softphone_error', 'websocket_connection_lost', 'websocket_connection_gained', 'state_change', 'acw', 'mute_toggle', 'local_media_stream_created', 'enqueued_next_state']); - - /**--------------------------------------------------------------- - * enum WebSocketEvents - */ - var WebSocketEvents = connect.makeNamespacedEnum('webSocket', ['init_failure', 'connection_open', 'connection_close', 'connection_error', 'connection_gain', 'connection_lost', 'subscription_update', 'subscription_failure', 'all_message', 'send', 'subscribe']); - - /**--------------------------------------------------------------- - * enum ContactEvents - */ - var ContactEvents = connect.makeNamespacedEnum('contact', ['init', 'refresh', 'destroyed', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'acw', 'view', 'ended', 'error', 'accepted']); - var ChannelViewEvents = connect.makeNamespacedEnum('taskList', ['activate_channel_with_view_type']); - var TaskEvents = connect.makeNamespacedEnum('task', ['created']); - - /**--------------------------------------------------------------- - * enum ConnectionEvents - */ - var ConnectionEvents = connect.makeNamespacedEnum('connection', ['session_init', 'ready_to_start_session']); - - /**--------------------------------------------------------------- - * enum Configuration Events - */ - var ConfigurationEvents = connect.makeNamespacedEnum('configuration', ['configure', 'set_speaker_device', 'set_microphone_device', 'set_ringer_device', 'speaker_device_changed', 'microphone_device_changed', 'ringer_device_changed']); - - /**--------------------------------------------------------------- - * enum VoiceId Events - */ - var VoiceIdEvents = connect.makeNamespacedEnum('voiceId', ['update_domain_id']); - - /**--------------------------------------------------------------- - * class EventFactory - */ - var EventFactory = function EventFactory() { }; - EventFactory.createRequest = function (type, method, params) { - return { - event: type, - requestId: connect.randomId(), - method: method, - params: params - }; - }; - EventFactory.createResponse = function (type, request, data, err) { - return { - event: type, - requestId: request.requestId, - data: data, - err: err || null - }; - }; - - /** - * An object representing an event subscription in an EventBus. - */ - var Subscription = function Subscription(subMap, eventName, f) { - this.subMap = subMap; - this.id = connect.randomId(); - this.eventName = eventName; - this.f = f; - }; - - /** - * Unsubscribe the handler of this subscription from the EventBus - * from which it was created. - */ - Subscription.prototype.unsubscribe = function () { - this.subMap.unsubscribe(this.eventName, this.id); - }; - - /** - * A map of event subscriptions, used by the EventBus. - */ - var SubscriptionMap = function SubscriptionMap() { - this.subIdMap = {}; - this.subEventNameMap = {}; - }; - - /** - * Add a subscription for the named event. Creates a new Subscription - * object and returns it. This object can be used to unsubscribe. - */ - SubscriptionMap.prototype.subscribe = function (eventName, f) { - var sub = new Subscription(this, eventName, f); - this.subIdMap[sub.id] = sub; - var subList = this.subEventNameMap[eventName] || []; - subList.push(sub); - this.subEventNameMap[eventName] = subList; - return sub; - }; - - /** - * Unsubscribe a subscription matching the given event name and id. - */ - SubscriptionMap.prototype.unsubscribe = function (eventName, subId) { - if (connect.contains(this.subEventNameMap, eventName)) { - this.subEventNameMap[eventName] = this.subEventNameMap[eventName].filter(function (s) { - return s.id !== subId; - }); - if (this.subEventNameMap[eventName].length < 1) { - delete this.subEventNameMap[eventName]; - } - } - if (connect.contains(this.subIdMap, subId)) { - delete this.subIdMap[subId]; - } - }; - - /** - * Get a list of all subscriptions in the subscription map. - */ - SubscriptionMap.prototype.getAllSubscriptions = function () { - return connect.values(this.subEventNameMap).reduce(function (a, b) { - return a.concat(b); - }, []); - }; - - /** - * Get a list of subscriptions for the given event name, or an empty - * list if there are no subscriptions. - */ - SubscriptionMap.prototype.getSubscriptions = function (eventName) { - return this.subEventNameMap[eventName] || []; - }; - - /** - * An object which maintains a map of subscriptions and serves as the - * mechanism for triggering events to be handled by subscribers. - */ - var EventBus = function EventBus(paramsIn) { - var params = paramsIn || {}; - this.subMap = new SubscriptionMap(); - this.logEvents = params.logEvents || false; - }; - - /** - * Subscribe to the named event. Returns a new Subscription object - * which can be used to unsubscribe. - */ - EventBus.prototype.subscribe = function (eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.subMap.subscribe(eventName, f); - }; - - /** - * Subscribe a function to be called on all events. - */ - EventBus.prototype.subscribeAll = function (f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.subMap.subscribe(ALL_EVENTS, f); - }; - - /** - * Get a list of subscriptions for the given event name, or an empty - * list if there are no subscriptions. - */ - EventBus.prototype.getSubscriptions = function (eventName) { - return this.subMap.getSubscriptions(eventName); - }; - - /** - * Trigger the given event with the given data. All methods subscribed - * to this event will be called and are provided with the given arbitrary - * data object and the name of the event, in that order. - */ - EventBus.prototype.trigger = function (eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - var self = this; - var allEventSubs = this.subMap.getSubscriptions(ALL_EVENTS); - var eventSubs = this.subMap.getSubscriptions(eventName); - if (this.logEvents && eventName !== connect.EventType.LOG && eventName !== connect.EventType.MASTER_RESPONSE && eventName !== connect.EventType.API_METRIC && eventName !== connect.EventType.SERVER_BOUND_INTERNAL_LOG) { - connect.getLog().trace("Publishing event: %s", eventName).sendInternalLogToServer(); - } - if (eventName.startsWith(connect.ContactEvents.ACCEPTED) && data && data.contactId && !(data instanceof connect.Contact)) { - data = new connect.Contact(data.contactId); - } - allEventSubs.concat(eventSubs).forEach(function (sub) { - try { - sub.f(data || null, eventName, self); - } catch (e) { - connect.getLog().error("'%s' event handler failed.", eventName).withException(e).sendInternalLogToServer(); - } - }); - }; - - /** - * Returns a closure which bridges an event from another EventBus to this bus. - * - * Usage: - * conduit.onUpstream("MyEvent", bus.bridge()); - */ - EventBus.prototype.bridge = function () { - var self = this; - return function (data, event) { - self.trigger(event, data); - }; - }; - - /** - * Unsubscribe all events in the event bus. - */ - EventBus.prototype.unsubscribeAll = function () { - this.subMap.getAllSubscriptions().forEach(function (sub) { - sub.unsubscribe(); - }); - }; - connect.EventBus = EventBus; - connect.EventFactory = EventFactory; - connect.EventType = EventType; - connect.AgentEvents = AgentEvents; - connect.ConfigurationEvents = ConfigurationEvents; - connect.ConnectionEvents = ConnectionEvents; - connect.ConnnectionEvents = ConnectionEvents; //deprecate on next major version release. - connect.ContactEvents = ContactEvents; - connect.ChannelViewEvents = ChannelViewEvents; - connect.TaskEvents = TaskEvents; - connect.VoiceIdEvents = VoiceIdEvents; - connect.WebSocketEvents = WebSocketEvents; - connect.MasterTopics = MasterTopics; - })(); - - /***/ -}), - -/***/ 42: -/***/ (() => { - - function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } - !function (e) { - var n = {}; - function t(o) { - if (n[o]) return n[o].exports; - var r = n[o] = { - i: o, - l: !1, - exports: {} - }; - return e[o].call(r.exports, r, r.exports, t), r.l = !0, r.exports; - } - t.m = e, t.c = n, t.d = function (e, n, o) { - t.o(e, n) || Object.defineProperty(e, n, { - enumerable: !0, - get: o - }); - }, t.r = function (e) { - "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { - value: "Module" - }), Object.defineProperty(e, "__esModule", { - value: !0 - }); - }, t.t = function (e, n) { - if (1 & n && (e = t(e)), 8 & n) return e; - if (4 & n && "object" == _typeof(e) && e && e.__esModule) return e; - var o = Object.create(null); - if (t.r(o), Object.defineProperty(o, "default", { - enumerable: !0, - value: e - }), 2 & n && "string" != typeof e) for (var r in e) t.d(o, r, function (n) { - return e[n]; - }.bind(null, r)); - return o; - }, t.n = function (e) { - var n = e && e.__esModule ? function () { - return e["default"]; - } : function () { - return e; - }; - return t.d(n, "a", n), n; - }, t.o = function (e, n) { - return Object.prototype.hasOwnProperty.call(e, n); - }, t.p = "", t(t.s = 2); - }([function (e, n, t) { - "use strict"; - - var o = t(1), - r = "NULL", - i = "CLIENT_LOGGER", - c = "DEBUG", - s = 2e3, - a = "aws/subscribe", - u = "aws/unsubscribe", - l = "aws/heartbeat", - f = "connected", - p = "disconnected"; - function d(e) { - return (d = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { - return _typeof(e); - } : function (e) { - return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); - })(e); - } - var b = { - assertTrue: function assertTrue(e, n) { - if (!e) throw new Error(n); - }, - assertNotNull: function assertNotNull(e, n) { - return b.assertTrue(null !== e && void 0 !== d(e), Object(o.sprintf)("%s must be provided", n || "A value")), e; - }, - isNonEmptyString: function isNonEmptyString(e) { - return "string" == typeof e && e.length > 0; - }, - assertIsList: function assertIsList(e, n) { - if (!Array.isArray(e)) throw new Error(n + " is not an array"); - }, - isFunction: function isFunction(e) { - return !!(e && e.constructor && e.call && e.apply); - }, - isObject: function isObject(e) { - return !("object" !== d(e) || null === e); - }, - isString: function isString(e) { - return "string" == typeof e; - }, - isNumber: function isNumber(e) { - return "number" == typeof e; - } - }, - g = new RegExp("^(wss://)\\w*"); - b.validWSUrl = function (e) { - return g.test(e); - }, b.getSubscriptionResponse = function (e, n, t) { - return { - topic: e, - content: { - status: n ? "success" : "failure", - topics: t - } - }; - }, b.assertIsObject = function (e, n) { - if (!b.isObject(e)) throw new Error(n + " is not an object!"); - }, b.addJitter = function (e) { - var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1; - n = Math.min(n, 1); - var t = Math.random() > .5 ? 1 : -1; - return Math.floor(e + t * e * Math.random() * n); - }, b.isNetworkOnline = function () { - return navigator.onLine; - }, b.isNetworkFailure = function (e) { - return !(!e._debug || !e._debug.type) && "NetworkingError" === e._debug.type; - }; - var y = b; - function m(e) { - return (m = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { - return _typeof(e); - } : function (e) { - return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); - })(e); - } - function S(e, n) { - return !n || "object" !== m(n) && "function" != typeof n ? function (e) { - if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - return e; - }(e) : n; - } - function k(e) { - return (k = Object.setPrototypeOf ? Object.getPrototypeOf : function (e) { - return e.__proto__ || Object.getPrototypeOf(e); - })(e); - } - function h(e, n) { - return (h = Object.setPrototypeOf || function (e, n) { - return e.__proto__ = n, e; - })(e, n); - } - function v(e, n) { - if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); - } - function w(e, n) { - for (var t = 0; t < n.length; t++) { - var o = n[t]; - o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); - } - } - function C(e, n, t) { - return n && w(e.prototype, n), t && w(e, t), e; - } - var T = function () { - function e() { - v(this, e); - } - return C(e, [{ - key: "debug", - value: function value(e) { } - }, { - key: "info", - value: function value(e) { } - }, { - key: "warn", - value: function value(e) { } - }, { - key: "error", - value: function value(e) { } - }]), e; - }(), - O = { - DEBUG: 10, - INFO: 20, - WARN: 30, - ERROR: 40 - }, - I = function () { - function e() { - v(this, e), this.updateLoggerConfig(), this.consoleLoggerWrapper = _(); - } - return C(e, [{ - key: "writeToClientLogger", - value: function value(e, n) { - if (this.hasClientLogger()) switch (e) { - case O.DEBUG: - return this._clientLogger.debug(n); - case O.INFO: - return this._clientLogger.info(n); - case O.WARN: - return this._clientLogger.warn(n); - case O.ERROR: - return this._clientLogger.error(n); - } - } - }, { - key: "isLevelEnabled", - value: function value(e) { - return e >= this._level; - } - }, { - key: "hasClientLogger", - value: function value() { - return null !== this._clientLogger; - } - }, { - key: "getLogger", - value: function value(e) { - var n = e.prefix || ""; - return this._logsDestination === c ? this.consoleLoggerWrapper : new N(n); - } - }, { - key: "updateLoggerConfig", - value: function value(e) { - var n = e || {}; - this._level = n.level || O.DEBUG, this._clientLogger = n.logger || null, this._logsDestination = r, n.debug && (this._logsDestination = c), n.logger && (this._logsDestination = i); - } - }]), e; - }(), - W = function () { - function e() { - v(this, e); - } - return C(e, [{ - key: "debug", - value: function value() { } - }, { - key: "info", - value: function value() { } - }, { - key: "warn", - value: function value() { } - }, { - key: "error", - value: function value() { } - }]), e; - }(), - N = function (e) { - function n(e) { - var t; - return v(this, n), (t = S(this, k(n).call(this))).prefix = e || "", t; - } - return function (e, n) { - if ("function" != typeof n && null !== n) throw new TypeError("Super expression must either be null or a function"); - e.prototype = Object.create(n && n.prototype, { - constructor: { - value: e, - writable: !0, - configurable: !0 - } - }), n && h(e, n); - }(n, W), C(n, [{ - key: "debug", - value: function value() { - for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; - return this._log(O.DEBUG, n); - } - }, { - key: "info", - value: function value() { - for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; - return this._log(O.INFO, n); - } - }, { - key: "warn", - value: function value() { - for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; - return this._log(O.WARN, n); - } - }, { - key: "error", - value: function value() { - for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; - return this._log(O.ERROR, n); - } - }, { - key: "_shouldLog", - value: function value(e) { - return E.hasClientLogger() && E.isLevelEnabled(e); - } - }, { - key: "_writeToClientLogger", - value: function value(e, n) { - return E.writeToClientLogger(e, n); - } - }, { - key: "_log", - value: function value(e, n) { - if (this._shouldLog(e)) { - var t = this._convertToSingleStatement(n); - return this._writeToClientLogger(e, t); - } - } - }, { - key: "_convertToSingleStatement", - value: function value(e) { - var n = ""; - this.prefix && (n += this.prefix + " "); - for (var t = 0; t < e.length; t++) { - var o = e[t]; - n += this._convertToString(o) + " "; - } - return n; - } - }, { - key: "_convertToString", - value: function value(e) { - try { - if (!e) return ""; - if (y.isString(e)) return e; - if (y.isObject(e) && y.isFunction(e.toString)) { - var n = e.toString(); - if ("[object Object]" !== n) return n; - } - return JSON.stringify(e); - } catch (n) { - return console.error("Error while converting argument to string", e, n), ""; - } - } - }]), n; - }(), - _ = function _() { - var e = new W(); - return e.debug = console.debug, e.info = console.info, e.warn = console.warn, e.error = console.error, e; - }, - E = new I(); - function F(e, n) { - for (var t = 0; t < n.length; t++) { - var o = n[t]; - o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); - } - } - var L = function () { - function e(n) { - var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : s; - !function (e, n) { - if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); - }(this, e), this.numAttempts = 0, this.executor = n, this.hasActiveReconnection = !1, this.defaultRetry = t; - } - var n, t, o; - return n = e, (t = [{ - key: "retry", - value: function value() { - var e = this; - this.hasActiveReconnection || (this.hasActiveReconnection = !0, setTimeout(function () { - e._execute(); - }, this._getDelay())); - } - }, { - key: "_execute", - value: function value() { - this.hasActiveReconnection = !1, this.executor(), this.numAttempts++; - } - }, { - key: "connected", - value: function value() { - this.numAttempts = 0; - } - }, { - key: "_getDelay", - value: function value() { - var e = Math.pow(2, this.numAttempts) * this.defaultRetry; - return e <= 3e4 ? e : 3e4; - } - }]) && F(n.prototype, t), o && F(n, o), e; - }(); - t.d(n, "a", function () { - return R; - }); - var x = function x() { - var e = E.getLogger({}), - n = y.isNetworkOnline(), - t = { - primary: null, - secondary: null - }, - o = { - reconnectWebSocket: !0, - websocketInitFailed: !1, - exponentialBackOffTime: 1e3, - exponentialTimeoutHandle: null, - lifeTimeTimeoutHandle: null, - webSocketInitCheckerTimeoutId: null, - connState: null - }, - r = { - connectWebSocketRetryCount: 0, - connectionAttemptStartTime: null, - noOpenConnectionsTimestamp: null - }, - i = { - pendingResponse: !1, - intervalHandle: null - }, - c = { - initFailure: new Set(), - getWebSocketTransport: null, - subscriptionUpdate: new Set(), - subscriptionFailure: new Set(), - topic: new Map(), - allMessage: new Set(), - connectionGain: new Set(), - connectionLost: new Set(), - connectionOpen: new Set(), - connectionClose: new Set() - }, - s = { - connConfig: null, - promiseHandle: null, - promiseCompleted: !0 - }, - d = { - subscribed: new Set(), - pending: new Set(), - subscriptionHistory: new Set() - }, - b = { - responseCheckIntervalId: null, - requestCompleted: !0, - reSubscribeIntervalId: null, - consecutiveFailedSubscribeAttempts: 0, - consecutiveNoResponseRequest: 0 - }, - g = new L(function () { - U(); - }), - m = new Set([a, u, l]), - S = setInterval(function () { - if (n !== y.isNetworkOnline()) { - if (!(n = y.isNetworkOnline())) return void J(e.info("Network offline")); - var t = O(); - n && (!t || w(t, WebSocket.CLOSING) || w(t, WebSocket.CLOSED)) && (J(e.info("Network online, connecting to WebSocket server")), U()); - } - }, 250), - k = function k(n, t) { - n.forEach(function (n) { - try { - n(t); - } catch (n) { - J(e.error("Error executing callback", n)); - } - }); - }, - h = function h(e) { - if (null === e) return "NULL"; - switch (e.readyState) { - case WebSocket.CONNECTING: - return "CONNECTING"; - case WebSocket.OPEN: - return "OPEN"; - case WebSocket.CLOSING: - return "CLOSING"; - case WebSocket.CLOSED: - return "CLOSED"; - default: - return "UNDEFINED"; - } - }, - v = function v() { - var n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ""; - J(e.debug("[" + n + "] Primary WebSocket: " + h(t.primary) + " | Secondary WebSocket: " + h(t.secondary))); - }, - w = function w(e, n) { - return e && e.readyState === n; - }, - C = function C(e) { - return w(e, WebSocket.OPEN); - }, - T = function T(e) { - return null === e || void 0 === e.readyState || w(e, WebSocket.CLOSED); - }, - O = function O() { - return null !== t.secondary ? t.secondary : t.primary; - }, - I = function I() { - return C(O()); - }, - W = function W() { - if (i.pendingResponse) return J(e.warn("Heartbeat response not received")), clearInterval(i.intervalHandle), i.pendingResponse = !1, void U(); - I() ? (J(e.debug("Sending heartbeat")), O().send(G(l)), i.pendingResponse = !0) : (J(e.warn("Failed to send heartbeat since WebSocket is not open")), v("sendHeartBeat"), U()); - }, - N = function N() { - o.exponentialBackOffTime = 1e3, i.pendingResponse = !1, o.reconnectWebSocket = !0, clearTimeout(o.lifeTimeTimeoutHandle), clearInterval(i.intervalHandle), clearTimeout(o.exponentialTimeoutHandle), clearTimeout(o.webSocketInitCheckerTimeoutId); - }, - _ = function _() { - b.consecutiveFailedSubscribeAttempts = 0, b.consecutiveNoResponseRequest = 0, clearInterval(b.responseCheckIntervalId), clearInterval(b.reSubscribeIntervalId); - }, - F = function F() { - r.connectWebSocketRetryCount = 0, r.connectionAttemptStartTime = null, r.noOpenConnectionsTimestamp = null; - }, - x = function x() { - try { - J(e.info("WebSocket connection established!")), v("webSocketOnOpen"), null !== o.connState && o.connState !== p || k(c.connectionGain), o.connState = f; - var n = Date.now(); - k(c.connectionOpen, { - connectWebSocketRetryCount: r.connectWebSocketRetryCount, - connectionAttemptStartTime: r.connectionAttemptStartTime, - noOpenConnectionsTimestamp: r.noOpenConnectionsTimestamp, - connectionEstablishedTime: n, - timeToConnect: n - r.connectionAttemptStartTime, - timeWithoutConnection: r.noOpenConnectionsTimestamp ? n - r.noOpenConnectionsTimestamp : null - }), F(), N(), O().openTimestamp = Date.now(), 0 === d.subscribed.size && C(t.secondary) && D(t.primary, "[Primary WebSocket] Closing WebSocket"), (d.subscribed.size > 0 || d.pending.size > 0) && (C(t.secondary) && J(e.info("Subscribing secondary websocket to topics of primary websocket")), d.subscribed.forEach(function (e) { - d.subscriptionHistory.add(e), d.pending.add(e); - }), d.subscribed.clear(), A()), W(), i.intervalHandle = setInterval(W, 1e4); - var a = 1e3 * s.connConfig.webSocketTransport.transportLifeTimeInSeconds; - J(e.debug("Scheduling WebSocket manager reconnection, after delay " + a + " ms")), o.lifeTimeTimeoutHandle = setTimeout(function () { - J(e.debug("Starting scheduled WebSocket manager reconnection")), U(); - }, a); - } catch (n) { - J(e.error("Error after establishing WebSocket connection", n)); - } - }, - R = function R(n) { - v("webSocketOnError"), J(e.error("WebSocketManager Error, error_event: ", JSON.stringify(n))), U(); - }, - j = function j(n) { - var o = JSON.parse(n.data); - switch (o.topic) { - case a: - if (J(e.debug("Subscription Message received from webSocket server", n.data)), b.requestCompleted = !0, b.consecutiveNoResponseRequest = 0, "success" === o.content.status) b.consecutiveFailedSubscribeAttempts = 0, o.content.topics.forEach(function (e) { - d.subscriptionHistory["delete"](e), d.pending["delete"](e), d.subscribed.add(e); - }), 0 === d.subscriptionHistory.size ? C(t.secondary) && (J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")), D(t.primary, "[Primary WebSocket] Closing WebSocket")) : A(), k(c.subscriptionUpdate, o); else { - if (clearInterval(b.reSubscribeIntervalId), ++b.consecutiveFailedSubscribeAttempts, 5 === b.consecutiveFailedSubscribeAttempts) return k(c.subscriptionFailure, o), void (b.consecutiveFailedSubscribeAttempts = 0); - b.reSubscribeIntervalId = setInterval(function () { - A(); - }, 500); - } - break; - case l: - J(e.debug("Heartbeat response received")), i.pendingResponse = !1; - break; - default: - if (o.topic) { - if (J(e.debug("Message received for topic " + o.topic)), C(t.primary) && C(t.secondary) && 0 === d.subscriptionHistory.size && this === t.primary) return void J(e.warn("Ignoring Message for Topic " + o.topic + ", to avoid duplicates")); - if (0 === c.allMessage.size && 0 === c.topic.size) return void J(e.warn("No registered callback listener for Topic", o.topic)); - k(c.allMessage, o), c.topic.has(o.topic) && k(c.topic.get(o.topic), o); - } else o.message ? J(e.warn("WebSocketManager Message Error", o)) : J(e.warn("Invalid incoming message", o)); - } - }, - A = function n() { - if (b.consecutiveNoResponseRequest > 3) return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")), void k(c.subscriptionFailure, y.getSubscriptionResponse(a, !1, Array.from(d.pending))); - I() ? (clearInterval(b.responseCheckIntervalId), O().send(G(a, { - topics: Array.from(d.pending) - })), b.requestCompleted = !1, b.responseCheckIntervalId = setInterval(function () { - b.requestCompleted || (++b.consecutiveNoResponseRequest, n()); - }, 1e3)) : J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open")); - }, - D = function D(n, t) { - w(n, WebSocket.CONNECTING) || w(n, WebSocket.OPEN) ? n.close(1e3, t) : J(e.warn("Ignoring WebSocket Close request, WebSocket State: " + h(n))); - }, - M = function M(e) { - D(t.primary, "[Primary] WebSocket " + e), D(t.secondary, "[Secondary] WebSocket " + e); - }, - P = function P() { - r.connectWebSocketRetryCount++; - var n = y.addJitter(o.exponentialBackOffTime, .3); - Date.now() + n <= s.connConfig.urlConnValidTime ? (J(e.debug("Scheduling WebSocket reinitialization, after delay " + n + " ms")), o.exponentialTimeoutHandle = setTimeout(function () { - return q(); - }, n), o.exponentialBackOffTime *= 2) : (J(e.warn("WebSocket URL cannot be used to establish connection")), U()); - }, - H = function H(n) { - N(), _(), J(e.error("WebSocket Initialization failed")), o.websocketInitFailed = !0, M("Terminating WebSocket Manager"), clearInterval(S), k(c.initFailure, { - connectWebSocketRetryCount: r.connectWebSocketRetryCount, - connectionAttemptStartTime: r.connectionAttemptStartTime, - reason: n - }), F(); - }, - G = function G(e, n) { - return JSON.stringify({ - topic: e, - content: n - }); - }, - z = function z(n) { - return !!(y.isObject(n) && y.isObject(n.webSocketTransport) && y.isNonEmptyString(n.webSocketTransport.url) && y.validWSUrl(n.webSocketTransport.url) && 1e3 * n.webSocketTransport.transportLifeTimeInSeconds >= 3e5) || (J(e.error("Invalid WebSocket Connection Configuration", n)), !1); - }, - U = function U() { - if (y.isNetworkOnline()) { - if (o.websocketInitFailed) J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request")); else { - if (s.promiseCompleted) return N(), J(e.info("Fetching new WebSocket connection configuration")), r.connectionAttemptStartTime = r.connectionAttemptStartTime || Date.now(), s.promiseCompleted = !1, s.promiseHandle = c.getWebSocketTransport(), s.promiseHandle.then(function (n) { - return s.promiseCompleted = !0, J(e.debug("Successfully fetched webSocket connection configuration", n)), z(n) ? (s.connConfig = n, s.connConfig.urlConnValidTime = Date.now() + 85e3, g.connected(), q()) : (H("Invalid WebSocket connection configuration: " + n), { - webSocketConnectionFailed: !0 - }); - }, function (n) { - return s.promiseCompleted = !0, J(e.error("Failed to fetch webSocket connection configuration", n)), y.isNetworkFailure(n) ? (J(e.info("Retrying fetching new WebSocket connection configuration")), g.retry()) : H("Failed to fetch webSocket connection configuration: " + JSON.stringify(n)), { - webSocketConnectionFailed: !0 - }; - }); - J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")); - } - } else J(e.info("Network offline, ignoring this getWebSocketConnConfig request")); - }, - q = function q() { - if (o.websocketInitFailed) return J(e.info("web-socket initializing had failed, aborting re-init")), { - webSocketConnectionFailed: !0 - }; - if (!y.isNetworkOnline()) return J(e.warn("System is offline aborting web-socket init")), { - webSocketConnectionFailed: !0 - }; - J(e.info("Initializing Websocket Manager")), v("initWebSocket"); - try { - if (z(s.connConfig)) { - var n = null; - return C(t.primary) ? (J(e.debug("Primary Socket connection is already open")), w(t.secondary, WebSocket.CONNECTING) || (J(e.debug("Establishing a secondary web-socket connection")), t.secondary = B()), n = t.secondary) : (w(t.primary, WebSocket.CONNECTING) || (J(e.debug("Establishing a primary web-socket connection")), t.primary = B()), n = t.primary), o.webSocketInitCheckerTimeoutId = setTimeout(function () { - C(n) || P(); - }, 1e3), { - webSocketConnectionFailed: !1 - }; - } - } catch (n) { - return J(e.error("Error Initializing web-socket-manager", n)), H("Failed to initialize new WebSocket: " + n.message), { - webSocketConnectionFailed: !0 - }; - } - }, - B = function B() { - var n = new WebSocket(s.connConfig.webSocketTransport.url); - return n.addEventListener("open", x), n.addEventListener("message", j), n.addEventListener("error", R), n.addEventListener("close", function (i) { - return function (n, i) { - J(e.info("Socket connection is closed", n)), v("webSocketOnClose before-cleanup"), k(c.connectionClose, { - openTimestamp: i.openTimestamp, - closeTimestamp: Date.now(), - connectionDuration: Date.now() - i.openTimestamp, - code: n.code, - reason: n.reason - }), T(t.primary) && (t.primary = null), T(t.secondary) && (t.secondary = null), o.reconnectWebSocket && (C(t.primary) || C(t.secondary) ? T(t.primary) && C(t.secondary) && (J(e.info("[Primary] WebSocket Cleanly Closed")), t.primary = t.secondary, t.secondary = null) : (J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")), o.connState === p ? J(e.info("Ignoring connectionLost callback invocation")) : (k(c.connectionLost, { - openTimestamp: i.openTimestamp, - closeTimestamp: Date.now(), - connectionDuration: Date.now() - i.openTimestamp, - code: n.code, - reason: n.reason - }), r.noOpenConnectionsTimestamp = Date.now()), o.connState = p, U()), v("webSocketOnClose after-cleanup")); - }(i, n); - }), n; - }, - J = function J(e) { - return e && "function" == typeof e.sendInternalLogToServer && e.sendInternalLogToServer(), e; - }; - this.init = function (n) { - if (y.assertTrue(y.isFunction(n), "transportHandle must be a function"), null === c.getWebSocketTransport) return c.getWebSocketTransport = n, U(); - J(e.warn("Web Socket Manager was already initialized")); - }, this.onInitFailure = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.initFailure.add(e), o.websocketInitFailed && e(), function () { - return c.initFailure["delete"](e); - }; - }, this.onConnectionOpen = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionOpen.add(e), function () { - return c.connectionOpen["delete"](e); - }; - }, this.onConnectionClose = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionClose.add(e), function () { - return c.connectionClose["delete"](e); - }; - }, this.onConnectionGain = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionGain.add(e), I() && e(), function () { - return c.connectionGain["delete"](e); - }; - }, this.onConnectionLost = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionLost.add(e), o.connState === p && e(), function () { - return c.connectionLost["delete"](e); - }; - }, this.onSubscriptionUpdate = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.subscriptionUpdate.add(e), function () { - return c.subscriptionUpdate["delete"](e); - }; - }, this.onSubscriptionFailure = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.subscriptionFailure.add(e), function () { - return c.subscriptionFailure["delete"](e); - }; - }, this.onMessage = function (e, n) { - return y.assertNotNull(e, "topicName"), y.assertTrue(y.isFunction(n), "cb must be a function"), c.topic.has(e) ? c.topic.get(e).add(n) : c.topic.set(e, new Set([n])), function () { - return c.topic.get(e)["delete"](n); - }; - }, this.onAllMessage = function (e) { - return y.assertTrue(y.isFunction(e), "cb must be a function"), c.allMessage.add(e), function () { - return c.allMessage["delete"](e); - }; - }, this.subscribeTopics = function (e) { - y.assertNotNull(e, "topics"), y.assertIsList(e), e.forEach(function (e) { - d.subscribed.has(e) || d.pending.add(e); - }), b.consecutiveNoResponseRequest = 0, A(); - }, this.sendMessage = function (n) { - if (y.assertIsObject(n, "payload"), void 0 === n.topic || m.has(n.topic)) J(e.warn("Cannot send message, Invalid topic", n)); else { - try { - n = JSON.stringify(n); - } catch (t) { - return void J(e.warn("Error stringify message", n)); - } - I() ? O().send(n) : J(e.warn("Cannot send message, web socket connection is not open")); - } - }, this.closeWebSocket = function () { - N(), _(), o.reconnectWebSocket = !1, clearInterval(S), M("User request to close WebSocket"); - }, this.terminateWebSocketManager = H; - }, - R = { - create: function create() { - return new x(); - }, - setGlobalConfig: function setGlobalConfig(e) { - var n = e.loggerConfig; - E.updateLoggerConfig(n); - }, - LogLevel: O, - Logger: T - }; - }, function (e, n, t) { - var o; - !function () { - "use strict"; - - var r = { - not_string: /[^s]/, - not_bool: /[^t]/, - not_type: /[^T]/, - not_primitive: /[^v]/, - number: /[diefg]/, - numeric_arg: /[bcdiefguxX]/, - json: /[j]/, - not_json: /[^j]/, - text: /^[^\x25]+/, - modulo: /^\x25{2}/, - placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, - key: /^([a-z_][a-z_\d]*)/i, - key_access: /^\.([a-z_][a-z_\d]*)/i, - index_access: /^\[(\d+)\]/, - sign: /^[+-]/ - }; - function i(e) { - return function (e, n) { - var t, - o, - c, - s, - a, - u, - l, - f, - p, - d = 1, - b = e.length, - g = ""; - for (o = 0; o < b; o++) if ("string" == typeof e[o]) g += e[o]; else if ("object" == _typeof(e[o])) { - if ((s = e[o]).keys) for (t = n[d], c = 0; c < s.keys.length; c++) { - if (null == t) throw new Error(i('[sprintf] Cannot access property "%s" of undefined value "%s"', s.keys[c], s.keys[c - 1])); - t = t[s.keys[c]]; - } else t = s.param_no ? n[s.param_no] : n[d++]; - if (r.not_type.test(s.type) && r.not_primitive.test(s.type) && t instanceof Function && (t = t()), r.numeric_arg.test(s.type) && "number" != typeof t && isNaN(t)) throw new TypeError(i("[sprintf] expecting number but found %T", t)); - switch (r.number.test(s.type) && (f = t >= 0), s.type) { - case "b": - t = parseInt(t, 10).toString(2); - break; - case "c": - t = String.fromCharCode(parseInt(t, 10)); - break; - case "d": - case "i": - t = parseInt(t, 10); - break; - case "j": - t = JSON.stringify(t, null, s.width ? parseInt(s.width) : 0); - break; - case "e": - t = s.precision ? parseFloat(t).toExponential(s.precision) : parseFloat(t).toExponential(); - break; - case "f": - t = s.precision ? parseFloat(t).toFixed(s.precision) : parseFloat(t); - break; - case "g": - t = s.precision ? String(Number(t.toPrecision(s.precision))) : parseFloat(t); - break; - case "o": - t = (parseInt(t, 10) >>> 0).toString(8); - break; - case "s": - t = String(t), t = s.precision ? t.substring(0, s.precision) : t; - break; - case "t": - t = String(!!t), t = s.precision ? t.substring(0, s.precision) : t; - break; - case "T": - t = Object.prototype.toString.call(t).slice(8, -1).toLowerCase(), t = s.precision ? t.substring(0, s.precision) : t; - break; - case "u": - t = parseInt(t, 10) >>> 0; - break; - case "v": - t = t.valueOf(), t = s.precision ? t.substring(0, s.precision) : t; - break; - case "x": - t = (parseInt(t, 10) >>> 0).toString(16); - break; - case "X": - t = (parseInt(t, 10) >>> 0).toString(16).toUpperCase(); - } - r.json.test(s.type) ? g += t : (!r.number.test(s.type) || f && !s.sign ? p = "" : (p = f ? "+" : "-", t = t.toString().replace(r.sign, "")), u = s.pad_char ? "0" === s.pad_char ? "0" : s.pad_char.charAt(1) : " ", l = s.width - (p + t).length, a = s.width && l > 0 ? u.repeat(l) : "", g += s.align ? p + t + a : "0" === u ? p + a + t : a + p + t); - } - return g; - }(function (e) { - if (s[e]) return s[e]; - var n, - t = e, - o = [], - i = 0; - for (; t;) { - if (null !== (n = r.text.exec(t))) o.push(n[0]); else if (null !== (n = r.modulo.exec(t))) o.push("%"); else { - if (null === (n = r.placeholder.exec(t))) throw new SyntaxError("[sprintf] unexpected placeholder"); - if (n[2]) { - i |= 1; - var c = [], - a = n[2], - u = []; - if (null === (u = r.key.exec(a))) throw new SyntaxError("[sprintf] failed to parse named argument key"); - for (c.push(u[1]); "" !== (a = a.substring(u[0].length));) if (null !== (u = r.key_access.exec(a))) c.push(u[1]); else { - if (null === (u = r.index_access.exec(a))) throw new SyntaxError("[sprintf] failed to parse named argument key"); - c.push(u[1]); - } - n[2] = c; - } else i |= 2; - if (3 === i) throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported"); - o.push({ - placeholder: n[0], - param_no: n[1], - keys: n[2], - sign: n[3], - pad_char: n[4], - align: n[5], - width: n[6], - precision: n[7], - type: n[8] - }); - } - t = t.substring(n[0].length); - } - return s[e] = o; - }(e), arguments); - } - function c(e, n) { - return i.apply(null, [e].concat(n || [])); - } - var s = Object.create(null); - n.sprintf = i, n.vsprintf = c, "undefined" != typeof window && (window.sprintf = i, window.vsprintf = c, void 0 === (o = function () { - return { - sprintf: i, - vsprintf: c - }; - }.call(n, t, n, e)) || (e.exports = o)); - }(); - }, function (e, n, t) { - "use strict"; - - t.r(n), function (e) { - t.d(n, "WebSocketManager", function () { - return r; - }); - var o = t(0); - e.connect = e.connect || {}, connect.WebSocketManager = o.a; - var r = o.a; - }.call(this, t(3)); - }, function (e, n) { - var t; - t = function () { - return this; - }(); - try { - t = t || new Function("return this")(); - } catch (e) { - "object" == (typeof window === "undefined" ? "undefined" : _typeof(window)) && (t = window); - } - e.exports = t; - }]); - - /***/ -}), - -/***/ 312: -/***/ (() => { - - function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - // How frequently softphone logs should be collected and reported to shared worker. - var SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS = 5000; - - // How frequently logs should be collected and sent downstream - var LOGS_REPORT_INTERVAL_MILLIS = 5000; - - // The default log roll interval (30min) - var DEFAULT_LOG_ROLL_INTERVAL = 1800000; - - /** - * An enumeration of common logging levels. - */ - var LogLevel = { - TEST: "TEST", - TRACE: "TRACE", - DEBUG: "DEBUG", - INFO: "INFO", - LOG: "LOG", - WARN: "WARN", - ERROR: "ERROR", - CRITICAL: "CRITICAL" - }; - - /** - * An enumeration of common logging components. - */ - var LogComponent = { - CCP: "ccp", - SOFTPHONE: "softphone", - CHAT: "chat", - TASK: "task" - }; - - /** - * The numeric order of the logging levels above. - * They are spaced to allow the addition of other log - * levels at a later time. - */ - var LogLevelOrder = { - TEST: 0, - TRACE: 10, - DEBUG: 20, - INFO: 30, - LOG: 40, - WARN: 50, - ERROR: 100, - CRITICAL: 200 - }; - - /** - * A map from log level to console logger function. - */ - var CONSOLE_LOGGER_MAP = { - TRACE: function TRACE(text) { - console.info(text); - }, - DEBUG: function DEBUG(text) { - console.info(text); - }, - INFO: function INFO(text) { - console.info(text); - }, - LOG: function LOG(text) { - console.log(text); - }, - TEST: function TEST(text) { - console.log(text); - }, - WARN: function WARN(text) { - console.warn(text); - }, - ERROR: function ERROR(text) { - console.error(text); - }, - CRITICAL: function CRITICAL(text) { - console.error(text); - } - }; - - /** - * Checks if it is a valid log component enum - */ - - var isValidLogComponent = function isValidLogComponent(component) { - return Object.values(LogComponent).indexOf(component) !== -1; - }; - - /** - * Extract the custom arguments as required by the logger - */ - var extractLoggerArgs = function extractLoggerArgs(loggerArgs) { - var args = Array.prototype.slice.call(loggerArgs, 0); - var firstArg = args.shift(); - var format; - var component; - if (isValidLogComponent(firstArg)) { - component = firstArg; - format = args.shift(); - } else { - //default to CCP component - format = firstArg; - component = LogComponent.CCP; - } - return { - format: format, - component: component, - args: args - }; - }; - - /** - * A log entry. - * - * @param component The logging component. - * @param level The log level of this log entry. - * @param text The text contained in the log entry. - * @param loggerId The root logger id. - * - * Log entries are aware of their timestamp, order, - * and can contain objects and exception stack traces. - */ - var LogEntry = function LogEntry(component, level, text, loggerId) { - this.component = component; - this.level = level; - this.text = text; - this.time = new Date(); - this.exception = null; - this.objects = []; - this.line = 0; - this.agentResourceId = null; - try { - if (connect.agent.initialized) { - this.agentResourceId = new connect.Agent()._getResourceId(); - } - } catch (e) { - console.log("Issue finding agentResourceId: ", e); //can't use our logger here as we might infinitely attempt to log this error. - } - - this.loggerId = loggerId; - }; - LogEntry.fromObject = function (obj) { - var entry = new LogEntry(LogComponent.CCP, obj.level, obj.text, obj.loggerId); - - // Required to check for Date objects sent across frame boundaries - if (Object.prototype.toString.call(obj.time) === '[object Date]') { - entry.time = new Date(obj.time.getTime()); - } else if (typeof obj.time === 'number') { - entry.time = new Date(obj.time); - } else if (typeof obj.time === 'string') { - entry.time = Date.parse(obj.time); - } else { - entry.time = new Date(); - } - entry.exception = obj.exception; - entry.objects = obj.objects; - return entry; - }; - - /** - * Private method to remove sensitive info from client log - */ - var redactSensitiveInfo = function redactSensitiveInfo(data) { - var regex = /AuthToken.*\=/g; - if (data && _typeof(data) === 'object') { - Object.keys(data).forEach(function (key) { - if (_typeof(data[key]) === 'object') { - redactSensitiveInfo(data[key]); - } else if (typeof data[key] === 'string') { - if (key === "url" || key === "text") { - data[key] = data[key].replace(regex, "[redacted]"); - } else if (key === "quickConnectName") { - data[key] = "[redacted]"; - } - } - }); - } - }; - - /** - * Pulls the type, message, and stack trace - * out of the given exception for JSON serialization. - */ - var LoggedException = function LoggedException(e) { - this.type = e instanceof Error ? e.name : e.code || Object.prototype.toString.call(e); - this.message = e.message; - this.stack = e.stack ? e.stack.split('\n') : []; - }; - - /** - * Minimally stringify this log entry for printing - * to the console. - */ - LogEntry.prototype.toString = function () { - return connect.sprintf("[%s] [%s] [%s]: %s", this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", this.getLevel(), this.getAgentResourceId(), this.getText()); - }; - - /** - * Get the log entry timestamp. - */ - LogEntry.prototype.getTime = function () { - return this.time; - }; - LogEntry.prototype.getAgentResourceId = function () { - return this.agentResourceId; - }; - - /** - * Get the level of the log entry. - */ - LogEntry.prototype.getLevel = function () { - return this.level; - }; - - /** - * Get the log entry text. - */ - LogEntry.prototype.getText = function () { - return this.text; - }; - - /** - * Get the log entry component. - */ - LogEntry.prototype.getComponent = function () { - return this.component; - }; - - /** - * Add an exception stack trace to this log entry. - * A log entry may contain only one exception stack trace. - */ - LogEntry.prototype.withException = function (e) { - this.exception = new LoggedException(e); - return this; - }; - - /** - * Add an arbitrary object to the log entry. A log entry - * may contain any number of objects. - */ - LogEntry.prototype.withObject = function (obj) { - var copiedObj = connect.deepcopy(obj); - redactSensitiveInfo(copiedObj); - this.objects.push(copiedObj); - return this; - }; - - /** - * Add a cross origin event object to the log entry. A log entry - * may contain any number of objects. - */ - LogEntry.prototype.withCrossOriginEventObject = function (obj) { - var copiedObj = connect.deepcopyCrossOriginEvent(obj); - redactSensitiveInfo(copiedObj); - this.objects.push(copiedObj); - return this; - }; - - /** - * Indicate that this log entry should be sent to the server - * NOTE: This should be used for internal logs only - */ - LogEntry.prototype.sendInternalLogToServer = function () { - connect.getLog()._serverBoundInternalLogs.push(this); - return this; - }; - - /** - * The logger instance. - */ - var Logger = function Logger() { - this._logs = []; - this._rolledLogs = []; - this._logsToPush = []; - this._serverBoundInternalLogs = []; - this._echoLevel = LogLevelOrder.INFO; - this._logLevel = LogLevelOrder.INFO; - this._lineCount = 0; - this._logRollInterval = 0; - this._logRollTimer = null; - this._loggerId = new Date().getTime() + "-" + Math.random().toString(36).slice(2); - this.setLogRollInterval(DEFAULT_LOG_ROLL_INTERVAL); - this._startLogIndexToPush = 0; - }; - - /** - * Sets the interval in milliseconds that the logs will be rotated. - * Logs are rotated out completely at the end of the second roll - * and will eventually be garbage collected. - */ - Logger.prototype.setLogRollInterval = function (interval) { - var self = this; - if (!this._logRollTimer || interval !== this._logRollInterval) { - if (this._logRollTimer) { - global.clearInterval(this._logRollTimer); - } - this._logRollInterval = interval; - this._logRollTimer = global.setInterval(function () { - this._rolledLogs = this._logs; - this._logs = []; - this._startLogIndexToPush = 0; - self.info("Log roll interval occurred."); - }, this._logRollInterval); - } else { - this.warn("Logger is already set to the given interval: %d", this._logRollInterval); - } - }; - - /** - * Set the log level. This is the minimum level at which logs will - * be kept for later archiving. - */ - Logger.prototype.setLogLevel = function (level) { - if (level in LogLevelOrder) { - this._logLevel = LogLevelOrder[level]; - } else { - throw new Error("Unknown logging level: " + level); - } - }; - - /** - * Set the echo level. This is the minimum level at which logs will - * be printed to the javascript console. - */ - Logger.prototype.setEchoLevel = function (level) { - if (level in LogLevelOrder) { - this._echoLevel = LogLevelOrder[level]; - } else { - throw new Error("Unknown logging level: " + level); - } - }; - - /** - * Write a particular log entry. - * - * @param level The logging level of the entry. - * @param text The text contents of the entry. - * - * @returns The new log entry. - */ - Logger.prototype.write = function (component, level, text) { - var logEntry = new LogEntry(component, level, text, this.getLoggerId()); - redactSensitiveInfo(logEntry); - this.addLogEntry(logEntry); - return logEntry; - }; - Logger.prototype.addLogEntry = function (logEntry) { - // Call this second time as in some places this function is called directly - redactSensitiveInfo(logEntry); - this._logs.push(logEntry); - - //For now only send softphone logs only. - //TODO add CCP logs once we are sure that no sensitive data is being logged. - if (LogComponent.SOFTPHONE === logEntry.component) { - this._logsToPush.push(logEntry); - } - if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { - if (LogLevelOrder[logEntry.level] >= this._echoLevel) { - CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); - } - logEntry.line = this._lineCount++; - } - }; - Logger.prototype.sendInternalLogEntryToServer = function (logEntry) { - this._serverBoundInternalLogs.push(logEntry); - if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { - if (LogLevelOrder[logEntry.level] >= this._echoLevel) { - CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); - } - logEntry.line = this._lineCount++; - } - }; - - /** - * Remove all objects from all log entries. - */ - Logger.prototype.clearObjects = function () { - for (var x = 0; x < this._logs.length; x++) { - if (this._logs[x].objects) { - delete this._logs[x].objects; - } - } - }; - - /** - * Remove all exception stack traces from the log entries. - */ - Logger.prototype.clearExceptions = function () { - for (var x = 0; x < this._logs.length; x++) { - if (this._logs[x].exception) { - delete this._logs[x].exception; - } - } - }; - Logger.prototype.trace = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.TRACE, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.debug = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.DEBUG, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.info = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.INFO, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.log = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.LOG, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.test = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.TEST, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.warn = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.WARN, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.error = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); - }; - Logger.prototype.critical = function () { - var logArgs = extractLoggerArgs(arguments); - return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); - }; - - /** - * Create a string representation of the logger contents. - */ - Logger.prototype.toString = function () { - var lines = []; - for (var x = 0; x < this._logs.length; x++) { - lines.push(this._logs[x].toString()); - } - return lines.join("\n"); - }; - - /** - * Download/Archive logs to a file, - * By default, it returns all logs. - * To filter logs by the minimum log level set by setLogLevel or the default set in _logLevel, - * pass in filterByLogLevel to true in options - * - * @param options download options [Object|String]. - * - of type Object: - * { logName: 'my-log-name', - * filterByLogLevel: false, //download all logs - * } - * - of type String (for backward compatibility), the file's name - */ - Logger.prototype.download = function (options) { - var logName = 'agent-log'; - var filterByLogLevel = false; - if (_typeof(options) === 'object') { - logName = options.logName || logName; - filterByLogLevel = options.filterByLogLevel || filterByLogLevel; - } else if (typeof options === 'string') { - logName = options || logName; - } - var self = this; - var logs = this._rolledLogs.concat(this._logs); - if (filterByLogLevel) { - logs = logs.filter(function (entry) { - return LogLevelOrder[entry.level] >= self._logLevel; - }); - } - var logBlob = new global.Blob([JSON.stringify(logs, undefined, 4)], ['text/plain']); - var downloadLink = document.createElement('a'); - var logName = logName || 'agent-log'; - downloadLink.href = global.URL.createObjectURL(logBlob); - downloadLink.download = logName + '.txt'; - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); - }; - Logger.prototype.scheduleUpstreamLogPush = function (conduit) { - if (!connect.upstreamLogPushScheduled) { - connect.upstreamLogPushScheduled = true; - /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ - global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); - } - }; - Logger.prototype.reportMasterLogsUpStream = function (conduit) { - var logsToPush = this._logsToPush.slice(); - this._logsToPush = []; - connect.ifMaster(connect.MasterTopics.SEND_LOGS, function () { - if (logsToPush.length > 0) { - conduit.sendUpstream(connect.EventType.SEND_LOGS, logsToPush); - } - }); - }; - Logger.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function (conduit) { - global.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, conduit), 1000); - }; - Logger.prototype.scheduleUpstreamOuterContextCCPLogsPush = function (conduit) { - global.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, conduit), 1000); - }; - Logger.prototype.pushOuterContextCCPserverBoundLogsUpstream = function (conduit) { - if (this._serverBoundInternalLogs.length > 0) { - for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { - this._serverBoundInternalLogs[i].text = this._serverBoundInternalLogs[i].text; - } - conduit.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs); - this._serverBoundInternalLogs = []; - } - }; - Logger.prototype.pushOuterContextCCPLogsUpstream = function (conduit) { - for (var i = this._startLogIndexToPush; i < this._logs.length; i++) { - if (this._logs[i].loggerId !== this._loggerId) { - continue; - } - conduit.sendUpstream(connect.EventType.LOG, this._logs[i]); - } - this._startLogIndexToPush = this._logs.length; - }; - Logger.prototype.getLoggerId = function () { - return this._loggerId; - }; - Logger.prototype.scheduleDownstreamClientSideLogsPush = function () { - global.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), LOGS_REPORT_INTERVAL_MILLIS); - }; - Logger.prototype.pushClientSideLogsDownstream = function () { - var logs = []; - - // We do not send a request if we have less than 50 records so that we minimize the number of - // requests per second. - // 500 is the max we accept on the server. - // We chose 500 because this is the limit imposed by Firehose for a put batch request - if (this._serverBoundInternalLogs.length < 50) { - return; - } else if (this._serverBoundInternalLogs.length > 500) { - logs = this._serverBoundInternalLogs.splice(0, 500); - } else { - logs = this._serverBoundInternalLogs; - this._serverBoundInternalLogs = []; - } - connect.publishClientSideLogs(logs); - }; - var DownstreamConduitLogger = function DownstreamConduitLogger(conduit) { - Logger.call(this); - this.conduit = conduit; - global.setInterval(connect.hitch(this, this._pushLogsDownstream), DownstreamConduitLogger.LOG_PUSH_INTERVAL); - - // Disable log rolling, we will purge our own logs once they have - // been pushed downstream. - global.clearInterval(this._logRollTimer); - this._logRollTimer = null; - }; - // How frequently logs should be collected and delivered downstream. - DownstreamConduitLogger.LOG_PUSH_INTERVAL = 1000; - DownstreamConduitLogger.prototype = Object.create(Logger.prototype); - DownstreamConduitLogger.prototype.constructor = DownstreamConduitLogger; - DownstreamConduitLogger.prototype.pushLogsDownstream = function (logs) { - var self = this; - logs.forEach(function (log) { - self.conduit.sendDownstream(connect.EventType.LOG, log); - }); - }; - DownstreamConduitLogger.prototype._pushLogsDownstream = function () { - var self = this; - this._logs.forEach(function (log) { - self.conduit.sendDownstream(connect.EventType.LOG, log); - }); - this._logs = []; - for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { - this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[i]); - } - this._serverBoundInternalLogs = []; - }; - - /** - * Wrap a function with try catch block - */ - var tryCatchWrapperMethod = function tryCatchWrapperMethod(fn) { - var wrappedfunction = function wrappedfunction() { - try { - return fn.apply(this, arguments); - } catch (e) { - // Since this wraps Logger class, we can only print it in the console and eat it. - CONSOLE_LOGGER_MAP.ERROR(e); - } - }; - return wrappedfunction; - }; - /** - * This is a wrapper method to wrap each function - * in an object with try catch block. - */ - var tryCatchWrapperObject = function tryCatchWrapperObject(obj) { - for (var method in obj) { - if (typeof obj[method] === 'function') { - obj[method] = tryCatchWrapperMethod(obj[method]); - } - } - }; - - /** Create the singleton logger instance. */ - connect.rootLogger = new Logger(); - tryCatchWrapperObject(connect.rootLogger); - - /** Fetch the singleton logger instance. */ - var getLog = function getLog() { - return connect.rootLogger; - }; - connect = connect || {}; - connect.getLog = getLog; - connect.LogEntry = LogEntry; - connect.Logger = Logger; - connect.LogLevel = LogLevel; - connect.LogComponent = LogComponent; - connect.DownstreamConduitLogger = DownstreamConduitLogger; - })(); - - /***/ -}), - -/***/ 158: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - connect.ChatMediaController = function (mediaInfo, metadata) { - var logger = connect.getLog(); - var logComponent = connect.LogComponent.CHAT; - var createMediaInstance = function createMediaInstance() { - publishTelemetryEvent("Chat media controller init", mediaInfo.contactId); - logger.info(logComponent, "Chat media controller init").withObject(mediaInfo).sendInternalLogToServer(); - connect.ChatSession.setGlobalConfig({ - loggerConfig: { - logger: logger - }, - region: metadata.region - }); - - /** Could be also CUSTOMER - For now we are creating only Agent connection media object */ - var controller = connect.ChatSession.create({ - chatDetails: mediaInfo, - type: "AGENT", - websocketManager: connect.core.getWebSocketManager() - }); - trackChatConnectionStatus(controller); - return controller.connect().then(function (data) { - logger.info(logComponent, "Chat Session Successfully established for contactId %s", mediaInfo.contactId).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session Successfully established", mediaInfo.contactId); - return controller; - })["catch"](function (error) { - logger.error(logComponent, "Chat Session establishement failed for contact %s", mediaInfo.contactId).withException(error).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); - throw error; - }); - }; - var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { - connect.publishMetric({ - name: eventName, - contactId: mediaInfo.contactId, - data: data || mediaInfo - }); - }; - var trackChatConnectionStatus = function trackChatConnectionStatus(controller) { - controller.onConnectionBroken(function (data) { - logger.error(logComponent, "Chat Session connection broken").withException(data).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session connection broken", data); - }); - controller.onConnectionEstablished(function (data) { - logger.info(logComponent, "Chat Session connection established").withObject(data).sendInternalLogToServer(); - publishTelemetryEvent("Chat Session connection established", data); - }); - }; - return { - get: function get() { - return createMediaInstance(); - } - }; - }; - })(); - - /***/ -}), - -/***/ 7: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - connect.MediaFactory = function (params) { - /** controller holder */ - var mediaControllers = {}; - var toBeDestroyed = new Set(); - var logger = connect.getLog(); - var logComponent = connect.LogComponent.CHAT; - var metadata = connect.merge({}, params) || {}; - metadata.region = metadata.region || "us-west-2"; // Default it to us-west-2 - - var getMediaController = function getMediaController(connectionObj) { - var connectionId = connectionObj.getConnectionId(); - var mediaInfo = connectionObj.getMediaInfo(); - /** if we do not have the media info then just reject the request */ - if (!mediaInfo) { - logger.error(logComponent, "Media info does not exist for a media type %s", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); - return Promise.reject("Media info does not exist for this connection"); - } - if (!mediaControllers[connectionId]) { - logger.info(logComponent, "media controller of type %s init", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); - switch (connectionObj.getMediaType()) { - case connect.MediaType.CHAT: - return mediaControllers[connectionId] = new connect.ChatMediaController(connectionObj.getMediaInfo(), metadata).get(); - case connect.MediaType.SOFTPHONE: - return mediaControllers[connectionId] = new connect.SoftphoneMediaController(connectionObj.getMediaInfo()).get(); - case connect.MediaType.TASK: - return mediaControllers[connectionId] = new connect.TaskMediaController(connectionObj.getMediaInfo()).get(); - default: - logger.error(logComponent, "Unrecognized media type %s ", connectionObj.getMediaType()).sendInternalLogToServer(); - return Promise.reject(); - } - } else { - return mediaControllers[connectionId]; - } - }; - - /** Check all the active states for the connection */ - var ifConnectionActive = function ifConnectionActive(connectionObj) { - return connectionObj.isActive(); - }; - var get = function get(connectionObj) { - if (ifConnectionActive(connectionObj)) { - return getMediaController(connectionObj); - } else { - destroy(connectionObj.getConnectionId()); - return Promise.reject("Media Controller is no longer available for this connection"); - } - }; - var destroy = function destroy(connectionId) { - if (mediaControllers[connectionId] && !toBeDestroyed.has(connectionId)) { - logger.info(logComponent, "Destroying mediaController for %s", connectionId); - toBeDestroyed.add(connectionId); - mediaControllers[connectionId].then(function () { - if (typeof controller.cleanUp === "function") controller.cleanUp(); - delete mediaControllers[connectionId]; - toBeDestroyed["delete"](connectionId); - })["catch"](function () { - delete mediaControllers[connectionId]; - toBeDestroyed["delete"](connectionId); - }); - } - }; - return { - get: get, - destroy: destroy - }; - }; - })(); - - /***/ -}), - -/***/ 6: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - - // TODO move softphone implementations here - Wil do this for GA - connect.SoftphoneMediaController = function (mediaInfo) { - return { - get: function get() { - return Promise.resolve(mediaInfo); - } - }; - }; - })(); - - /***/ -}), - -/***/ 487: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Amazon Software License (the "License"). You may not use - * this file except in compliance with the License. A copy of the License is - * located at - * - * http://aws.amazon.com/asl/ - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express - * or implied. See the License for the specific language governing permissions - * and limitations under the License. - */ - - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - connect.TaskMediaController = function (mediaInfo) { - var logger = connect.getLog(); - var logComponent = connect.LogComponent.TASK; - var createMediaInstance = function createMediaInstance() { - publishTelemetryEvent("Task media controller init", mediaInfo.contactId); - logger.info(logComponent, "Task media controller init").withObject(mediaInfo); - var controller = connect.TaskSession.create({ - contactId: mediaInfo.contactId, - initialContactId: mediaInfo.initialContactId, - websocketManager: connect.core.getWebSocketManager() - }); - trackTaskConnectionStatus(controller); - return controller.connect().then(function () { - logger.info(logComponent, "Task Session Successfully established for contactId %s", mediaInfo.contactId); - publishTelemetryEvent("Task Session Successfully established", mediaInfo.contactId); - return controller; - })["catch"](function (error) { - logger.error(logComponent, "Task Session establishement failed for contact %s", mediaInfo.contactId).withException(error); - publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); - throw error; - }); - }; - var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { - connect.publishMetric({ - name: eventName, - contactId: mediaInfo.contactId, - data: data || mediaInfo - }); - }; - var trackTaskConnectionStatus = function trackTaskConnectionStatus(controller) { - controller.onConnectionBroken(function (data) { - logger.error(logComponent, "Task Session connection broken").withException(data); - publishTelemetryEvent("Task Session connection broken", data); - }); - controller.onConnectionEstablished(function (data) { - logger.info(logComponent, "Task Session connection established").withObject(data); - publishTelemetryEvent("Task Session connection established", data); - }); - }; - return { - get: function get() { - return createMediaInstance(); - } - }; - }; - })(); - - /***/ -}), - -/***/ 743: -/***/ (() => { - - function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } - function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } - function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } - function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } - function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } - /** - * Module which gets used for the Request storage access - * Exposes init, hasAccess, request and onRequest methods. - * utilizes core post message technique to communicate back to the parent which invokes the storage access - * - * @usage - Used by initCCP and customer can make use of onRequest callbacks , this will be called even before agent login - * - * Example - - * connect.storageAccess.onRequest({ - * onInit(){}, - * onDeny(){}, - * onGrant(){} - * }); - * - * There are 4 lifecycle methods in the storage access check - * - * a) Request - StreamJS would request for storage access check to the embedded Connect hosted storage access banner - * b) Init - Storage access banner inits the access check and sends back the current access state with hasAccess set to true or false - * this is the step where we show the actual RSA banner to agents and for custom use cases hidden container will be shown - * c) Grant [optional] - Executes when Agent/user accepts storage access or already given grant - * d) Deny [optional] - Executes when Agent/user deny the storage access/ - * - * In a positive flow - we should expect Request, Init, Grant and negative Request, Init, Deny - * - * Chrome Implementation of RSA API can be found here - https://github.com/cfredric/chrome-storage-access-api - */ - (function () { - var global = this || globalThis; - var connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - var requestStorageAccessPath = "/request-storage-access"; - /** - * Configurable options exposed via initCCP - * By default canRequest will be set to false to make this as a explicit opt in - */ - var defaultStorageAccessParams = { - /* Config which controls the opt out/in - we expect customers to explicitely opt in. */ - canRequest: true, - /* ["custom", "default"] - decides the rsa page view */ - mode: "default", - custom: { - /** - * Only applicable for custom type RSA page and these messages should be localized by customers - * - * title: 'Cookie Notice', - * header: 'Please provide access' - * - */ - } - }; - var storageParams = {}; - var originalCCPUrl = ""; - var rsaContainer = null; - var onGrantCallbackInvoked = false; - var requesthandlerUnsubscriber; - var storageAccessEvents = { - INIT: "storageAccess::init", - GRANTED: "storageAccess::granted", - DENIED: "storageAccess::denied", - REQUEST: "storageAccess::request" - }; - var initStorageParams = function initStorageParams() { - var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - params.custom = params.custom || {}; - storageParams = _objectSpread(_objectSpread(_objectSpread({}, defaultStorageAccessParams), params), {}, { - custom: _objectSpread(_objectSpread({}, defaultStorageAccessParams.custom), params.custom) - }); - storageParams.canRequest = !(storageParams.canRequest === "false" || storageParams.canRequest === false); - }; - var resetStorageAccessState = function resetStorageAccessState() { - storageParams = {}; - originalCCPUrl = ""; - rsaContainer = null; - }; - - /** - * Handle display none/block properties for the RTSA container, if customer have different settings like height, opacity, positions etc configured they are encouraged to use - * onRequest Callback handle to reset the same. - * */ - var getRSAContainer = function getRSAContainer() { - return { - show: function show() { - rsaContainer.style.display = "block"; - }, - hide: function hide() { - rsaContainer.style.display = "none"; - } - }; - }; - - /** - * Custom Mode will show minimalistic UI - without any Connect references or Connect headers - * This will allow fully Custom CCPs to use banner and use minimal real estate to show the storage access Content - * */ - var isCustomRequestAccessMode = function isCustomRequestAccessMode() { - return storageParams && storageParams.mode !== "default"; - }; - var isConnectDomain = function isConnectDomain(origin) { - return origin.match(/.connect.aws.a2z.com|.my.connect.aws|.awsapps.com/); - }; - - /** - * Given the URL, this method generates the prefixed connect domain request storage access URL - * @param {string} url - * @returns {string} - */ - var getRsaUrlWithprefix = function getRsaUrlWithprefix(url) { - var _URL = new URL(url), - origin = _URL.origin, - pathname = _URL.pathname; - if (origin.match(/.awsapps.com/)) { - var prefix = "connect"; - if (pathname.startsWith("/connect-gamma")) { - prefix = "connect-gamma"; - } - return "".concat(origin, "/").concat(prefix).concat(requestStorageAccessPath); - } else { - return "".concat(origin).concat(requestStorageAccessPath); - } - }; - var isLocalhost = function isLocalhost(url) { - return url.match(/^https?:\/\/localhost/); - }; - - /** - * Fetches the landat path for request storage access page to navigate. This is typically CCP path or channel view - * @returns {string} - */ - var getlandAtPath = function getlandAtPath() { - if (!originalCCPUrl) { - throw new Error("[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first"); - } - if (isConnectDomain(originalCCPUrl) || isLocalhost(originalCCPUrl)) { - var _URL2 = new URL(originalCCPUrl), - pathname = _URL2.pathname; - return pathname; - } - return "/connect/ccp-v2"; - }; - - /** - * - * Method which returns the relative request-storage-access page path. - * Validates against localhost and connect domains and returns prefixed path - * @returns {string} - */ - var getRequestStorageAccessUrl = function getRequestStorageAccessUrl() { - // ccpUrl may contain non standard direct SSO URLs in which case we may ask customers to provide instanceUrl as part of storage access params - - if (!originalCCPUrl) { - throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first"); - } - if (isConnectDomain(originalCCPUrl)) { - return getRsaUrlWithprefix(originalCCPUrl); - } else if (isLocalhost(originalCCPUrl)) { - connect.getLog().info("[StorageAccess] [CCP] Local testing"); - return "".concat(originalCCPUrl).concat(requestStorageAccessPath); - } else if (storageParams.instanceUrl && isConnectDomain(storageParams.instanceUrl)) { - connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(storageParams.instanceUrl)); - return getRsaUrlWithprefix(storageParams.instanceUrl); - } else if (storageParams.instanceUrl && isLocalhost(storageParams.instanceUrl)) { - connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"); - return "".concat(storageParams.instanceUrl).concat(requestStorageAccessPath); - } else { - connect.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"); - // FIXME - For test cases to succeed passing original parameter back instead throw an error by fixing all the CCP URL parameters accross the tests. - throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL"); - } - }; - - /** - * Method which allows customers to listen on Storage access request and it's state changes - * @param {Object} consists of callbacks for the onInit, onDeny and onGrants - */ - var onRequestHandler = function onRequestHandler(_ref) { - var onInit = _ref.onInit, - onDeny = _ref.onDeny, - onGrant = _ref.onGrant; - function handleUpstreamMessages(_ref2) { - var data = _ref2.data, - source = _ref2.source; - var iframeContainer = connect.core._getCCPIframe(); - if (iframeContainer.contentWindow !== source) { - // disabling the logs for now - // connect.getLog().error('[StorageAccess][onRequestHandler] Request Coming from unknown domain %s', origin); - return false; - } - if (connect.core.initialized) { - window.removeEventListener("message", handleUpstreamMessages); - } - switch (data.event) { - case storageAccessEvents.INIT: - { - connect.getLog().info("[StorageAccess][INIT] message recieved").withObject(data); - if (onInit) { - onInit(data); - } - break; - } - case storageAccessEvents.GRANTED: - { - connect.getLog().info("[StorageAccess][GRANTED] message recieved").withObject(data); - if (onGrant) { - onGrant(data); - } - break; - } - case storageAccessEvents.DENIED: - { - connect.getLog().info("[StorageAccess][DENIED] message recieved").withObject(data); - if (onDeny) { - onDeny(data); - } - break; - } - default: - { - // Make sure to clean up the handler as soon as the access is granted. - if (connect.core.initialized) { - window.removeEventListener("message", handleUpstreamMessages); - } - break; - } - } - } - // do this only if canRequest is set to true - if (storageParams.canRequest) { - window.addEventListener("message", handleUpstreamMessages); - } - return { - unsubscribe: function unsubscribe() { - window.removeEventListener("message", handleUpstreamMessages); - } - }; - }; - - /** - * setupRequestHandlers - method which attaches post message handlers and let the initCCP flow to continue. - * In case of custom CCPs - it also does hide/show the container. - * @param {*} param0 - */ - var setupRequestHandlers = function setupRequestHandlers(_ref3) { - var onGrantCallback = _ref3.onGrant; - if (requesthandlerUnsubscriber) { - requesthandlerUnsubscriber.unsubscribe(); - } - requesthandlerUnsubscriber = onRequestHandler({ - onInit: function onInit(messageData) { - console.log("%c[INIT]", "background:lime; color: black; font-size:large"); - connect.getLog().info("[StorageAccess][onInit] callback executed").withObject(messageData === null || messageData === void 0 ? void 0 : messageData.data); - if (!(messageData !== null && messageData !== void 0 && messageData.data.hasAccess) && isCustomRequestAccessMode()) { - getRSAContainer().show(); - } - }, - onDeny: function onDeny() { - console.log("%c[DENIED]", "background:lime; color: black; font-size:large"); - connect.getLog().info("[StorageAccess][onDeny] callback executed"); - if (isCustomRequestAccessMode()) { - getRSAContainer().show(); - } - }, - onGrant: function onGrant() { - console.log("%c[Granted]", "background:lime; color: black; font-size:large"); - connect.getLog().info("[StorageAccess][onGrant] callback executed"); - if (isCustomRequestAccessMode()) { - getRSAContainer().hide(); - } - // Invoke onGrantCallback only once as it setsup initCCP callbacks and events - if (!onGrantCallbackInvoked) { - onGrantCallback(); - onGrantCallbackInvoked = true; - } - } - }); - }; - connect.storageAccess = Object.freeze({ - /** - * Checks wther user has opted out for storage Access checks or not - * @returns {boolean} - */ - canRequest: function canRequest() { - return storageParams.canRequest; - }, - /** - * Mainly used by Tests, by default storage access is enabled for all - */ - optOutFromRequestAccess: function optOutFromRequestAccess() { - defaultStorageAccessParams.canRequest = false; - }, - /** - * Mainly used by Tests - */ - optInForRequestAccess: function optInForRequestAccess() { - defaultStorageAccessParams.canRequest = true; - }, - /** - * Method which inits the Storage Access module with Customer paramters. - * and generates request storage access URL and apply customization to the default paramters - * @param {*} params - storage access params - * @param {*} container - Container where CCP is being shown - * @returns {{canRequest, requestAccessPageurl}} - */ - init: function init(ccpUrl, containerDiv) { - var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - connect.assertNotNull(ccpUrl, "ccpUrl"); - connect.assertNotNull(containerDiv, "container"); - rsaContainer = containerDiv; - originalCCPUrl = ccpUrl; - initStorageParams(params); - connect.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(ccpUrl, " - ").concat(!storageParams.canRequest ? "user has opted out, skipping request storage access" : "Proceeding with requesting storage access")).withObject(storageParams); - }, - setupRequestHandlers: setupRequestHandlers, - getRequestStorageAccessUrl: getRequestStorageAccessUrl, - storageAccessEvents: storageAccessEvents, - resetStorageAccessState: resetStorageAccessState, - getStorageAccessParams: function getStorageAccessParams() { - return storageParams; - }, - onRequest: onRequestHandler, - request: function request() { - var iframeContainer = connect.core._getCCPIframe(); - iframeContainer.contentWindow.postMessage({ - event: storageAccessEvents.REQUEST, - data: _objectSpread(_objectSpread({}, storageParams), {}, { - landat: getlandAtPath() - }) - }, "*"); - } - }); - })(); - - /***/ -}), - -/***/ 555: -/***/ (() => { - - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - var connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - var RingtoneEngineBase = function RingtoneEngineBase(ringtoneConfig) { - var self = this; - this._prevContactId = null; - connect.assertNotNull(ringtoneConfig, "ringtoneConfig"); - if (!ringtoneConfig.ringtoneUrl) { - throw new Error("ringtoneUrl is required!"); - } - if (global.Audio && typeof global.Promise !== "undefined") { - this._playableAudioPromise = new Promise(function (resolve, reject) { - self._audio = new Audio(ringtoneConfig.ringtoneUrl); - self._audio.loop = true; - self._audio.addEventListener("canplay", function () { - self._audioPlayable = true; - resolve(self._audio); - }); - }); - } else { - this._audio = null; - connect.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer(); - } - self._driveRingtone(); - }; - RingtoneEngineBase.prototype._driveRingtone = function () { - throw new Error("Not implemented."); - }; - RingtoneEngineBase.prototype._startRingtone = function (contact) { - if (this._audio) { - this._audio.play()["catch"](function (e) { - this._publishTelemetryEvent("Ringtone Playback Failure", contact); - connect.getLog().error("Ringtone Playback Failure").sendInternalLogToServer(); - }); - this._publishTelemetryEvent("Ringtone Start", contact); - connect.getLog().info("Ringtone Start").sendInternalLogToServer(); - } - }; - RingtoneEngineBase.prototype._stopRingtone = function (contact) { - if (this._audio) { - this._audio.pause(); - this._audio.currentTime = 0; - this._publishTelemetryEvent("Ringtone Stop", contact); - connect.getLog().info("Ringtone Stop").sendInternalLogToServer(); - } - }; - - /** - * Stop ringtone. - */ - RingtoneEngineBase.prototype.stopRingtone = function () { - this._stopRingtone(); - }; - RingtoneEngineBase.prototype._ringtoneSetup = function (contact) { - var self = this; - connect.ifMaster(connect.MasterTopics.RINGTONE, function () { - self._startRingtone(contact); - self._prevContactId = contact.getContactId(); - contact.onConnected(lily.hitch(self, self._stopRingtone)); - contact.onAccepted(lily.hitch(self, self._stopRingtone)); - contact.onEnded(lily.hitch(self, self._stopRingtone)); - // Just to make sure to stop the ringtone in case of the failures of specific callbacks(onAccepted,onConnected); - contact.onRefresh(function (contact) { - if (contact.getStatus().type !== connect.ContactStatusType.CONNECTING && contact.getStatus().type !== connect.ContactStatusType.INCOMING) { - self._stopRingtone(); - } - }); - }); - }; - RingtoneEngineBase.prototype._publishTelemetryEvent = function (eventName, contact) { - if (contact && contact.getContactId()) { - connect.publishMetric({ - name: eventName, - contactId: contact.getContactId() - }); - } - }; - - /** - * Change the audio device used to play ringtone. - * If audio element is not fully initialized, the API will wait _audioPlayablePromise for 3 seconds and fail on timeout. - * This API is supported only by browsers that implemented ES6 Promise and http://www.w3.org/TR/audio-output/ - * Return a Promise that indicates the result of changing output device. - */ - RingtoneEngineBase.prototype.setOutputDevice = function (deviceId) { - if (this._playableAudioPromise) { - var playableAudioWithTimeout = Promise.race([this._playableAudioPromise, new Promise(function (resolve, reject) { - global.setTimeout(function () { - reject("Timed out waiting for playable audio"); - }, 3000 /*ms*/); - })]); - - return playableAudioWithTimeout.then(function (audio) { - if (audio) { - if (audio.setSinkId) { - return Promise.resolve(audio.setSinkId(deviceId)); - } else { - return Promise.reject("Not supported"); - } - } else { - return Promise.reject("No audio found"); - } - }); - } - if (global.Promise) { - return Promise.reject("Not eligible ringtone owner"); - } - }; - var VoiceRingtoneEngine = function VoiceRingtoneEngine(ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); - }; - VoiceRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - VoiceRingtoneEngine.prototype.constructor = VoiceRingtoneEngine; - VoiceRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - var onContactConnect = function onContactConnect(contact) { - if (contact.getType() === lily.ContactType.VOICE && contact.isSoftphoneCall() && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Ringtone Connecting", contact); - connect.getLog().info("Ringtone Connecting").sendInternalLogToServer(); - } - }; - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); - new connect.Agent().getContacts().forEach(function (contact) { - if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { - onContactConnect(contact); - } - }); - }; - var ChatRingtoneEngine = function ChatRingtoneEngine(ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); - }; - ChatRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - ChatRingtoneEngine.prototype.constructor = ChatRingtoneEngine; - ChatRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - var onContactConnect = function onContactConnect(contact) { - if (contact.getType() === lily.ContactType.CHAT && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Chat Ringtone Connecting", contact); - connect.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer(); - } - }; - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); - }; - var TaskRingtoneEngine = function TaskRingtoneEngine(ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); - }; - TaskRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - TaskRingtoneEngine.prototype.constructor = TaskRingtoneEngine; - TaskRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - var onContactConnect = function onContactConnect(contact) { - if (contact.getType() === lily.ContactType.TASK && contact.isInbound()) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Task Ringtone Connecting", contact); - connect.getLog().info("Task Ringtone Connecting").sendInternalLogToServer(); - } - }; - connect.contact(function (contact) { - contact.onConnecting(onContactConnect); - }); - }; - var QueueCallbackRingtoneEngine = function QueueCallbackRingtoneEngine(ringtoneConfig) { - RingtoneEngineBase.call(this, ringtoneConfig); - }; - QueueCallbackRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); - QueueCallbackRingtoneEngine.prototype.constructor = QueueCallbackRingtoneEngine; - QueueCallbackRingtoneEngine.prototype._driveRingtone = function () { - var self = this; - connect.contact(function (contact) { - contact.onIncoming(function () { - if (contact.getType() === lily.ContactType.QUEUE_CALLBACK) { - self._ringtoneSetup(contact); - self._publishTelemetryEvent("Callback Ringtone Connecting", contact); - connect.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer(); - } - }); - }); - }; - - /* export connect.RingtoneEngine */ - connect.VoiceRingtoneEngine = VoiceRingtoneEngine; - connect.ChatRingtoneEngine = ChatRingtoneEngine; - connect.TaskRingtoneEngine = TaskRingtoneEngine; - connect.QueueCallbackRingtoneEngine = QueueCallbackRingtoneEngine; - })(); - - /***/ -}), - -/***/ 960: -/***/ (() => { - - function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - global.ccpVersion = "V2"; - var RTPJobIntervalMs = 1000; - var statsReportingJobIntervalMs = 30000; - var streamBufferSize = 500; - var CallTypeMap = {}; - CallTypeMap[connect.SoftphoneCallType.AUDIO_ONLY] = 'Audio'; - CallTypeMap[connect.SoftphoneCallType.VIDEO_ONLY] = 'Video'; - CallTypeMap[connect.SoftphoneCallType.AUDIO_VIDEO] = 'AudioVideo'; - CallTypeMap[connect.SoftphoneCallType.NONE] = 'None'; - var AUDIO_INPUT = 'audio_input'; - var AUDIO_OUTPUT = 'audio_output'; - var MediaTypeMap = {}; - MediaTypeMap[connect.ContactType.VOICE] = "Voice"; - var UNKNOWN_MEDIA_TYPE = "Unknown"; - var timeSeriesStreamStatsBuffer = []; - var aggregatedUserAudioStats = {}; - var aggregatedRemoteAudioStats = {}; - var rtpStatsJob = null; - var reportStatsJob = null; - //Logger specific to softphone. - var logger = null; - var SoftphoneErrorTypes = connect.SoftphoneErrorTypes; - var HANG_UP_MULTIPLE_SESSIONS_EVENT = "MultiSessionHangUp"; - var MULTIPLE_SESSIONS_EVENT = "MultiSessions"; - var localMediaStream = {}; - var softphoneClientId = connect.randomId(); - var requestIceAccess = function requestIceAccess(transport) { - return new Promise(function (resolve, reject) { - connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, transport, { - success: function success(data) { - resolve(data.softphoneTransport.softphoneMediaConnections); - }, - failure: function failure(reason) { - if (reason.message && reason.message.includes("SoftphoneConnectionLimitBreachedException")) { - publishError("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""); - } - reject(Error("requestIceAccess failed")); - }, - authFailure: function authFailure() { - reject(Error("Authentication failed while requestIceAccess")); - }, - accessDenied: function accessDenied() { - reject(Error("Access Denied while requestIceAccess")); - } - }); - }); - }; - var SoftphoneManager = function SoftphoneManager(softphoneParams) { - var self = this; - logger = new SoftphoneLogger(connect.getLog()); - logger.info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(); - var rtcPeerConnectionFactory; - if (connect.RtcPeerConnectionFactory) { - rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, connect.core.getWebSocketManager(), softphoneClientId, connect.hitch(self, requestIceAccess, { - transportType: "softphone", - softphoneClientId: softphoneClientId - }), connect.hitch(self, publishError)); - } - if (!isBrowserSoftPhoneSupported()) { - publishError(SoftphoneErrorTypes.UNSUPPORTED_BROWSER, "Connect does not support this browser. Some functionality may not work. ", ""); - } - var gumPromise = fetchUserMedia({ - success: function success(stream) { - connect.core.setSoftphoneUserMediaStream(stream); - }, - failure: function failure(err) { - publishError(err, "Your microphone is not enabled in your browser. ", ""); - } - }); - handleSoftPhoneMuteToggle(); - handleSpeakerDeviceChange(); - handleMicrophoneDeviceChange(); - this.ringtoneEngine = null; - var rtcSessions = {}; - // Tracks the agent connection ID, so that if the same contact gets re-routed to the same agent, it'll still set up softphone - var callsDetected = {}; - this.onInitContactSub = {}; - this.onInitContactSub.unsubscribe = function () { }; - - // variables for firefox multitab - var isSessionPending = false; - var pendingContact = null; - var pendingAgentConnectionId = null; - var postponeStartingSession = function postponeStartingSession(contact, agentConnectionId) { - isSessionPending = true; - pendingContact = contact; - pendingAgentConnectionId = agentConnectionId; - }; - var cancelPendingSession = function cancelPendingSession() { - isSessionPending = false; - pendingContact = null; - pendingAgentConnectionId = null; - }; - - // helper method to provide access to rtc sessions - this.getSession = function (connectionId) { - return rtcSessions[connectionId]; - }; - this.replaceLocalMediaTrack = function (connectionId, track) { - var stream = localMediaStream[connectionId].stream; - if (stream) { - var oldTrack = stream.getAudioTracks()[0]; - track.enabled = oldTrack.enabled; - oldTrack.enabled = false; - stream.removeTrack(oldTrack); - stream.addTrack(track); - } - }; - var isContactTerminated = function isContactTerminated(contact) { - return contact.getStatus().type === connect.ContactStatusType.ENDED || contact.getStatus().type === connect.ContactStatusType.ERROR || contact.getStatus().type === connect.ContactStatusType.MISSED; - }; - var destroySession = function destroySession(agentConnectionId) { - if (rtcSessions.hasOwnProperty(agentConnectionId)) { - var session = rtcSessions[agentConnectionId]; - // Currently the assumption is it will throw an exception only and if only it already has been hung up. - // TODO: Update once the hangup API does not throw exceptions - new Promise(function (resolve, reject) { - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - session.hangup(); - })["catch"](function (err) { - lily.getLog().warn("Clean up the session locally " + agentConnectionId, err.message).sendInternalLogToServer(); - }); - } - }; - - // When multiple RTC sessions detected, ignore the new call and hang up the previous sessions. - // TODO: Update when connect-rtc exposes an API to detect session status. - var sanityCheckActiveSessions = function sanityCheckActiveSessions(rtcSessions) { - if (Object.keys(rtcSessions).length > 0) { - // Error! our state doesn't match, tear it all down. - for (var connectionId in rtcSessions) { - if (rtcSessions.hasOwnProperty(connectionId)) { - // Log an error for the session we are about to end. - publishMultipleSessionsEvent(HANG_UP_MULTIPLE_SESSIONS_EVENT, rtcSessions[connectionId].callId, connectionId); - destroySession(connectionId); - } - } - throw new Error("duplicate session detected, refusing to setup new connection"); - } - }; - this.startSession = function (_contact, _agentConnectionId) { - var contact = isSessionPending ? pendingContact : _contact; - var agentConnectionId = isSessionPending ? pendingAgentConnectionId : _agentConnectionId; - if (!contact || !agentConnectionId) { - return; - } - cancelPendingSession(); - - // Set to true, this will block subsequent invokes from entering. - callsDetected[agentConnectionId] = true; - logger.info("Softphone call detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); - - // Ensure our session state matches our contact state to prevent issues should we lose track of a contact. - sanityCheckActiveSessions(rtcSessions); - if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { - publishTelemetryEvent("Softphone Connecting", contact.getContactId()); - } - initializeParams(); - var softphoneInfo = contact.getAgentConnection().getSoftphoneMediaInfo(); - var callConfig = parseCallConfig(softphoneInfo.callConfigJson); - var webSocketProvider; - if (callConfig.useWebSocketProvider) { - webSocketProvider = connect.core.getWebSocketManager(); - } - var session = new connect.RTCSession(callConfig.signalingEndpoint, callConfig.iceServers, softphoneInfo.callContextToken, logger, contact.getContactId(), agentConnectionId, webSocketProvider); - rtcSessions[agentConnectionId] = session; - if (connect.core.getSoftphoneUserMediaStream()) { - session.mediaStream = connect.core.getSoftphoneUserMediaStream(); - } - - // Custom Event to indicate the session init operations - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConnectionEvents.SESSION_INIT, - data: { - connectionId: agentConnectionId - } - }); - session.onSessionFailed = function (rtcSession, reason) { - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - publishSoftphoneFailureLogs(rtcSession, reason); - publishSessionFailureTelemetryEvent(contact.getContactId(), reason); - stopJobsAndReport(contact, rtcSession.sessionReport); - }; - session.onSessionConnected = function (rtcSession) { - publishTelemetryEvent("Softphone Session Connected", contact.getContactId()); - // Become master to send logs, since we need logs from softphone tab. - connect.becomeMaster(connect.MasterTopics.SEND_LOGS); - //start stats collection and reporting jobs - startStatsCollectionJob(rtcSession); - startStatsReportingJob(contact); - fireContactAcceptedEvent(contact); - }; - session.onSessionCompleted = function (rtcSession) { - publishTelemetryEvent("Softphone Session Completed", contact.getContactId()); - delete rtcSessions[agentConnectionId]; - delete callsDetected[agentConnectionId]; - // Stop all jobs and perform one last job. - stopJobsAndReport(contact, rtcSession.sessionReport); - - // Cleanup the cached streams - deleteLocalMediaStream(agentConnectionId); - }; - session.onLocalStreamAdded = function (rtcSession, stream) { - // Cache the streams for mute/unmute - localMediaStream[agentConnectionId] = { - stream: stream - }; - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, - data: { - connectionId: agentConnectionId - } - }); - }; - session.remoteAudioElement = document.getElementById('remote-audio'); - if (rtcPeerConnectionFactory) { - session.connect(rtcPeerConnectionFactory.get(callConfig.iceServers)); - } else { - session.connect(); - } - }; - var onRefreshContact = function onRefreshContact(contact, agentConnectionId) { - if (rtcSessions[agentConnectionId] && isContactTerminated(contact)) { - destroySession(agentConnectionId); - cancelPendingSession(); - } - if (contact.isSoftphoneCall() && !callsDetected[agentConnectionId] && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { - if (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs()) { - postponeStartingSession(contact, agentConnectionId); - } else { - self.startSession(contact, agentConnectionId); - } - } - }; - var onInitContact = function onInitContact(contact) { - var agentConnectionId = contact.getAgentConnection().connectionId; - logger.info("Contact detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); - if (!callsDetected[agentConnectionId]) { - contact.onRefresh(function () { - onRefreshContact(contact, agentConnectionId); - }); - } - }; - self.onInitContactSub = connect.contact(onInitContact); - - // Contact already in connecting state scenario - In this case contact INIT is missed hence the OnRefresh callback is missed. - new connect.Agent().getContacts().forEach(function (contact) { - var agentConnectionId = contact.getAgentConnection().connectionId; - logger.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); - onInitContact(contact); - onRefreshContact(contact, agentConnectionId); - }); - }; - var fireContactAcceptedEvent = function fireContactAcceptedEvent(contact) { - var conduit = connect.core.getUpstream(); - var agentConnection = contact.getAgentConnection(); - if (!agentConnection) { - logger.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer(); - return; - } - var softphoneMediaInfo = agentConnection.getSoftphoneMediaInfo(); - if (!softphoneMediaInfo) { - logger.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer(); - return; - } - if (softphoneMediaInfo.autoAccept === true) { - logger.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.ContactEvents.ACCEPTED, - data: new connect.Contact(contact.contactId) - }); - conduit.sendUpstream(connect.EventType.BROADCAST, { - event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, contact.contactId), - data: new connect.Contact(contact.contactId) - }); - } else { - logger.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer(); - } - }; - - // Bind events for mute - var handleSoftPhoneMuteToggle = function handleSoftPhoneMuteToggle() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.EventType.MUTE, muteToggle); - }; - var handleSpeakerDeviceChange = function handleSpeakerDeviceChange() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, setSpeakerDevice); - }; - var handleMicrophoneDeviceChange = function handleMicrophoneDeviceChange() { - var bus = connect.core.getEventBus(); - bus.subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, setMicrophoneDevice); - }; - - // Make sure once we disconnected we get the mute state back to normal - var deleteLocalMediaStream = function deleteLocalMediaStream(connectionId) { - delete localMediaStream[connectionId]; - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.MUTE_TOGGLE, - data: { - muted: false - } - }); - }; - - // Check for the local streams if exists - revert it - // And inform other clients about the change - var muteToggle = function muteToggle(data) { - var status; - if (connect.keys(localMediaStream).length === 0) { - return; - } - if (data && data.mute !== undefined) { - status = data.mute; - } - for (var connectionId in localMediaStream) { - if (localMediaStream.hasOwnProperty(connectionId)) { - var localMedia = localMediaStream[connectionId].stream; - if (localMedia) { - var audioTracks = localMedia.getAudioTracks()[0]; - if (status !== undefined) { - audioTracks.enabled = !status; - localMediaStream[connectionId].muted = status; - if (status) { - logger.info("Agent has muted the contact, connectionId - " + connectionId).sendInternalLogToServer(); - } else { - logger.info("Agent has unmuted the contact, connectionId - " + connectionId).sendInternalLogToServer(); - } - } else { - status = localMediaStream[connectionId].muted || false; - } - } - } - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.MUTE_TOGGLE, - data: { - muted: status - } - }); - }; - var setSpeakerDevice = function setSpeakerDevice(data) { - if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { - return; - } - var deviceId = data.deviceId; - var remoteAudioElement = document.getElementById('remote-audio'); - try { - logger.info("Trying to set speaker to device " + deviceId); - if (remoteAudioElement && typeof remoteAudioElement.setSinkId === 'function') { - remoteAudioElement.setSinkId(deviceId); - } - } catch (e) { - logger.error("Failed to set speaker to device " + deviceId); - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, - data: { - deviceId: deviceId - } - }); - }; - var setMicrophoneDevice = function setMicrophoneDevice(data) { - if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { - return; - } - var deviceId = data.deviceId; - var softphoneManager = connect.core.getSoftphoneManager(); - try { - navigator.mediaDevices.getUserMedia({ - audio: { - deviceId: { - exact: deviceId - } - } - }).then(function (newMicrophoneStream) { - var newMicrophoneTrack = newMicrophoneStream.getAudioTracks()[0]; - for (var connectionId in localMediaStream) { - if (localMediaStream.hasOwnProperty(connectionId)) { - var localMedia = localMediaStream[connectionId].stream; - var session = softphoneManager.getSession(connectionId); - //Replace the audio track in the RtcPeerConnection - session._pc.getSenders()[0].replaceTrack(newMicrophoneTrack).then(function () { - //Replace the audio track in the local media stream (for mute / unmute) - softphoneManager.replaceLocalMediaTrack(connectionId, newMicrophoneTrack); - }); - } - } - }); - } catch (e) { - logger.error("Failed to set microphone device " + deviceId); - } - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, - data: { - deviceId: deviceId - } - }); - }; - var publishSoftphoneFailureLogs = function publishSoftphoneFailureLogs(rtcSession, reason) { - if (reason === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { - var endPointUrl = "\n"; - for (var i = 0; i < rtcSession._iceServers.length; i++) { - for (var j = 0; j < rtcSession._iceServers[i].urls.length; j++) { - endPointUrl = endPointUrl + rtcSession._iceServers[i].urls[j] + "\n"; - } - } - publishError(SoftphoneErrorTypes.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", endPointUrl); - } else if (reason === connect.RTCErrors.USER_BUSY) { - publishError(SoftphoneErrorTypes.USER_BUSY_ERROR, "Softphone call UserBusy error. ", ""); - } else if (reason === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE) { - publishError(SoftphoneErrorTypes.SIGNALLING_HANDSHAKE_FAILURE, "Handshaking with Signalling Server " + rtcSession._signalingUri + " failed. ", rtcSession._signalingUri); - } else if (reason === connect.RTCErrors.GUM_TIMEOUT_FAILURE || reason === connect.RTCErrors.GUM_OTHER_FAILURE) { - publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", ""); - } else if (reason === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE) { - publishError(SoftphoneErrorTypes.SIGNALLING_CONNECTION_FAILURE, "URL " + rtcSession._signalingUri + " cannot be reached. ", rtcSession._signalingUri); - } else if (reason === connect.RTCErrors.CALL_NOT_FOUND) { - // No need to publish any softphone error for this case. CCP UX will handle this case. - logger.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer(); - } else { - publishError(SoftphoneErrorTypes.WEBRTC_ERROR, "webrtc system error. ", ""); - } - }; - - /** Parse the JSON encoded web call config into the data it represents. */ - var parseCallConfig = function parseCallConfig(serializedConfig) { - // Our underscore is too old for unescape - // https://issues.amazon.com/issues/CSWF-1467 - var decodedJSON = serializedConfig.replace(/"/g, '"'); - return JSON.parse(decodedJSON); - }; - var fetchUserMedia = function fetchUserMedia(callbacksIn) { - var callbacks = callbacksIn || {}; - callbacks.success = callbacks.success || function () { }; - callbacks.failure = callbacks.failure || function () { }; - var CONSTRAINT = { - audio: true - }; - var promise = null; - if (typeof Promise !== "function") { - callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); - return; - } - if (_typeof(navigator.mediaDevices) === "object" && typeof navigator.mediaDevices.getUserMedia === "function") { - promise = navigator.mediaDevices.getUserMedia(CONSTRAINT); - } else if (typeof navigator.webkitGetUserMedia === "function") { - promise = new Promise(function (resolve, reject) { - navigator.webkitGetUserMedia(CONSTRAINT, resolve, reject); - }); - } else { - callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); - return; - } - promise.then(function (stream) { - var audioTracks = stream.getAudioTracks(); - if (audioTracks && audioTracks.length > 0) { - callbacks.success(stream); - } else { - callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); - } - }, function (err) { - callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); - }); - return promise; - }; - var publishError = function publishError(errorType, message, endPointUrl) { - logger.error("Softphone error occurred : ", errorType, message || "").sendInternalLogToServer(); - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.AgentEvents.SOFTPHONE_ERROR, - data: new connect.SoftphoneError(errorType, message, endPointUrl) - }); - }; - var publishSessionFailureTelemetryEvent = function publishSessionFailureTelemetryEvent(contactId, reason) { - publishTelemetryEvent("Softphone Session Failed", contactId, { - failedReason: reason - }); - }; - var publishTelemetryEvent = function publishTelemetryEvent(eventName, contactId, data) { - if (contactId) { - connect.publishMetric({ - name: eventName, - contactId: contactId, - data: data - }); - } - }; - - // Publish the contact and agent information in a multiple sessions scenarios - var publishMultipleSessionsEvent = function publishMultipleSessionsEvent(eventName, contactId, agentConnectionId) { - publishTelemetryEvent(eventName, contactId, [{ - name: "AgentConnectionId", - value: agentConnectionId - }]); - logger.info("Publish multiple session error metrics", eventName, "contactId " + contactId, "agent connectionId " + agentConnectionId).sendInternalLogToServer(); - }; - var isBrowserSoftPhoneSupported = function isBrowserSoftPhoneSupported() { - // In Opera, the true version is after "Opera" or after "Version" - if (connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) { - return true; - } - // In Chrome, the true version is after "Chrome" - else if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) { - return true; - } - // In Firefox, the true version is after "Firefox" - else if (connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) { - return true; - } else { - return false; - } - }; - var sendSoftphoneMetrics = function sendSoftphoneMetrics(contact) { - var streamStats = timeSeriesStreamStatsBuffer.slice(); - timeSeriesStreamStatsBuffer = []; - if (streamStats.length > 0) { - contact.sendSoftphoneMetrics(streamStats, { - success: function success() { - logger.info("sendSoftphoneMetrics success" + JSON.stringify(streamStats)).sendInternalLogToServer(); - }, - failure: function failure(data) { - logger.error("sendSoftphoneMetrics failed.").withObject(data).sendInternalLogToServer(); - } - }); - } - }; - var sendSoftphoneReport = function sendSoftphoneReport(contact, report, userAudioStats, remoteAudioStats) { - report.streamStats = [addStreamTypeToStats(userAudioStats, AUDIO_INPUT), addStreamTypeToStats(remoteAudioStats, AUDIO_OUTPUT)]; - var callReport = { - callStartTime: report.sessionStartTime, - callEndTime: report.sessionEndTime, - gumTimeMillis: report.gumTimeMillis, - initializationTimeMillis: report.initializationTimeMillis, - iceCollectionTimeMillis: report.iceCollectionTimeMillis, - signallingConnectTimeMillis: report.signallingConnectTimeMillis, - handshakingTimeMillis: report.handshakingTimeMillis, - preTalkingTimeMillis: report.preTalkingTimeMillis, - talkingTimeMillis: report.talkingTimeMillis, - cleanupTimeMillis: report.cleanupTimeMillis, - iceCollectionFailure: report.iceCollectionFailure, - signallingConnectionFailure: report.signallingConnectionFailure, - handshakingFailure: report.handshakingFailure, - gumOtherFailure: report.gumOtherFailure, - gumTimeoutFailure: report.gumTimeoutFailure, - createOfferFailure: report.createOfferFailure, - setLocalDescriptionFailure: report.setLocalDescriptionFailure, - userBusyFailure: report.userBusyFailure, - invalidRemoteSDPFailure: report.invalidRemoteSDPFailure, - noRemoteIceCandidateFailure: report.noRemoteIceCandidateFailure, - setRemoteDescriptionFailure: report.setRemoteDescriptionFailure, - softphoneStreamStatistics: report.streamStats - }; - contact.sendSoftphoneReport(callReport, { - success: function success() { - logger.info("sendSoftphoneReport success" + JSON.stringify(callReport)).sendInternalLogToServer(); - }, - failure: function failure(data) { - logger.error("sendSoftphoneReport failed.").withObject(data).sendInternalLogToServer(); - } - }); - }; - var startStatsCollectionJob = function startStatsCollectionJob(rtcSession) { - rtpStatsJob = window.setInterval(function () { - rtcSession.getUserAudioStats().then(function (stats) { - var previousUserStats = aggregatedUserAudioStats; - aggregatedUserAudioStats = stats; - timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedUserAudioStats, previousUserStats, AUDIO_INPUT)); - }, function (error) { - logger.debug("Failed to get user audio stats.", error).sendInternalLogToServer(); - }); - rtcSession.getRemoteAudioStats().then(function (stats) { - var previousRemoteStats = aggregatedRemoteAudioStats; - aggregatedRemoteAudioStats = stats; - timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedRemoteAudioStats, previousRemoteStats, AUDIO_OUTPUT)); - }, function (error) { - logger.debug("Failed to get remote audio stats.", error).sendInternalLogToServer(); - }); - }, 1000); - }; - var startStatsReportingJob = function startStatsReportingJob(contact) { - reportStatsJob = window.setInterval(function () { - sendSoftphoneMetrics(contact); - }, statsReportingJobIntervalMs); - }; - var initializeParams = function initializeParams() { - aggregatedUserAudioStats = null; - aggregatedRemoteAudioStats = null; - timeSeriesStreamStatsBuffer = []; - rtpStatsJob = null; - reportStatsJob = null; - }; - var getTimeSeriesStats = function getTimeSeriesStats(currentStats, previousStats, streamType) { - if (previousStats && currentStats) { - var packetsLost = currentStats.packetsLost > previousStats.packetsLost ? currentStats.packetsLost - previousStats.packetsLost : 0; - var packetsCount = currentStats.packetsCount > previousStats.packetsCount ? currentStats.packetsCount - previousStats.packetsCount : 0; - return new RTPStreamStats(currentStats.timestamp, packetsLost, packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); - } else { - return new RTPStreamStats(currentStats.timestamp, currentStats.packetsLost, currentStats.packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); - } - }; - var stopJob = function stopJob(task) { - if (task !== null) { - window.clearInterval(task); - } - return null; - }; - var stopJobsAndReport = function stopJobsAndReport(contact, sessionReport) { - rtpStatsJob = stopJob(rtpStatsJob); - reportStatsJob = stopJob(reportStatsJob); - sendSoftphoneReport(contact, sessionReport, addStreamTypeToStats(aggregatedUserAudioStats, AUDIO_INPUT), addStreamTypeToStats(aggregatedRemoteAudioStats, AUDIO_OUTPUT)); - sendSoftphoneMetrics(contact); - }; - - /** - * Adding streamtype parameter on top of RTCJS RTStats object. - */ - var RTPStreamStats = function RTPStreamStats(timestamp, packetsLost, packetsCount, streamType, audioLevel, jitterBufferMillis, roundTripTimeMillis) { - this.softphoneStreamType = streamType; - this.timestamp = timestamp; - this.packetsLost = packetsLost; - this.packetsCount = packetsCount; - this.audioLevel = audioLevel; - this.jitterBufferMillis = jitterBufferMillis; - this.roundTripTimeMillis = roundTripTimeMillis; - }; - var addStreamTypeToStats = function addStreamTypeToStats(stats, streamType) { - stats = stats || {}; - return new RTPStreamStats(stats.timestamp, stats.packetsLost, stats.packetsCount, streamType, stats.audioLevel); - }; - var SoftphoneLogger = function SoftphoneLogger(logger) { - this._originalLogger = logger; - var self = this; - this._tee = function (level, method) { - return function () { - // call the original logger object to output to browser - //Connect logger follows %s format to print objects to console. - var args = Array.prototype.slice.call(arguments[0]); - var format = ""; - args.forEach(function () { - format = format + " %s"; - }); - return method.apply(self._originalLogger, [connect.LogComponent.SOFTPHONE, format].concat(args)); - }; - }; - }; - SoftphoneLogger.prototype.debug = function () { - return this._tee(1, this._originalLogger.debug)(arguments); - }; - SoftphoneLogger.prototype.info = function () { - return this._tee(2, this._originalLogger.info)(arguments); - }; - SoftphoneLogger.prototype.log = function () { - return this._tee(3, this._originalLogger.log)(arguments); - }; - SoftphoneLogger.prototype.warn = function () { - return this._tee(4, this._originalLogger.warn)(arguments); - }; - SoftphoneLogger.prototype.error = function () { - return this._tee(5, this._originalLogger.error)(arguments); - }; - connect.SoftphoneManager = SoftphoneManager; - })(); - - /***/ -}), - -/***/ 778: -/***/ (() => { - - /*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ - - (function () { - var ctx = this; - var sprintf = function sprintf() { - if (!sprintf.cache.hasOwnProperty(arguments[0])) { - sprintf.cache[arguments[0]] = sprintf.parse(arguments[0]); - } - return sprintf.format.call(null, sprintf.cache[arguments[0]], arguments); - }; - sprintf.format = function (parse_tree, argv) { - var cursor = 1, - tree_length = parse_tree.length, - node_type = '', - arg, - output = [], - i, - k, - match, - pad, - pad_character, - pad_length; - for (i = 0; i < tree_length; i++) { - node_type = get_type(parse_tree[i]); - if (node_type === 'string') { - output.push(parse_tree[i]); - } else if (node_type === 'array') { - match = parse_tree[i]; // convenience purposes only - if (match[2]) { - // keyword argument - arg = argv[cursor]; - for (k = 0; k < match[2].length; k++) { - if (!arg.hasOwnProperty(match[2][k])) { - throw sprintf('[sprintf] property "%s" does not exist', match[2][k]); - } - arg = arg[match[2][k]]; - } - } else if (match[1]) { - // positional argument (explicit) - arg = argv[match[1]]; - } else { - // positional argument (implicit) - arg = argv[cursor++]; - } - if (/[^s]/.test(match[8]) && get_type(arg) != 'number') { - throw sprintf('[sprintf] expecting number but found %s', get_type(arg)); - } - switch (match[8]) { - case 'b': - arg = arg.toString(2); - break; - case 'c': - arg = String.fromCharCode(arg); - break; - case 'd': - arg = parseInt(arg, 10); - break; - case 'e': - arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); - break; - case 'f': - arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); - break; - case 'o': - arg = arg.toString(8); - break; - case 's': - arg = (arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg; - break; - case 'u': - arg = arg >>> 0; - break; - case 'x': - arg = arg.toString(16); - break; - case 'X': - arg = arg.toString(16).toUpperCase(); - break; - } - arg = /[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg; - pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; - pad_length = match[6] - String(arg).length; - pad = match[6] ? str_repeat(pad_character, pad_length) : ''; - output.push(match[5] ? arg + pad : pad + arg); - } - } - return output.join(''); - }; - sprintf.cache = {}; - sprintf.parse = function (fmt) { - var _fmt = fmt, - match = [], - parse_tree = [], - arg_names = 0; - while (_fmt) { - if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { - parse_tree.push(match[0]); - } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { - parse_tree.push('%'); - } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { - if (match[2]) { - arg_names |= 1; - var field_list = [], - replacement_field = match[2], - field_match = []; - if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { - if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { - field_list.push(field_match[1]); - } else { - throw '[sprintf] huh?'; - } - } - } else { - throw '[sprintf] huh?'; - } - match[2] = field_list; - } else { - arg_names |= 2; - } - if (arg_names === 3) { - throw '[sprintf] mixing positional and named placeholders is not (yet) supported'; - } - parse_tree.push(match); - } else { - throw '[sprintf] huh?'; - } - _fmt = _fmt.substring(match[0].length); - } - return parse_tree; - }; - var vsprintf = function vsprintf(fmt, argv, _argv) { - _argv = argv.slice(0); - _argv.splice(0, 0, fmt); - return sprintf.apply(null, _argv); - }; - - /** - * helpers - */ - function get_type(variable) { - return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); - } - function str_repeat(input, multiplier) { - for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */ } - return output.join(''); - } - - /** - * export to either browser or node.js - */ - ctx.sprintf = sprintf; - ctx.vsprintf = vsprintf; - })(); + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */exports.inherits=require('inherits');exports._extend=function(origin,add){// Don't do anything if add isn't an object +if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]];}return origin;};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop);}}).call(this);}).call(this,require('_process'),typeof __webpack_require__.g!=="undefined"?__webpack_require__.g:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{});},{"./support/isBuffer":96,"_process":86,"inherits":95}],98:[function(require,module,exports){var v1=require('./v1');var v4=require('./v4');var uuid=v4;uuid.v1=v1;uuid.v4=v4;module.exports=uuid;},{"./v1":101,"./v4":102}],99:[function(require,module,exports){/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */var byteToHex=[];for(var i=0;i<256;++i){byteToHex[i]=(i+0x100).toString(16).substr(1);}function bytesToUuid(buf,offset){var i=offset||0;var bth=byteToHex;// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 +return[bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],'-',bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]],bth[buf[i++]]].join('');}module.exports=bytesToUuid;},{}],100:[function(require,module,exports){// Unique ID creation requires a high quality random # generator. In the +// browser this is a little complicated due to unknown quality of Math.random() +// and inconsistent support for the `crypto` API. We do the best we can via +// feature-detection +// getRandomValues needs to be invoked in a context where "this" is a Crypto +// implementation. Also, find the complete implementation of crypto on IE11. +var getRandomValues=typeof crypto!='undefined'&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!='undefined'&&typeof window.msCrypto.getRandomValues=='function'&&msCrypto.getRandomValues.bind(msCrypto);if(getRandomValues){// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto +var rnds8=new Uint8Array(16);// eslint-disable-line no-undef +module.exports=function whatwgRNG(){getRandomValues(rnds8);return rnds8;};}else{// Math.random()-based (RNG) +// +// If all else fails, use Math.random(). It's fast, but is of unspecified +// quality. +var rnds=new Array(16);module.exports=function mathRNG(){for(var i=0,r;i<16;i++){if((i&0x03)===0)r=Math.random()*0x100000000;rnds[i]=r>>>((i&0x03)<<3)&0xff;}return rnds;};}},{}],101:[function(require,module,exports){var rng=require('./lib/rng');var bytesToUuid=require('./lib/bytesToUuid');// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +var _nodeId;var _clockseq;// Previous uuid creation time +var _lastMSecs=0;var _lastNSecs=0;// See https://github.com/broofa/node-uuid for API details +function v1(options,buf,offset){var i=buf&&offset||0;var b=buf||[];options=options||{};var node=options.node||_nodeId;var clockseq=options.clockseq!==undefined?options.clockseq:_clockseq;// node and clockseq need to be initialized to random values if they're not +// specified. We do this lazily to minimize issues related to insufficient +// system entropy. See #189 +if(node==null||clockseq==null){var seedBytes=rng();if(node==null){// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) +node=_nodeId=[seedBytes[0]|0x01,seedBytes[1],seedBytes[2],seedBytes[3],seedBytes[4],seedBytes[5]];}if(clockseq==null){// Per 4.2.2, randomize (14 bit) clockseq +clockseq=_clockseq=(seedBytes[6]<<8|seedBytes[7])&0x3fff;}}// UUID timestamps are 100 nano-second units since the Gregorian epoch, +// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so +// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' +// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. +var msecs=options.msecs!==undefined?options.msecs:new Date().getTime();// Per 4.2.1.2, use count of uuid's generated during the current clock +// cycle to simulate higher resolution clock +var nsecs=options.nsecs!==undefined?options.nsecs:_lastNSecs+1;// Time since last uuid creation (in msecs) +var dt=msecs-_lastMSecs+(nsecs-_lastNSecs)/10000;// Per 4.2.1.2, Bump clockseq on clock regression +if(dt<0&&options.clockseq===undefined){clockseq=clockseq+1&0x3fff;}// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new +// time interval +if((dt<0||msecs>_lastMSecs)&&options.nsecs===undefined){nsecs=0;}// Per 4.2.1.2 Throw error if too many uuids are requested +if(nsecs>=10000){throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');}_lastMSecs=msecs;_lastNSecs=nsecs;_clockseq=clockseq;// Per 4.1.4 - Convert from unix epoch to Gregorian epoch +msecs+=12219292800000;// `time_low` +var tl=((msecs&0xfffffff)*10000+nsecs)%0x100000000;b[i++]=tl>>>24&0xff;b[i++]=tl>>>16&0xff;b[i++]=tl>>>8&0xff;b[i++]=tl&0xff;// `time_mid` +var tmh=msecs/0x100000000*10000&0xfffffff;b[i++]=tmh>>>8&0xff;b[i++]=tmh&0xff;// `time_high_and_version` +b[i++]=tmh>>>24&0xf|0x10;// include version +b[i++]=tmh>>>16&0xff;// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) +b[i++]=clockseq>>>8|0x80;// `clock_seq_low` +b[i++]=clockseq&0xff;// `node` +for(var n=0;n<6;++n){b[i+n]=node[n];}return buf?buf:bytesToUuid(b);}module.exports=v1;},{"./lib/bytesToUuid":99,"./lib/rng":100}],102:[function(require,module,exports){var rng=require('./lib/rng');var bytesToUuid=require('./lib/bytesToUuid');function v4(options,buf,offset){var i=buf&&offset||0;if(typeof options=='string'){buf=options==='binary'?new Array(16):null;options=null;}options=options||{};var rnds=options.random||(options.rng||rng)();// Per 4.4, set bits for version and `clock_seq_hi_and_reserved` +rnds[6]=rnds[6]&0x0f|0x40;rnds[8]=rnds[8]&0x3f|0x80;// Copy bytes to buffer, if provided +if(buf){for(var ii=0;ii<16;++ii){buf[i+ii]=rnds[ii];}}return buf||bytesToUuid(rnds);}module.exports=v4;},{"./lib/bytesToUuid":99,"./lib/rng":100}],103:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var LRU_1=require("./utils/LRU");var CACHE_SIZE=1000;/** + * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache] + */var EndpointCache=/** @class */function(){function EndpointCache(maxSize){if(maxSize===void 0){maxSize=CACHE_SIZE;}this.maxSize=maxSize;this.cache=new LRU_1.LRUCache(maxSize);};Object.defineProperty(EndpointCache.prototype,"size",{get:function get(){return this.cache.length;},enumerable:true,configurable:true});EndpointCache.prototype.put=function(key,value){var keyString=typeof key!=='string'?EndpointCache.getKeyString(key):key;var endpointRecord=this.populateValue(value);this.cache.put(keyString,endpointRecord);};EndpointCache.prototype.get=function(key){var keyString=typeof key!=='string'?EndpointCache.getKeyString(key):key;var now=Date.now();var records=this.cache.get(keyString);if(records){for(var i=0;i { - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /**--------------------------------------------------------------- - * class Stream - * - * Represents an object from which messages can be read and to which - * messages can be sent. - */ - var Stream = function Stream() { }; - - /** - * Send a message to the stream. This method must be implemented by subclasses. - */ - Stream.prototype.send = function (message) { - throw new connect.NotImplementedError(); - }; - - /** - * Provide a method to be called when messages are received from this stream. - * This method must be implemented by subclasses. - */ - Stream.prototype.onMessage = function (f) { - throw new connect.NotImplementedError(); - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + /**--------------------------------------------------------------- + * enum ClientMethods + */ + connect.ClientMethods = connect.makeEnum(['getAgentSnapshot', 'putAgentState', 'getAgentStates', 'getDialableCountryCodes', 'getRoutingProfileQueues', 'getAgentPermissions', 'getAgentConfiguration', 'updateAgentConfiguration', 'acceptContact', 'createOutboundContact', 'createTaskContact', 'clearContact', 'completeContact', 'destroyContact', 'rejectContact', 'notifyContactIssue', 'updateContactAttributes', 'createAdditionalConnection', 'destroyConnection', 'holdConnection', 'resumeConnection', 'toggleActiveConnections', 'conferenceConnections', 'sendClientLogs', 'sendDigits', 'sendSoftphoneCallReport', 'sendSoftphoneCallMetrics', 'getEndpoints', 'getNewAuthToken', 'createTransport', 'muteParticipant', 'unmuteParticipant']); + + /**--------------------------------------------------------------- + * enum AgentAppClientMethods + */ + connect.AgentAppClientMethods = { + GET_CONTACT: "AgentAppService.Lcms.getContact", + DELETE_SPEAKER: "AgentAppService.VoiceId.deleteSpeaker", + ENROLL_BY_SESSION: "AgentAppService.VoiceId.enrollBySession", + EVALUATE_SESSION: "AgentAppService.VoiceId.evaluateSession", + DESCRIBE_SPEAKER: "AgentAppService.VoiceId.describeSpeaker", + OPT_OUT_SPEAKER: "AgentAppService.VoiceId.optOutSpeaker", + UPDATE_VOICE_ID_DATA: "AgentAppService.Lcms.updateVoiceIdData", + DESCRIBE_SESSION: "AgentAppService.VoiceId.describeSession", + UPDATE_SESSION: "AgentAppService.VoiceId.updateSession", + START_VOICE_ID_SESSION: "AgentAppService.Nasa.startVoiceIdSession", + LIST_INTEGRATION_ASSOCIATIONS: "AgentAppService.Acs.listIntegrationAssociations" + }; + + /**--------------------------------------------------------------- + * enum MasterMethods + */ + connect.MasterMethods = connect.makeEnum(['becomeMaster', 'checkMaster']); + + /**--------------------------------------------------------------- + * abstract class ClientBase + */ + var ClientBase = function ClientBase() {}; + ClientBase.EMPTY_CALLBACKS = { + success: function success() {}, + failure: function failure() {} + }; + ClientBase.prototype.call = function (method, paramsIn, callbacksIn) { + connect.assertNotNull(method, 'method'); + var params = paramsIn || {}; + var callbacks = callbacksIn || ClientBase.EMPTY_CALLBACKS; + this._callImpl(method, params, callbacks); + }; + ClientBase.prototype._callImpl = function (method, params, callbacks) { + throw new connect.NotImplementedError(); + }; + + /**--------------------------------------------------------------- + * class NullClient extends ClientBase + */ + var NullClient = function NullClient() { + ClientBase.call(this); + }; + NullClient.prototype = Object.create(ClientBase.prototype); + NullClient.prototype.constructor = NullClient; + NullClient.prototype._callImpl = function (method, params, callbacks) { + if (callbacks && callbacks.failure) { + var message = connect.sprintf('No such method exists on NULL client: %s', method); + callbacks.failure(new connect.ValueError(message), { + message: message + }); + } + }; + + /**--------------------------------------------------------------- + * abstract class UpstreamConduitClientBase extends ClientBase + */ + var UpstreamConduitClientBase = function UpstreamConduitClientBase(conduit, requestEvent, responseEvent) { + ClientBase.call(this); + this.conduit = conduit; + this.requestEvent = requestEvent; + this.responseEvent = responseEvent; + this._requestIdCallbacksMap = {}; + this.conduit.onUpstream(responseEvent, connect.hitch(this, this._handleResponse)); + }; + UpstreamConduitClientBase.prototype = Object.create(ClientBase.prototype); + UpstreamConduitClientBase.prototype.constructor = UpstreamConduitClientBase; + UpstreamConduitClientBase.prototype._callImpl = function (method, params, callbacks) { + var request = connect.EventFactory.createRequest(this.requestEvent, method, params); + this._requestIdCallbacksMap[request.requestId] = callbacks; + this.conduit.sendUpstream(request.event, request); + }; + UpstreamConduitClientBase.prototype._getCallbacksForRequest = function (requestId) { + var callbacks = this._requestIdCallbacksMap[requestId] || null; + if (callbacks != null) { + delete this._requestIdCallbacksMap[requestId]; + } + return callbacks; + }; + UpstreamConduitClientBase.prototype._handleResponse = function (data) { + var callbacks = this._getCallbacksForRequest(data.requestId); + if (callbacks == null) { + return; + } + if (data.err && callbacks.failure) { + callbacks.failure(data.err, data.data); + } else if (callbacks.success) { + callbacks.success(data.data); + } + }; + + /**--------------------------------------------------------------- + * class UpstreamConduitClient extends ClientBase + */ + var UpstreamConduitClient = function UpstreamConduitClient(conduit) { + UpstreamConduitClientBase.call(this, conduit, connect.EventType.API_REQUEST, connect.EventType.API_RESPONSE); + }; + UpstreamConduitClient.prototype = Object.create(UpstreamConduitClientBase.prototype); + UpstreamConduitClient.prototype.constructor = UpstreamConduitClient; + + /**--------------------------------------------------------------- + * class UpstreamConduitMasterClient extends ClientBase + */ + var UpstreamConduitMasterClient = function UpstreamConduitMasterClient(conduit) { + UpstreamConduitClientBase.call(this, conduit, connect.EventType.MASTER_REQUEST, connect.EventType.MASTER_RESPONSE); + }; + UpstreamConduitMasterClient.prototype = Object.create(UpstreamConduitClientBase.prototype); + UpstreamConduitMasterClient.prototype.constructor = UpstreamConduitMasterClient; + + /**--------------------------------------------------------------- + * class AgentAppClient extends ClientBase + */ + var AgentAppClient = function AgentAppClient(authCookieName, authToken, endpoint) { + connect.assertNotNull(authCookieName, 'authCookieName'); + connect.assertNotNull(authToken, 'authToken'); + connect.assertNotNull(endpoint, 'endpoint'); + ClientBase.call(this); + this.endpointUrl = connect.getUrlWithProtocol(endpoint); + this.authToken = authToken; + this.authCookieName = authCookieName; + }; + AgentAppClient.prototype = Object.create(ClientBase.prototype); + AgentAppClient.prototype.constructor = AgentAppClient; + AgentAppClient.prototype._callImpl = function (method, params, callbacks) { + var self = this; + var bear = {}; + bear[self.authCookieName] = self.authToken; + var options = { + method: 'post', + body: JSON.stringify(params || {}), + headers: { + 'Accept': 'application/json', + 'Content-Type': 'application/json', + 'X-Amz-target': method, + 'X-Amz-Bearer': JSON.stringify(bear) + } + }; + connect.fetch(self.endpointUrl, options).then(function (res) { + callbacks.success(res); + })["catch"](function (err) { + var reader = err.body.getReader(); + var body = ''; + var decoder = new TextDecoder(); + reader.read().then(function processText(_ref) { + var done = _ref.done, + value = _ref.value; + if (done) { + var error = JSON.parse(body); + error.status = err.status; + callbacks.failure(error); + return; + } + body += decoder.decode(value); + return reader.read().then(processText); + }); + }); + }; + /**--------------------------------------------------------------- + * class AWSClient extends ClientBase + */ + var AWSClient = function AWSClient(authToken, region, endpointIn) { + connect.assertNotNull(authToken, 'authToken'); + connect.assertNotNull(region, 'region'); + ClientBase.call(this); + AWS.config.credentials = new AWS.Credentials({}); + AWS.config.region = region; + this.authToken = authToken; + var baseUrl = connect.getBaseUrl(); + var endpointUrl = endpointIn || (baseUrl.includes(".awsapps.com") ? baseUrl + '/connect/api' : baseUrl + '/api'); + var endpoint = new AWS.Endpoint(endpointUrl); + this.client = new AWS.Connect({ + endpoint: endpoint + }); + }; + AWSClient.prototype = Object.create(ClientBase.prototype); + AWSClient.prototype.constructor = AWSClient; + AWSClient.prototype._callImpl = function (method, params, callbacks) { + var self = this; + var log = connect.getLog(); + if (!connect.contains(this.client, method)) { + var message = connect.sprintf('No such method exists on AWS client: %s', method); + callbacks.failure(new connect.ValueError(message), { + message: message + }); + } else { + params = this._translateParams(method, params); + log.trace("AWSClient: --> Calling operation '%s'", method).sendInternalLogToServer(); + this.client[method](params).on('build', function (request) { + request.httpRequest.headers['X-Amz-Bearer'] = self.authToken; + }).send(function (err, data) { + try { + if (err) { + if (err.code === connect.CTIExceptions.UNAUTHORIZED_EXCEPTION) { + callbacks.authFailure(); + } else if (callbacks.accessDenied && (err.code === connect.CTIExceptions.ACCESS_DENIED_EXCEPTION || err.statusCode === 403)) { + callbacks.accessDenied(); + } else { + // Can't pass err directly to postMessage + // postMessage() tries to clone the err object and failed. + // Refer to https://github.com/goatslacker/alt-devtool/issues/5 + var error = {}; + error.type = err.code; + error.message = err.message; + error.stack = err.stack ? err.stack.split('\n') : []; + callbacks.failure(error, data); + } + log.trace("AWSClient: <-- Operation '%s' failed: %s", method, JSON.stringify(err)).sendInternalLogToServer(); + } else { + log.trace("AWSClient: <-- Operation '%s' succeeded.", method).withObject(data).sendInternalLogToServer(); + callbacks.success(data); + } + } catch (e) { + connect.getLog().error("Failed to handle AWS API request for method %s", method).withException(e).sendInternalLogToServer(); + } + }); + } + }; + AWSClient.prototype._requiresAuthenticationParam = function (method) { + return method !== connect.ClientMethods.COMPLETE_CONTACT && method !== connect.ClientMethods.CLEAR_CONTACT && method !== connect.ClientMethods.REJECT_CONTACT && method !== connect.ClientMethods.CREATE_TASK_CONTACT; + }; + AWSClient.prototype._translateParams = function (method, params) { + switch (method) { + case connect.ClientMethods.UPDATE_AGENT_CONFIGURATION: + params.configuration = this._translateAgentConfiguration(params.configuration); + break; + case connect.ClientMethods.SEND_SOFTPHONE_CALL_METRICS: + params.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(params.softphoneStreamStatistics); + break; + case connect.ClientMethods.SEND_SOFTPHONE_CALL_REPORT: + params.report = this._translateSoftphoneCallReport(params.report); + break; + default: + break; + } + if (this._requiresAuthenticationParam(method)) { + params.authentication = { + authToken: this.authToken + }; + } + return params; + }; + AWSClient.prototype._translateAgentConfiguration = function (config) { + return { + name: config.name, + softphoneEnabled: config.softphoneEnabled, + softphoneAutoAccept: config.softphoneAutoAccept, + extension: config.extension, + routingProfile: this._translateRoutingProfile(config.routingProfile), + agentPreferences: config.agentPreferences + }; + }; + AWSClient.prototype._translateRoutingProfile = function (profile) { + return { + name: profile.name, + routingProfileARN: profile.routingProfileARN, + defaultOutboundQueue: this._translateQueue(profile.defaultOutboundQueue) + }; + }; + AWSClient.prototype._translateQueue = function (queue) { + return { + queueARN: queue.queueARN, + name: queue.name + }; + }; + AWSClient.prototype._translateSoftphoneStreamStatistics = function (stats) { + stats.forEach(function (stat) { + if ('packetsCount' in stat) { + stat.packetCount = stat.packetsCount; + delete stat.packetsCount; + } + }); + return stats; + }; + AWSClient.prototype._translateSoftphoneCallReport = function (report) { + if ('handshakingTimeMillis' in report) { + report.handshakeTimeMillis = report.handshakingTimeMillis; + delete report.handshakingTimeMillis; + } + if ('preTalkingTimeMillis' in report) { + report.preTalkTimeMillis = report.preTalkingTimeMillis; + delete report.preTalkingTimeMillis; + } + if ('handshakingFailure' in report) { + report.handshakeFailure = report.handshakingFailure; + delete report.handshakingFailure; + } + if ('talkingTimeMillis' in report) { + report.talkTimeMillis = report.talkingTimeMillis; + delete report.talkingTimeMillis; + } + report.softphoneStreamStatistics = this._translateSoftphoneStreamStatistics(report.softphoneStreamStatistics); + return report; + }; + connect.ClientBase = ClientBase; + connect.NullClient = NullClient; + connect.UpstreamConduitClient = UpstreamConduitClient; + connect.UpstreamConduitMasterClient = UpstreamConduitMasterClient; + connect.AWSClient = AWSClient; + connect.AgentAppClient = AgentAppClient; +})(); - /**--------------------------------------------------------------- - * class NullStream extends Stream - * - * A null stream which provides no message sending or receiving facilities. - */ - var NullStream = function NullStream() { - Stream.call(this); - }; - NullStream.prototype = Object.create(Stream.prototype); - NullStream.prototype.constructor = NullStream; - NullStream.prototype.onMessage = function (f) { }; - NullStream.prototype.send = function (message) { }; - - /**--------------------------------------------------------------- - * class WindowStream extends Stream - * - * A stream for communicating with a window object. The domain provided - * must match the allowed message domains of the downstream receiver - * or messages will be rejected, see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage - * for more info. - */ - var WindowStream = function WindowStream(win, domain) { - Stream.call(this); - this.window = win; - this.domain = domain || '*'; - }; - WindowStream.prototype = Object.create(Stream.prototype); - WindowStream.prototype.constructor = WindowStream; - WindowStream.prototype.send = function (message) { - this.window.postMessage(message, this.domain); - }; - WindowStream.prototype.onMessage = function (f) { - this.window.addEventListener("message", f); - }; +/***/ }), - /**--------------------------------------------------------------- - * class WindowIOStream extends Stream - * - * A stream used by IFrame/popup windows to communicate with their parents - * and vise versa. - * - * This object encapsulates the fact that incoming and outgoing messages - * arrive on different windows and allows this to be managed as a single - * Stream object. - */ - var WindowIOStream = function WindowIOStream(inputwin, outputwin, domain) { - Stream.call(this); - this.input = inputwin; - this.output = outputwin; - this.domain = domain || '*'; - }; - WindowIOStream.prototype = Object.create(Stream.prototype); - WindowIOStream.prototype.constructor = WindowIOStream; - WindowIOStream.prototype.send = function (message) { - this.output.postMessage(message, this.domain); - }; - WindowIOStream.prototype.onMessage = function (f) { - var _this = this; - this.input.addEventListener("message", function (message) { - if (message.source === _this.output) { - f(message); - } - }); - }; +/***/ 531: +/***/ (() => { - /**--------------------------------------------------------------- - * class PortStream extends Stream - * - * A stream wrapping an HTML5 Worker port. This could be the port - * used to connect to a Worker or one of the multitude of ports - * made available to a SharedWorker for communication back to - * its connected clients. - */ - var PortStream = function PortStream(port) { - Stream.call(this); - this.port = port; - this.id = connect.randomId(); - }; - PortStream.prototype = Object.create(Stream.prototype); - PortStream.prototype.constructor = PortStream; - PortStream.prototype.send = function (message) { - this.port.postMessage(message); - }; - PortStream.prototype.onMessage = function (f) { - this.port.addEventListener("message", f); - }; - PortStream.prototype.getId = function () { - return this.id; - }; +function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + connect.core = {}; + connect.core.initialized = false; + connect.version = "1.7.7"; + connect.DEFAULT_BATCH_SIZE = 500; + var CCP_SYN_TIMEOUT = 1000; // 1 sec + var CCP_ACK_TIMEOUT = 3000; // 3 sec + var CCP_LOAD_TIMEOUT = 5000; // 5 sec + var CCP_IFRAME_REFRESH_INTERVAL = 5000; // 5 sec + + var LEGACY_LOGIN_URL_PATTERN = "https://{alias}.awsapps.com/auth/?client_id={client_id}&redirect_uri={redirect}"; + var CLIENT_ID_MAP = { + "us-east-1": "06919f4fd8ed324e" + }; + var AUTHORIZE_ENDPOINT = "/auth/authorize"; + var LEGACY_AUTHORIZE_ENDPOINT = "/connect/auth/authorize"; + var AUTHORIZE_RETRY_INTERVAL = 2000; + var AUTHORIZE_MAX_RETRY = 5; + var LEGACY_WHITELISTED_ORIGINS_ENDPOINT = "/connect/whitelisted-origins"; + var WHITELISTED_ORIGINS_ENDPOINT = "/whitelisted-origins"; + var WHITELISTED_ORIGINS_RETRY_INTERVAL = 2000; + var WHITELISTED_ORIGINS_MAX_RETRY = 5; + connect.numberOfConnectedCCPs = 0; + var CCP_IFRAME_NAME = 'Amazon Connect CCP'; + + /** + * @deprecated + * This function was only meant for internal use. + * The name is misleading for what it should do. + * Internally we have replaced its usage with `getLoginUrl`. + */ + var createLoginUrl = function createLoginUrl(params) { + var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; + connect.assertNotNull(redirect); + if (params.loginUrl) { + return params.loginUrl; + } else if (params.alias) { + log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); + return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); + } else { + return params.ccpUrl; + } + }; + + /** + * Replaces `createLoginUrl`, as that function's name was misleading. + * The `params.alias` parameter is deprecated. Please refrain from using it. + */ + var getLoginUrl = function getLoginUrl(params) { + var redirect = "https://lily.us-east-1.amazonaws.com/taw/auth/code"; + connect.assertNotNull(redirect); + if (params.loginUrl) { + return params.loginUrl; + } else if (params.alias) { + log.warn("The `alias` param is deprecated and should not be expected to function properly. Please use `ccpUrl` or `loginUrl`. See https://github.com/amazon-connect/amazon-connect-streams/blob/master/README.md#connectcoreinitccp for valid parameters."); + return LEGACY_LOGIN_URL_PATTERN.replace("{alias}", params.alias).replace("{client_id}", CLIENT_ID_MAP["us-east-1"]).replace("{redirect}", global.encodeURIComponent(redirect)); + } else { + return params.ccpUrl; + } + }; + + /**------------------------------------------------------------------------- + * Returns scheme://host:port for a given url + */ + function sanitizeDomain(url) { + var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n?]+)/ig); + return domain.length ? domain[0] : ""; + } + + /**------------------------------------------------------------------------- + * Print a warning message if the Connect core is not initialized. + */ + connect.core.checkNotInitialized = function () { + if (connect.core.initialized) { + var log = connect.getLog(); + log.warn("Connect core already initialized, only needs to be initialized once.").sendInternalLogToServer(); + } + }; + + /**------------------------------------------------------------------------- + * Basic Connect client initialization. + * Should be used only by the API Shared Worker. + */ + connect.core.init = function (params) { + connect.core.eventBus = new connect.EventBus(); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.initClient(params); + connect.core.initAgentAppClient(params); + connect.core.initialized = true; + }; + + /**------------------------------------------------------------------------- + * Initialized AWS client + * Should be used by Shared Worker to update AWS client with new credentials + * after refreshed authentication. + */ + connect.core.initClient = function (params) { + connect.assertNotNull(params, 'params'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var region = connect.assertNotNull(params.region, 'params.region'); + var endpoint = params.endpoint || null; + connect.core.client = new connect.AWSClient(authToken, region, endpoint); + }; + + /**------------------------------------------------------------------------- + * Initialized AgentApp client + * Should be used by Shared Worker to update AgentApp client with new credentials + * after refreshed authentication. + */ + connect.core.initAgentAppClient = function (params) { + connect.assertNotNull(params, 'params'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var authCookieName = connect.assertNotNull(params.authCookieName, 'params.authCookieName'); + var endpoint = connect.assertNotNull(params.agentAppEndpoint, 'params.agentAppEndpoint'); + connect.core.agentAppClient = new connect.AgentAppClient(authCookieName, authToken, endpoint); + }; + + /**------------------------------------------------------------------------- + * Uninitialize Connect. + */ + connect.core.terminate = function () { + connect.core.client = new connect.NullClient(); + connect.core.agentAppClient = new connect.NullClient(); + connect.core.masterClient = new connect.NullClient(); + var bus = connect.core.getEventBus(); + if (bus) bus.unsubscribeAll(); + connect.core.bus = new connect.EventBus(); + connect.core.agentDataProvider = null; + connect.core.softphoneManager = null; + connect.core.upstream = null; + connect.core.keepaliveManager = null; + connect.agent.initialized = false; + connect.core.initialized = false; + }; + + /**------------------------------------------------------------------------- + * Setup the SoftphoneManager to be initialized when the agent + * is determined to have softphone enabled. + */ + connect.core.softphoneUserMediaStream = null; + connect.core.getSoftphoneUserMediaStream = function () { + return connect.core.softphoneUserMediaStream; + }; + connect.core.setSoftphoneUserMediaStream = function (stream) { + connect.core.softphoneUserMediaStream = stream; + }; + connect.core.initRingtoneEngines = function (params) { + connect.assertNotNull(params, "params"); + var setupRingtoneEngines = function setupRingtoneEngines(ringtoneSettings) { + connect.assertNotNull(ringtoneSettings, "ringtoneSettings"); + connect.assertNotNull(ringtoneSettings.voice, "ringtoneSettings.voice"); + connect.assertTrue(ringtoneSettings.voice.ringtoneUrl || ringtoneSettings.voice.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.voice.disabled must be true"); + connect.assertNotNull(ringtoneSettings.queue_callback, "ringtoneSettings.queue_callback"); + connect.assertTrue(ringtoneSettings.queue_callback.ringtoneUrl || ringtoneSettings.queue_callback.disabled, "ringtoneSettings.voice.ringtoneUrl must be provided or ringtoneSettings.queue_callback.disabled must be true"); + connect.core.ringtoneEngines = {}; + connect.agent(function (agent) { + agent.onRefresh(function () { + connect.ifMaster(connect.MasterTopics.RINGTONE, function () { + if (!ringtoneSettings.voice.disabled && !connect.core.ringtoneEngines.voice) { + connect.core.ringtoneEngines.voice = new connect.VoiceRingtoneEngine(ringtoneSettings.voice); + connect.getLog().info("VoiceRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.chat.disabled && !connect.core.ringtoneEngines.chat) { + connect.core.ringtoneEngines.chat = new connect.ChatRingtoneEngine(ringtoneSettings.chat); + connect.getLog().info("ChatRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.task.disabled && !connect.core.ringtoneEngines.task) { + connect.core.ringtoneEngines.task = new connect.TaskRingtoneEngine(ringtoneSettings.task); + connect.getLog().info("TaskRingtoneEngine initialized.").sendInternalLogToServer(); + } + if (!ringtoneSettings.queue_callback.disabled && !connect.core.ringtoneEngines.queue_callback) { + connect.core.ringtoneEngines.queue_callback = new connect.QueueCallbackRingtoneEngine(ringtoneSettings.queue_callback); + connect.getLog().info("QueueCallbackRingtoneEngine initialized.").sendInternalLogToServer(); + } + }); + }); + }); + handleRingerDeviceChange(); + }; + var mergeParams = function mergeParams(params, otherParams) { + // For backwards compatibility: support pulling disabled flag and ringtoneUrl + // from softphone config if it exists from downstream into the ringtone config. + params.ringtone = params.ringtone || {}; + params.ringtone.voice = params.ringtone.voice || {}; + params.ringtone.queue_callback = params.ringtone.queue_callback || {}; + params.ringtone.chat = params.ringtone.chat || { + disabled: true + }; + params.ringtone.task = params.ringtone.task || { + disabled: true + }; + if (otherParams.softphone) { + if (otherParams.softphone.disableRingtone) { + params.ringtone.voice.disabled = true; + params.ringtone.queue_callback.disabled = true; + } + if (otherParams.softphone.ringtoneUrl) { + params.ringtone.voice.ringtoneUrl = otherParams.softphone.ringtoneUrl; + params.ringtone.queue_callback.ringtoneUrl = otherParams.softphone.ringtoneUrl; + } + } + if (otherParams.chat) { + if (otherParams.chat.disableRingtone) { + params.ringtone.chat.disabled = true; + } + if (otherParams.chat.ringtoneUrl) { + params.ringtone.chat.ringtoneUrl = otherParams.chat.ringtoneUrl; + } + } + + // Merge in ringtone settings from downstream. + if (otherParams.ringtone) { + params.ringtone.voice = connect.merge(params.ringtone.voice, otherParams.ringtone.voice || {}); + params.ringtone.queue_callback = connect.merge(params.ringtone.queue_callback, otherParams.ringtone.voice || {}); + params.ringtone.chat = connect.merge(params.ringtone.chat, otherParams.ringtone.chat || {}); + } + }; + + // Merge params from params.softphone and params.chat into params.ringtone + // for embedded and non-embedded use cases so that defaults are picked up. + mergeParams(params, params); + if (connect.isFramed()) { + // If the CCP is in a frame, wait for configuration from downstream. + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + this.unsubscribe(); + // Merge all params from data into params for any overridden + // values in either legacy "softphone" or "ringtone" settings. + mergeParams(params, data); + setupRingtoneEngines(params.ringtone); + }); + } else { + setupRingtoneEngines(params.ringtone); + } + }; + var handleRingerDeviceChange = function handleRingerDeviceChange() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.ConfigurationEvents.SET_RINGER_DEVICE, setRingerDevice); + }; + var setRingerDevice = function setRingerDevice(data) { + if (connect.keys(connect.core.ringtoneEngines).length === 0 || !data || !data.deviceId) { + return; + } + var deviceId = data.deviceId; + for (var ringtoneType in connect.core.ringtoneEngines) { + connect.core.ringtoneEngines[ringtoneType].setOutputDevice(deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.RINGER_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); + }; + connect.core.initSoftphoneManager = function (paramsIn) { + connect.getLog().info("[Softphone Manager] initSoftphoneManager started").sendInternalLogToServer(); + var params = paramsIn || {}; + var competeForMasterOnAgentUpdate = function competeForMasterOnAgentUpdate(softphoneParamsIn) { + var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); + connect.getLog().info("[Softphone Manager] competeForMasterOnAgentUpdate executed").sendInternalLogToServer(); + connect.agent(function (agent) { + if (!agent.getChannelConcurrency(connect.ChannelType.VOICE)) { + return; + } + agent.onRefresh(function () { + var sub = this; + connect.getLog().info("[Softphone Manager] agent refresh handler executed").sendInternalLogToServer(); + connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { + connect.getLog().info("[Softphone Manager] confirmed as softphone master topic").sendInternalLogToServer(); + if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { + // Become master to send logs, since we need logs from softphone tab. + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); + sub.unsubscribe(); + } + }); + }); + }); + }; + + /** + * If the window is framed, we need to wait for a CONFIGURE message from + * downstream before we try to initialize, unless params.allowFramedSoftphone is true. + */ + if (connect.isFramed() && !params.allowFramedSoftphone) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + connect.getLog().info("[Softphone Manager] Configure event handler executed").sendInternalLogToServer(); + if (data.softphone && data.softphone.allowFramedSoftphone) { + this.unsubscribe(); + competeForMasterOnAgentUpdate(data.softphone); + } + setupEventListenersForMultiTabUseInFirefox(data.softphone); + }); + } else { + competeForMasterOnAgentUpdate(params); + setupEventListenersForMultiTabUseInFirefox(params); + } + connect.agent(function (agent) { + // Sync mute across all tabs + if (agent.isSoftphoneEnabled() && agent.getChannelConcurrency(connect.ChannelType.VOICE)) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.MUTE + }); + } + }); + function setupEventListenersForMultiTabUseInFirefox(softphoneParamsIn) { + var softphoneParams = connect.merge(params.softphone || {}, softphoneParamsIn); + + // keep the softphone params for external use + connect.core.softphoneParams = softphoneParams; + if (connect.isFirefoxBrowser()) { + // In Firefox, when a tab takes over another tab's softphone primary, + // the previous primary tab should delete sofphone manager and stop microphone + connect.core.getUpstream().onUpstream(connect.EventType.MASTER_RESPONSE, function (res) { + if (res.data && res.data.topic === connect.MasterTopics.SOFTPHONE && res.data.takeOver && res.data.masterId !== connect.core.portStreamId) { + if (connect.core.softphoneManager) { + connect.core.softphoneManager.onInitContactSub.unsubscribe(); + delete connect.core.softphoneManager; + } + var userMediaStream = connect.core.getSoftphoneUserMediaStream(); + if (userMediaStream) { + userMediaStream.getTracks().forEach(function (track) { + track.stop(); + }); + connect.core.setSoftphoneUserMediaStream(null); + } + } + }); - /**--------------------------------------------------------------- - * class StreamMultiplexer extends Stream - * - * A wrapper for multiplexed downstream communication with - * multiple streams at once. Mainly useful for the SharedWorker to - * broadcast events to many PortStream objects at once. - */ - var StreamMultiplexer = function StreamMultiplexer(streams) { - Stream.call(this); - this.streamMap = streams ? connect.index(streams, function (s) { - return s.getId(); - }) : {}; - this.messageListeners = []; - }; - StreamMultiplexer.prototype = Object.create(Stream.prototype); - StreamMultiplexer.prototype.constructor = StreamMultiplexer; - - /** - * Send a message to all ports in the multiplexer. - */ - StreamMultiplexer.prototype.send = function (message) { - this.getStreams().forEach(function (stream) { - try { - stream.send(message); - } catch (e) { - // Couldn't send message to one of the downstreams for some reason... - // No reliable logging possible without further failures, - // no recovery, just eat it. + // In Firefox, when multiple tabs are open, + // webrtc session is not started until READY_TO_START_SESSION event is triggered + connect.core.getEventBus().subscribe(connect.ConnectionEvents.READY_TO_START_SESSION, function () { + connect.ifMaster(connect.MasterTopics.SOFTPHONE, function () { + if (connect.core.softphoneManager) { + connect.core.softphoneManager.startSession(); + } + }, function () { + connect.becomeMaster(connect.MasterTopics.SOFTPHONE, function () { + connect.agent(function (agent) { + if (!connect.core.softphoneManager && agent.isSoftphoneEnabled()) { + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + connect.core.softphoneManager = new connect.SoftphoneManager(softphoneParams); + connect.core.softphoneManager.startSession(); + } + }); + }); + }); + }); + + // handling outbound-call and auto-accept cases for pending session + connect.contact(function (c) { + connect.agent(function (agent) { + c.onRefresh(function (contact) { + if (connect.hasOtherConnectedCCPs() && document.visibilityState === 'visible' && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { + var isOutBoundCall = contact.isSoftphoneCall() && !contact.isInbound(); + var isAutoAcceptEnabled = contact.isSoftphoneCall() && agent.getConfiguration().softphoneAutoAccept; + var isQueuedCallback = contact.getType() === connect.ContactType.QUEUE_CALLBACK; + if (isOutBoundCall || isAutoAcceptEnabled || isQueuedCallback) { + connect.core.triggerReadyToStartSessionEvent(); + } } }); - }; - - /** - * Register a method which will be called when a message is received from - * any of the downstreams. - */ - StreamMultiplexer.prototype.onMessage = function (f) { - this.messageListeners.push(f); - - // Update existing streams with the new listener. - this.getStreams().forEach(function (stream) { - stream.onMessage(f); + }); + }); + } + } + }; + + // trigger READY_TO_START_SESSION event in a context with Softphone Manager + // internal use only + connect.core.triggerReadyToStartSessionEvent = function () { + var allowFramedSoftphone = connect.core.softphoneParams && connect.core.softphoneParams.allowFramedSoftphone; + if (connect.isCCP()) { + if (allowFramedSoftphone) { + // the event is triggered in this iframed CCP context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + if (connect.isFramed()) { + // if this is an iframed CCP, the event is send to downstream (CRM) + connect.core.getUpstream().sendDownstream(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + // if this is a standalone CCP, trigger this event in this CCP context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } + } + } else { + if (allowFramedSoftphone) { + // the event is send to the upstream (iframed CCP) + connect.core.getUpstream().sendUpstream(connect.ConnectionEvents.READY_TO_START_SESSION); + } else { + // the event is triggered in this CRM context + connect.core.getEventBus().trigger(connect.ConnectionEvents.READY_TO_START_SESSION); + } + } + }; + connect.core.initPageOptions = function (params) { + connect.assertNotNull(params, "params"); + if (connect.isFramed()) { + // If the CCP is in a frame, wait for configuration from downstream. + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.CONFIGURE, function (data) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.CONFIGURE, + data: data + }); + }); + // Listen for iframe media devices request from CRM + bus.subscribe(connect.EventType.MEDIA_DEVICE_REQUEST, function () { + function sendDevices(devices) { + connect.core.getUpstream().sendDownstream(connect.EventType.MEDIA_DEVICE_RESPONSE, devices); + } + if (navigator && navigator.mediaDevices) { + navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { + devices = devicesIn || []; + devices = devices.map(function (d) { + return d.toJSON(); + }); + sendDevices(devices); + })["catch"](function (err) { + sendDevices({ + error: err.message }); - }; + }); + } else { + sendDevices({ + error: "No navigator or navigator.mediaDevices object found" + }); + } + }); + } + }; + + /**------------------------------------------------------------------------- + * Get the list of media devices from iframed CCP + * Timeout for the request is passed an an optional argument + * The default timeout is 1000ms + */ + connect.core.getFrameMediaDevices = function (timeoutIn) { + var sub = null; + var timeout = timeoutIn || 1000; + var timeoutPromise = new Promise(function (resolve, reject) { + setTimeout(function () { + reject(new Error("Timeout exceeded")); + }, timeout); + }); + var mediaDevicesPromise = new Promise(function (resolve, reject) { + if (connect.isFramed() || connect.isCCP()) { + if (navigator && navigator.mediaDevices) { + navigator.mediaDevices.enumerateDevices().then(function (devicesIn) { + devices = devicesIn || []; + devices = devices.map(function (d) { + return d.toJSON(); + }); + resolve(devices); + }); + } else { + reject(new Error("No navigator or navigator.mediaDevices object found")); + } + } else { + var bus = connect.core.getEventBus(); + sub = bus.subscribe(connect.EventType.MEDIA_DEVICE_RESPONSE, function (data) { + if (data.error) { + reject(new Error(data.error)); + } else { + resolve(data); + } + }); + connect.core.getUpstream().sendUpstream(connect.EventType.MEDIA_DEVICE_REQUEST); + } + }); + return Promise.race([mediaDevicesPromise, timeoutPromise])["finally"](function () { + if (sub) { + sub.unsubscribe(); + } + }); + }; + + //Internal use only. + connect.core.authorize = function (endpoint) { + var options = { + credentials: 'include' + }; + var authorizeEndpoint = endpoint; + if (!authorizeEndpoint) { + authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; + } + return connect.fetch(authorizeEndpoint, options, AUTHORIZE_RETRY_INTERVAL, AUTHORIZE_MAX_RETRY); + }; + + /** + * @deprecated + * This used to be used internally, but is no longer needed. + */ + connect.core.verifyDomainAccess = function (authToken, endpoint) { + connect.getLog().warn("This API will be deprecated in the next major version release"); + if (!connect.isFramed()) { + return Promise.resolve(); + } + var options = { + headers: { + 'X-Amz-Bearer': authToken + } + }; + var whitelistedOriginsEndpoint = null; + if (endpoint) { + whitelistedOriginsEndpoint = endpoint; + } else { + whitelistedOriginsEndpoint = connect.core.isLegacyDomain() ? LEGACY_WHITELISTED_ORIGINS_ENDPOINT : WHITELISTED_ORIGINS_ENDPOINT; + } + return connect.fetch(whitelistedOriginsEndpoint, options, WHITELISTED_ORIGINS_RETRY_INTERVAL, WHITELISTED_ORIGINS_MAX_RETRY).then(function (response) { + var topDomain = sanitizeDomain(window.document.referrer); + var isAllowed = response.whitelistedOrigins.some(function (origin) { + return topDomain === sanitizeDomain(origin); + }); + return isAllowed ? Promise.resolve() : Promise.reject(); + }); + }; + + /**------------------------------------------------------------------------- + * Returns true if this window's href is on the legacy connect domain. + * Only useful for internal use. + */ + connect.core.isLegacyDomain = function (url) { + url = url || window.location.href; + return url.includes('.awsapps.com'); + }; + + /**------------------------------------------------------------------------- + * Initializes Connect by creating or connecting to the API Shared Worker. + * Used only by the CCP + */ + connect.core.initSharedWorker = function (params) { + connect.core.checkNotInitialized(); + if (connect.core.initialized) { + return; + } + connect.assertNotNull(params, 'params'); + var sharedWorkerUrl = connect.assertNotNull(params.sharedWorkerUrl, 'params.sharedWorkerUrl'); + var authToken = connect.assertNotNull(params.authToken, 'params.authToken'); + var refreshToken = connect.assertNotNull(params.refreshToken, 'params.refreshToken'); + var authTokenExpiration = connect.assertNotNull(params.authTokenExpiration, 'params.authTokenExpiration'); + var region = connect.assertNotNull(params.region, 'params.region'); + var endpoint = params.endpoint || null; + var authorizeEndpoint = params.authorizeEndpoint; + if (!authorizeEndpoint) { + authorizeEndpoint = connect.core.isLegacyDomain() ? LEGACY_AUTHORIZE_ENDPOINT : AUTHORIZE_ENDPOINT; + } + var agentAppEndpoint = params.agentAppEndpoint || null; + var authCookieName = params.authCookieName || null; + try { + // Initialize the event bus and agent data providers. + connect.core.eventBus = new connect.EventBus({ + logEvents: true + }); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.mediaFactory = new connect.MediaFactory(params); + + // Create the shared worker and upstream conduit. + var worker = new SharedWorker(sharedWorkerUrl, "ConnectSharedWorker"); + var conduit = new connect.Conduit("ConnectSharedWorkerConduit", new connect.PortStream(worker.port), new connect.WindowIOStream(window, parent)); + + // Set the global upstream conduit for external use. + connect.core.upstream = conduit; + connect.core.webSocketProvider = new WebSocketProvider(); + + // Close our port to the shared worker before the window closes. + global.onunload = function () { + conduit.sendUpstream(connect.EventType.CLOSE); + worker.port.close(); + }; + connect.getLog().scheduleUpstreamLogPush(conduit); + connect.getLog().scheduleDownstreamClientSideLogsPush(); + // Bridge all upstream messages into the event bus. + conduit.onAllUpstream(connect.core.getEventBus().bridge()); + // Pass all upstream messages (from shared worker) downstream (to CCP consumer). + conduit.onAllUpstream(conduit.passDownstream()); + if (connect.isFramed()) { + // Bridge all downstream messages into the event bus. + conduit.onAllDownstream(connect.core.getEventBus().bridge()); + // Pass all downstream messages (from CCP consumer) upstream (to shared worker). + conduit.onAllDownstream(conduit.passUpstream()); + } + // Send configuration up to the shared worker. + conduit.sendUpstream(connect.EventType.CONFIGURE, { + authToken: authToken, + authTokenExpiration: authTokenExpiration, + endpoint: endpoint, + refreshToken: refreshToken, + region: region, + authorizeEndpoint: authorizeEndpoint, + agentAppEndpoint: agentAppEndpoint, + authCookieName: authCookieName + }); + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { + connect.getLog().info("Acknowledged by the ConnectSharedWorker!").sendInternalLogToServer(); + connect.core.initialized = true; + connect.core.portStreamId = data.id; + this.unsubscribe(); + }); + // Add all upstream log entries to our own logger. + conduit.onUpstream(connect.EventType.LOG, function (logEntry) { + if (logEntry.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + } + }); + // Get worker logs + conduit.onUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logEntry) { + connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(logEntry)); + }); + // Get outer context logs + conduit.onDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, function (logs) { + if (connect.isFramed() && Array.isArray(logs)) { + logs.forEach(function (log) { + connect.getLog().sendInternalLogEntryToServer(connect.LogEntry.fromObject(log)); + }); + } + }); + // Get log from outer context + conduit.onDownstream(connect.EventType.LOG, function (log) { + if (connect.isFramed() && log.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(log)); + } + }); + // Reload the page if the shared worker detects an API auth failure. + conduit.onUpstream(connect.EventType.AUTH_FAIL, function (logEntry) { + location.reload(); + }); + connect.getLog().info("User Agent: " + navigator.userAgent).sendInternalLogToServer(); + connect.getLog().info("isCCPv2: " + true).sendInternalLogToServer(); + connect.getLog().info("isFramed: " + connect.isFramed()).sendInternalLogToServer(); + connect.core.upstream.onDownstream(connect.EventType.OUTER_CONTEXT_INFO, function (data) { + var streamsVersion = data.streamsVersion; + connect.getLog().info("StreamsJS Version: " + streamsVersion).sendInternalLogToServer(); + }); + conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { + connect.getLog().info("Number of connected CCPs updated: " + data.length).sendInternalLogToServer(); + connect.numberOfConnectedCCPs = data.length; + }); + connect.core.client = new connect.UpstreamConduitClient(conduit); + connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); + + // Pass the TERMINATE request upstream to the shared worker. + connect.core.getEventBus().subscribe(connect.EventType.TERMINATE, conduit.passUpstream()); + + // Refresh the page when we receive the TERMINATED response from the + // shared worker. + connect.core.getEventBus().subscribe(connect.EventType.TERMINATED, function () { + window.location.reload(true); + }); + worker.port.start(); + conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { + if (data && data.domainId) { + connect.core.voiceIdDomainId = data.domainId; + } + }); + + // try fetching voiceId's domainId once the agent is initialized + connect.agent(function () { + var voiceId = new connect.VoiceId(); + voiceId.getDomainId().then(function (domainId) { + connect.getLog().info("voiceId domainId successfully fetched at agent initialization: " + domainId).sendInternalLogToServer(); + })["catch"](function (err) { + connect.getLog().info("voiceId domainId not fetched at agent initialization").withObject({ + err: err + }).sendInternalLogToServer(); + }); + }); + + // Attempt to get permission to show notifications. + var nm = connect.core.getNotificationManager(); + nm.requestPermission(); + } catch (e) { + connect.getLog().error("Failed to initialize the API shared worker, we're dead!").withException(e).sendInternalLogToServer(); + } + }; + connect.core._getCCPIframe = function () { + var _iterator = _createForOfIteratorHelper(window.document.getElementsByTagName('iframe')), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var iframe = _step.value; + if (iframe.name === CCP_IFRAME_NAME) { + return iframe; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return null; + }; + + /**------------------------------------------------------------------------- + * Initializes Connect by creating or connecting to the API Shared Worker. + * Initializes Connect by loading the CCP in an iframe and connecting to it. + */ + connect.core.initCCP = function (containerDiv, paramsIn) { + connect.core.checkNotInitialized(); + if (connect.core.initialized) { + return; + } + + // For backwards compatibility, when instead of taking a params object + // as input we only accepted ccpUrl. + var params = {}; + if (typeof paramsIn === 'string') { + params.ccpUrl = paramsIn; + } else { + params = paramsIn; + } + connect.assertNotNull(containerDiv, 'containerDiv'); + connect.assertNotNull(params.ccpUrl, 'params.ccpUrl'); + connect.storageAccess.init(params.ccpUrl, containerDiv, params.storageAccess || {}); + + // Create the CCP iframe and append it to the container div. + var iframe = document.createElement('iframe'); + iframe.src = params.ccpUrl; + iframe.allow = "microphone; autoplay"; + iframe.style = "width: 100%; height: 100%"; + iframe.title = 'Amazon Connect CCP'; + iframe.name = CCP_IFRAME_NAME; + + //for Storage Access follow the rsa path + if (connect.storageAccess.canRequest()) { + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + iframe.addEventListener('load', connect.storageAccess.request); + } + containerDiv.appendChild(iframe); + + // Build the upstream conduit communicating with the CCP iframe. + var conduit = new connect.IFrameConduit(params.ccpUrl, window, iframe); + + // Set the global upstream conduit for external use. + connect.core.upstream = conduit; + + // Initialize the event bus and agent data providers. + // NOTE: Setting logEvents here to FALSE in order to avoid duplicating + // events which are logged in CCP. + connect.core.eventBus = new connect.EventBus({ + logEvents: false + }); + connect.core.agentDataProvider = new AgentDataProvider(connect.core.getEventBus()); + connect.core.mediaFactory = new connect.MediaFactory(params); + if (connect.storageAccess.canRequest()) { + // Create the Iframe and load the RSA banner and append it to the container div. + connect.storageAccess.setupRequestHandlers({ + onGrant: setupInitCCP + }); + } else { + setupInitCCP(); + } + function setupInitCCP() { + // Let CCP know if iframe is visible + iframe.onload = setTimeout(function () { + var style = window.getComputedStyle(iframe, null); + var data = { + display: style.display, + offsetWidth: iframe.offsetWidth, + offsetHeight: iframe.offsetHeight, + clientRectsLength: iframe.getClientRects().length + }; + conduit.sendUpstream(connect.EventType.IFRAME_STYLE, data); + }, 10000); + + // Init webSocketProvider + connect.core.webSocketProvider = new WebSocketProvider(); + conduit.onAllUpstream(connect.core.getEventBus().bridge()); + + // Initialize the keepalive manager. + connect.core.keepaliveManager = new KeepaliveManager(conduit, connect.core.getEventBus(), params.ccpSynTimeout || CCP_SYN_TIMEOUT, params.ccpAckTimeout || CCP_ACK_TIMEOUT); + connect.core.iframeRefreshInterval = null; + + // Allow 5 sec (default) before receiving the first ACK from the CCP. + connect.core.ccpLoadTimeoutInstance = global.setTimeout(function () { + connect.core.ccpLoadTimeoutInstance = null; + connect.core.getEventBus().trigger(connect.EventType.ACK_TIMEOUT); + }, params.ccpLoadTimeout || CCP_LOAD_TIMEOUT); + connect.getLog().scheduleUpstreamOuterContextCCPLogsPush(conduit); + connect.getLog().scheduleUpstreamOuterContextCCPserverBoundLogsPush(conduit); + + // Once we receive the first ACK, setup our upstream API client and establish + // the SYN/ACK refresh flow. + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function (data) { + connect.getLog().info("Acknowledged by the CCP!").sendInternalLogToServer(); + connect.core.client = new connect.UpstreamConduitClient(conduit); + connect.core.masterClient = new connect.UpstreamConduitMasterClient(conduit); + connect.core.portStreamId = data.id; + if (params.softphone || params.chat || params.pageOptions) { + // Send configuration up to the CCP. + //set it to false if secondary + conduit.sendUpstream(connect.EventType.CONFIGURE, { + softphone: params.softphone, + chat: params.chat, + pageOptions: params.pageOptions + }); + } + if (connect.core.ccpLoadTimeoutInstance) { + global.clearTimeout(connect.core.ccpLoadTimeoutInstance); + connect.core.ccpLoadTimeoutInstance = null; + } + conduit.sendUpstream(connect.EventType.OUTER_CONTEXT_INFO, { + streamsVersion: connect.version + }); + connect.core.keepaliveManager.start(); + this.unsubscribe(); + connect.core.initialized = true; + connect.core.getEventBus().trigger(connect.EventType.INIT); + }); + + // Add any logs from the upstream to our own logger. + conduit.onUpstream(connect.EventType.LOG, function (logEntry) { + if (logEntry.loggerId !== connect.getLog().getLoggerId()) { + connect.getLog().addLogEntry(connect.LogEntry.fromObject(logEntry)); + } + }); + + // Pop a login page when we encounter an ACK timeout. + connect.core.getEventBus().subscribe(connect.EventType.ACK_TIMEOUT, function () { + // loginPopup is true by default, only false if explicitly set to false. + if (params.loginPopup !== false) { + try { + var loginUrl = getLoginUrl(params); + connect.getLog().warn("ACK_TIMEOUT occurred, attempting to pop the login page if not already open.").sendInternalLogToServer(); + // clear out last opened timestamp for SAML authentication when there is ACK_TIMEOUT + if (params.loginUrl) { + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + } + connect.core.loginWindow = connect.core.getPopupManager().open(loginUrl, connect.MasterTopics.LOGIN_POPUP, params.loginOptions); + } catch (e) { + connect.getLog().error("ACK_TIMEOUT occurred but we are unable to open the login popup.").withException(e).sendInternalLogToServer(); + } + } + if (connect.core.iframeRefreshInterval == null) { + connect.core.iframeRefreshInterval = window.setInterval(function () { + if (connect.storageAccess.canRequest()) { + iframe.removeEventListener('load', connect.storageAccess.request); + iframe.addEventListener('load', connect.storageAccess.request); + iframe.src = connect.storageAccess.getRequestStorageAccessUrl(); + } else { + iframe.src = params.ccpUrl; + } + }, CCP_IFRAME_REFRESH_INTERVAL); + conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { + this.unsubscribe(); + global.clearInterval(connect.core.iframeRefreshInterval); + connect.core.iframeRefreshInterval = null; + connect.core.getPopupManager().clear(connect.MasterTopics.LOGIN_POPUP); + if ((params.loginPopupAutoClose || params.loginOptions && params.loginOptions.autoClose) && connect.core.loginWindow) { + connect.core.loginWindow.close(); + connect.core.loginWindow = null; + } + }); + } + }); + if (params.onViewContact) { + connect.core.onViewContact(params.onViewContact); + } + conduit.onUpstream(connect.EventType.UPDATE_CONNECTED_CCPS, function (data) { + connect.numberOfConnectedCCPs = data.length; + }); + conduit.onUpstream(connect.VoiceIdEvents.UPDATE_DOMAIN_ID, function (data) { + if (data && data.domainId) { + connect.core.voiceIdDomainId = data.domainId; + } + }); + + // keep the softphone params for external use + connect.core.softphoneParams = params.softphone; + } + }; + + /**-----------------------------------------------------------------------*/ + var KeepaliveManager = function KeepaliveManager(conduit, eventBus, synTimeout, ackTimeout) { + this.conduit = conduit; + this.eventBus = eventBus; + this.synTimeout = synTimeout; + this.ackTimeout = ackTimeout; + this.ackTimer = null; + this.synTimer = null; + this.ackSub = null; + }; + KeepaliveManager.prototype.start = function () { + var self = this; + this.conduit.sendUpstream(connect.EventType.SYNCHRONIZE); + this.ackSub = this.conduit.onUpstream(connect.EventType.ACKNOWLEDGE, function () { + this.unsubscribe(); + global.clearTimeout(self.ackTimer); + self._deferStart(); + }); + this.ackTimer = global.setTimeout(function () { + self.ackSub.unsubscribe(); + self.eventBus.trigger(connect.EventType.ACK_TIMEOUT); + self._deferStart(); + }, this.ackTimeout); + }; + + //Fixes the keepalivemanager. + KeepaliveManager.prototype._deferStart = function () { + this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); + }; + + // For backwards compatibility only, in case customers are using this to start the keepalivemanager for some reason. + KeepaliveManager.prototype.deferStart = function () { + if (this.synTimer == null) { + this.synTimer = global.setTimeout(connect.hitch(this, this.start), this.synTimeout); + } + }; + + /**-----------------------------------------------------------------------*/ + + var WebSocketProvider = function WebSocketProvider() { + var callbacks = { + initFailure: new Set(), + subscriptionUpdate: new Set(), + subscriptionFailure: new Set(), + topic: new Map(), + allMessage: new Set(), + connectionGain: new Set(), + connectionLost: new Set(), + connectionOpen: new Set(), + connectionClose: new Set() + }; + var invokeCallbacks = function invokeCallbacks(callbacks, response) { + callbacks.forEach(function (callback) { + callback(response); + }); + }; + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.INIT_FAILURE, function () { + invokeCallbacks(callbacks.initFailure); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_OPEN, function (response) { + invokeCallbacks(callbacks.connectionOpen, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_CLOSE, function (response) { + invokeCallbacks(callbacks.connectionClose, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_GAIN, function () { + invokeCallbacks(callbacks.connectionGain); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.CONNECTION_LOST, function (response) { + invokeCallbacks(callbacks.connectionLost, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, function (response) { + invokeCallbacks(callbacks.subscriptionUpdate, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, function (response) { + invokeCallbacks(callbacks.subscriptionFailure, response); + }); + connect.core.getUpstream().onUpstream(connect.WebSocketEvents.ALL_MESSAGE, function (response) { + invokeCallbacks(callbacks.allMessage, response); + if (callbacks.topic.has(response.topic)) { + invokeCallbacks(callbacks.topic.get(response.topic), response); + } + }); + this.sendMessage = function (webSocketPayload) { + connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SEND, webSocketPayload); + }; + this.onInitFailure = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.initFailure.add(cb); + return function () { + return callbacks.initFailure["delete"](cb); + }; + }; + this.onConnectionOpen = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionOpen.add(cb); + return function () { + return callbacks.connectionOpen["delete"](cb); + }; + }; + this.onConnectionClose = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionClose.add(cb); + return function () { + return callbacks.connectionClose["delete"](cb); + }; + }; + this.onConnectionGain = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionGain.add(cb); + return function () { + return callbacks.connectionGain["delete"](cb); + }; + }; + this.onConnectionLost = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.connectionLost.add(cb); + return function () { + return callbacks.connectionLost["delete"](cb); + }; + }; + this.onSubscriptionUpdate = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.subscriptionUpdate.add(cb); + return function () { + return callbacks.subscriptionUpdate["delete"](cb); + }; + }; + this.onSubscriptionFailure = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.subscriptionFailure.add(cb); + return function () { + return callbacks.subscriptionFailure["delete"](cb); + }; + }; + this.subscribeTopics = function (topics) { + connect.assertNotNull(topics, 'topics'); + connect.assertTrue(connect.isArray(topics), 'topics must be a array'); + connect.core.getUpstream().sendUpstream(connect.WebSocketEvents.SUBSCRIBE, topics); + }; + this.onMessage = function (topicName, cb) { + connect.assertNotNull(topicName, 'topicName'); + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + if (callbacks.topic.has(topicName)) { + callbacks.topic.get(topicName).add(cb); + } else { + callbacks.topic.set(topicName, new Set([cb])); + } + return function () { + return callbacks.topic.get(topicName)["delete"](cb); + }; + }; + this.onAllMessage = function (cb) { + connect.assertTrue(connect.isFunction(cb), 'method must be a function'); + callbacks.allMessage.add(cb); + return function () { + return callbacks.allMessage["delete"](cb); + }; + }; + }; + + /**-----------------------------------------------------------------------*/ + var AgentDataProvider = function AgentDataProvider(bus) { + var agentData = null; + this.bus = bus; + this.bus.subscribe(connect.AgentEvents.UPDATE, connect.hitch(this, this.updateAgentData)); + }; + AgentDataProvider.prototype.updateAgentData = function (agentData) { + var oldAgentData = this.agentData; + this.agentData = agentData; + if (oldAgentData == null) { + connect.agent.initialized = true; + this.bus.trigger(connect.AgentEvents.INIT, new connect.Agent()); + } + this.bus.trigger(connect.AgentEvents.REFRESH, new connect.Agent()); + this._fireAgentUpdateEvents(oldAgentData); + }; + AgentDataProvider.prototype.getAgentData = function () { + if (this.agentData == null) { + throw new connect.StateError('No agent data is available yet!'); + } + return this.agentData; + }; + AgentDataProvider.prototype.getContactData = function (contactId) { + var agentData = this.getAgentData(); + var contactData = connect.find(agentData.snapshot.contacts, function (ctdata) { + return ctdata.contactId === contactId; + }); + if (contactData == null) { + throw new connect.StateError('Contact %s no longer exists.', contactId); + } + return contactData; + }; + AgentDataProvider.prototype.getConnectionData = function (contactId, connectionId) { + var contactData = this.getContactData(contactId); + var connectionData = connect.find(contactData.connections, function (cdata) { + return cdata.connectionId === connectionId; + }); + if (connectionData == null) { + throw new connect.StateError('Connection %s for contact %s no longer exists.', connectionId, contactId); + } + return connectionData; + }; + AgentDataProvider.prototype.getInstanceId = function () { + return this.getAgentData().configuration.routingProfile.routingProfileId.match(/instance\/([0-9a-fA-F|-]+)\//)[1]; + }; + AgentDataProvider.prototype.getAWSAccountId = function () { + return this.getAgentData().configuration.routingProfile.routingProfileId.match(/:([0-9]+):instance/)[1]; + }; + AgentDataProvider.prototype._diffContacts = function (oldAgentData) { + var diff = { + added: {}, + removed: {}, + common: {}, + oldMap: connect.index(oldAgentData == null ? [] : oldAgentData.snapshot.contacts, function (contact) { + return contact.contactId; + }), + newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }) + }; + connect.keys(diff.oldMap).forEach(function (contactId) { + if (connect.contains(diff.newMap, contactId)) { + diff.common[contactId] = diff.newMap[contactId]; + } else { + diff.removed[contactId] = diff.oldMap[contactId]; + } + }); + connect.keys(diff.newMap).forEach(function (contactId) { + if (!connect.contains(diff.oldMap, contactId)) { + diff.added[contactId] = diff.newMap[contactId]; + } + }); + return diff; + }; + AgentDataProvider.prototype._fireAgentUpdateEvents = function (oldAgentData) { + var self = this; + var diff = null; + var oldAgentState = oldAgentData == null ? connect.AgentAvailStates.INIT : oldAgentData.snapshot.state.name; + var newAgentState = this.agentData.snapshot.state.name; + var oldRoutingState = oldAgentData == null ? connect.AgentStateType.INIT : oldAgentData.snapshot.state.type; + var newRoutingState = this.agentData.snapshot.state.type; + if (oldRoutingState !== newRoutingState) { + connect.core.getAgentRoutingEventGraph().getAssociations(this, oldRoutingState, newRoutingState).forEach(function (event) { + self.bus.trigger(event, new connect.Agent()); + }); + } + if (oldAgentState !== newAgentState) { + this.bus.trigger(connect.AgentEvents.STATE_CHANGE, { + agent: new connect.Agent(), + oldState: oldAgentState, + newState: newAgentState + }); + connect.core.getAgentStateEventGraph().getAssociations(this, oldAgentState, newAgentState).forEach(function (event) { + self.bus.trigger(event, new connect.Agent()); + }); + } + var oldNextState = oldAgentData && oldAgentData.snapshot.nextState ? oldAgentData.snapshot.nextState.name : null; + var newNextState = this.agentData.snapshot.nextState ? this.agentData.snapshot.nextState.name : null; + if (oldNextState !== newNextState && newNextState) { + self.bus.trigger(connect.AgentEvents.ENQUEUED_NEXT_STATE, new connect.Agent()); + } + if (oldAgentData !== null) { + diff = this._diffContacts(oldAgentData); + } else { + diff = { + added: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }), + removed: {}, + common: {}, + oldMap: {}, + newMap: connect.index(this.agentData.snapshot.contacts, function (contact) { + return contact.contactId; + }) + }; + } + connect.values(diff.added).forEach(function (contactData) { + self.bus.trigger(connect.ContactEvents.INIT, new connect.Contact(contactData.contactId)); + self._fireContactUpdateEvents(contactData.contactId, connect.ContactStateType.INIT, contactData.state.type); + }); + connect.values(diff.removed).forEach(function (contactData) { + self.bus.trigger(connect.ContactEvents.DESTROYED, new connect.ContactSnapshot(contactData)); + self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.DESTROYED, contactData.contactId), new connect.ContactSnapshot(contactData)); + self._unsubAllContactEventsForContact(contactData.contactId); + }); + connect.keys(diff.common).forEach(function (contactId) { + self._fireContactUpdateEvents(contactId, diff.oldMap[contactId].state.type, diff.newMap[contactId].state.type); + }); + }; + AgentDataProvider.prototype._fireContactUpdateEvents = function (contactId, oldContactState, newContactState) { + var self = this; + if (oldContactState !== newContactState) { + connect.core.getContactEventGraph().getAssociations(this, oldContactState, newContactState).forEach(function (event) { + self.bus.trigger(event, new connect.Contact(contactId)); + self.bus.trigger(connect.core.getContactEventName(event, contactId), new connect.Contact(contactId)); + }); + } + self.bus.trigger(connect.ContactEvents.REFRESH, new connect.Contact(contactId)); + self.bus.trigger(connect.core.getContactEventName(connect.ContactEvents.REFRESH, contactId), new connect.Contact(contactId)); + }; + AgentDataProvider.prototype._unsubAllContactEventsForContact = function (contactId) { + var self = this; + connect.values(connect.ContactEvents).forEach(function (eventName) { + self.bus.getSubscriptions(connect.core.getContactEventName(eventName, contactId)).map(function (sub) { + sub.unsubscribe(); + }); + }); + }; + + /** ----- minimal view layer event handling **/ + + connect.core.onViewContact = function (f) { + connect.core.getUpstream().onUpstream(connect.ContactEvents.VIEW, f); + }; + + /** + * Used of agent interface control. + * connect.core.viewContact("contactId") -> this is curently programmed to get the contact into view. + */ + connect.core.viewContact = function (contactId) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.VIEW, + data: { + contactId: contactId + } + }); + }; + + /** ----- minimal view layer event handling **/ + + connect.core.onActivateChannelWithViewType = function (f) { + connect.core.getUpstream().onUpstream(connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, f); + }; + + /** + * Used of agent interface control. + * connect.core.activateChannelWithViewType() -> this is curently programmed to get either the number pad, quick connects, or create task into view. + * the valid combinations are ("create_task", "task"), ("number_pad", "softphone"), ("create_task", "softphone"), ("quick_connects", "softphone") + * the softphone with create_task combo is a special case in the channel view to allow all three view type buttons to appear on the softphone screen + * + * The 'source' is an optional parameter which indicates the requester. For example, if invoked with ("create_task", "task", "agentapp") we would know agentapp requested open task view. + */ + connect.core.activateChannelWithViewType = function (viewType, mediaType, source) { + var data = { + viewType: viewType, + mediaType: mediaType + }; + if (source) { + data.source = source; + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ChannelViewEvents.ACTIVATE_CHANNEL_WITH_VIEW_TYPE, + data: data + }); + }; + + /** + * Used to publish 'task created' event + */ + connect.core.triggerTaskCreated = function (data) { + connect.core.getUpstream().upstreamBus.trigger(connect.TaskEvents.CREATED, data); + }; + + /** ------------------------------------------------- */ + + /** + * This will be helpful for the custom and embedded CCPs + * to handle the access denied use case. + */ + connect.core.onAccessDenied = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.ACCESS_DENIED, f); + }; + + /** + * This will be helpful for SAML use cases to handle the custom logins. + */ + connect.core.onAuthFail = function (f) { + connect.core.getUpstream().onUpstream(connect.EventType.AUTH_FAIL, f); + }; + + /** ------------------------------------------------- */ + + /** + * Used for handling the rtc session stats. + * Usage + * connect.core.onSoftphoneSessionInit(function({ connectionId }) { + * var softphoneManager = connect.core.getSoftphoneManager(); + * if(softphoneManager){ + * // access session + * var session = softphoneManager.getSession(connectionId); + * } + * }); + */ + + connect.core.onSoftphoneSessionInit = function (f) { + connect.core.getUpstream().onUpstream(connect.ConnectionEvents.SESSION_INIT, f); + }; + + /**-----------------------------------------------------------------------*/ + connect.core.onConfigure = function (f) { + connect.core.getUpstream().onUpstream(connect.ConfigurationEvents.CONFIGURE, f); + }; + + /**-----------------------------------------------------------------------*/ + connect.core.onInitialized = function (f) { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.INIT, f); + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getContactEventName = function (eventName, contactId) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(contactId, 'contactId'); + if (!connect.contains(connect.values(connect.ContactEvents), eventName)) { + throw new connect.ValueError('%s is not a valid contact event.', eventName); + } + return connect.sprintf('%s::%s', eventName, contactId); + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getEventBus = function () { + return connect.core.eventBus; + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getWebSocketManager = function () { + return connect.core.webSocketProvider; + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getAgentDataProvider = function () { + return connect.core.agentDataProvider; + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getLocalTimestamp = function () { + return connect.core.getAgentDataProvider().getAgentData().snapshot.localTimestamp; + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getSkew = function () { + return connect.core.getAgentDataProvider().getAgentData().snapshot.skew; + }; + + /**-----------------------------------------------------------------------*/ + connect.core.getAgentRoutingEventGraph = function () { + return connect.core.agentRoutingEventGraph; + }; + connect.core.agentRoutingEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.AgentStateType.ROUTABLE, connect.AgentEvents.ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.NOT_ROUTABLE, connect.AgentEvents.NOT_ROUTABLE).assoc(connect.EventGraph.ANY, connect.AgentStateType.OFFLINE, connect.AgentEvents.OFFLINE); + + /**-----------------------------------------------------------------------*/ + connect.core.getAgentStateEventGraph = function () { + return connect.core.agentStateEventGraph; + }; + connect.core.agentStateEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.AgentEvents.ERROR).assoc(connect.EventGraph.ANY, connect.AgentAvailStates.AFTER_CALL_WORK, connect.AgentEvents.ACW); + + /**-----------------------------------------------------------------------*/ + connect.core.getContactEventGraph = function () { + return connect.core.contactEventGraph; + }; + connect.core.contactEventGraph = new connect.EventGraph().assoc(connect.EventGraph.ANY, connect.ContactStateType.INCOMING, connect.ContactEvents.INCOMING).assoc(connect.EventGraph.ANY, connect.ContactStateType.PENDING, connect.ContactEvents.PENDING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTING, connect.ContactEvents.CONNECTING).assoc(connect.EventGraph.ANY, connect.ContactStateType.CONNECTED, connect.ContactEvents.CONNECTED).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.ContactStateType.INCOMING, connect.ContactStateType.ERROR, connect.ContactEvents.MISSED).assoc(connect.EventGraph.ANY, connect.ContactStateType.ENDED, connect.ContactEvents.ACW).assoc(connect.values(connect.CONTACT_ACTIVE_STATES), connect.values(connect.relativeComplement(connect.CONTACT_ACTIVE_STATES, connect.ContactStateType)), connect.ContactEvents.ENDED).assoc(connect.EventGraph.ANY, connect.values(connect.AgentErrorStates), connect.ContactEvents.ERROR).assoc(connect.ContactStateType.CONNECTING, connect.ContactStateType.MISSED, connect.ContactEvents.MISSED); + + /**-----------------------------------------------------------------------*/ + connect.core.getClient = function () { + if (!connect.core.client) { + throw new connect.StateError('The connect core has not been initialized!'); + } + return connect.core.client; + }; + connect.core.client = null; + + /**-----------------------------------------------------------------------*/ + connect.core.getAgentAppClient = function () { + if (!connect.core.agentAppClient) { + throw new connect.StateError('The connect AgentApp Client has not been initialized!'); + } + return connect.core.agentAppClient; + }; + connect.core.agentAppClient = null; + + /**-----------------------------------------------------------------------*/ + connect.core.getMasterClient = function () { + if (!connect.core.masterClient) { + throw new connect.StateError('The connect master client has not been initialized!'); + } + return connect.core.masterClient; + }; + connect.core.masterClient = null; + + /**-----------------------------------------------------------------------*/ + connect.core.getSoftphoneManager = function () { + return connect.core.softphoneManager; + }; + connect.core.softphoneManager = null; + + /**-----------------------------------------------------------------------*/ + connect.core.getNotificationManager = function () { + if (!connect.core.notificationManager) { + connect.core.notificationManager = new connect.NotificationManager(); + } + return connect.core.notificationManager; + }; + connect.core.notificationManager = null; + + /**-----------------------------------------------------------------------*/ + connect.core.getPopupManager = function () { + return connect.core.popupManager; + }; + connect.core.popupManager = new connect.PopupManager(); + + /**-----------------------------------------------------------------------*/ + connect.core.getUpstream = function () { + if (!connect.core.upstream) { + throw new connect.StateError('There is no upstream conduit!'); + } + return connect.core.upstream; + }; + connect.core.upstream = null; + + /**-----------------------------------------------------------------------*/ + connect.core.AgentDataProvider = AgentDataProvider; +})(); - /** - * Add a stream to the multiplexer. - */ - StreamMultiplexer.prototype.addStream = function (stream) { - var self = this; - this.streamMap[stream.getId()] = stream; +/***/ }), - // Update stream with existing listeners. - this.messageListeners.forEach(function (messageListener) { - stream.onMessage(messageListener); - }); - }; +/***/ 547: +/***/ (() => { - /** - * Remove the given downstream. This is typically used in response - * to the SharedWorker's onclose event, indicating that a consumer - * tab has been closed. - */ - StreamMultiplexer.prototype.removeStream = function (stream) { - delete this.streamMap[stream.getId()]; - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + var ALL_EVENTS = '<>'; + + /**--------------------------------------------------------------- + * enum EventType + */ + var EventType = connect.makeEnum(['acknowledge', 'ack_timeout', 'init', 'api_request', 'api_response', 'auth_fail', 'access_denied', 'close', 'configure', 'log', 'master_request', 'master_response', 'synchronize', 'terminate', 'terminated', 'send_logs', 'reload_agent_configuration', 'broadcast', 'api_metric', 'client_metric', 'softphone_stats', 'softphone_report', 'client_side_logs', 'server_bound_internal_log', 'mute', "iframe_style", "update_connected_ccps", "outer_context_info", "media_device_request", "media_device_response"]); + + /**--------------------------------------------------------------- + * enum MasterTopics + */ + var MasterTopics = connect.makeNamespacedEnum('connect', ['loginPopup', 'sendLogs', 'softphone', 'ringtone', 'metrics']); + + /**--------------------------------------------------------------- + * enum AgentEvents + */ + var AgentEvents = connect.makeNamespacedEnum('agent', ['init', 'update', 'refresh', 'routable', 'not_routable', 'pending', 'contact_pending', 'offline', 'error', 'softphone_error', 'websocket_connection_lost', 'websocket_connection_gained', 'state_change', 'acw', 'mute_toggle', 'local_media_stream_created', 'enqueued_next_state']); + + /**--------------------------------------------------------------- + * enum WebSocketEvents + */ + var WebSocketEvents = connect.makeNamespacedEnum('webSocket', ['init_failure', 'connection_open', 'connection_close', 'connection_error', 'connection_gain', 'connection_lost', 'subscription_update', 'subscription_failure', 'all_message', 'send', 'subscribe']); + + /**--------------------------------------------------------------- + * enum ContactEvents + */ + var ContactEvents = connect.makeNamespacedEnum('contact', ['init', 'refresh', 'destroyed', 'incoming', 'pending', 'connecting', 'connected', 'missed', 'acw', 'view', 'ended', 'error', 'accepted']); + var ChannelViewEvents = connect.makeNamespacedEnum('taskList', ['activate_channel_with_view_type']); + var TaskEvents = connect.makeNamespacedEnum('task', ['created']); + + /**--------------------------------------------------------------- + * enum ConnectionEvents + */ + var ConnectionEvents = connect.makeNamespacedEnum('connection', ['session_init', 'ready_to_start_session']); + + /**--------------------------------------------------------------- + * enum Configuration Events + */ + var ConfigurationEvents = connect.makeNamespacedEnum('configuration', ['configure', 'set_speaker_device', 'set_microphone_device', 'set_ringer_device', 'speaker_device_changed', 'microphone_device_changed', 'ringer_device_changed']); + + /**--------------------------------------------------------------- + * enum VoiceId Events + */ + var VoiceIdEvents = connect.makeNamespacedEnum('voiceId', ['update_domain_id']); + + /**--------------------------------------------------------------- + * class EventFactory + */ + var EventFactory = function EventFactory() {}; + EventFactory.createRequest = function (type, method, params) { + return { + event: type, + requestId: connect.randomId(), + method: method, + params: params + }; + }; + EventFactory.createResponse = function (type, request, data, err) { + return { + event: type, + requestId: request.requestId, + data: data, + err: err || null + }; + }; + + /** + * An object representing an event subscription in an EventBus. + */ + var Subscription = function Subscription(subMap, eventName, f) { + this.subMap = subMap; + this.id = connect.randomId(); + this.eventName = eventName; + this.f = f; + }; + + /** + * Unsubscribe the handler of this subscription from the EventBus + * from which it was created. + */ + Subscription.prototype.unsubscribe = function () { + this.subMap.unsubscribe(this.eventName, this.id); + }; + + /** + * A map of event subscriptions, used by the EventBus. + */ + var SubscriptionMap = function SubscriptionMap() { + this.subIdMap = {}; + this.subEventNameMap = {}; + }; + + /** + * Add a subscription for the named event. Creates a new Subscription + * object and returns it. This object can be used to unsubscribe. + */ + SubscriptionMap.prototype.subscribe = function (eventName, f) { + var sub = new Subscription(this, eventName, f); + this.subIdMap[sub.id] = sub; + var subList = this.subEventNameMap[eventName] || []; + subList.push(sub); + this.subEventNameMap[eventName] = subList; + return sub; + }; + + /** + * Unsubscribe a subscription matching the given event name and id. + */ + SubscriptionMap.prototype.unsubscribe = function (eventName, subId) { + if (connect.contains(this.subEventNameMap, eventName)) { + this.subEventNameMap[eventName] = this.subEventNameMap[eventName].filter(function (s) { + return s.id !== subId; + }); + if (this.subEventNameMap[eventName].length < 1) { + delete this.subEventNameMap[eventName]; + } + } + if (connect.contains(this.subIdMap, subId)) { + delete this.subIdMap[subId]; + } + }; + + /** + * Get a list of all subscriptions in the subscription map. + */ + SubscriptionMap.prototype.getAllSubscriptions = function () { + return connect.values(this.subEventNameMap).reduce(function (a, b) { + return a.concat(b); + }, []); + }; + + /** + * Get a list of subscriptions for the given event name, or an empty + * list if there are no subscriptions. + */ + SubscriptionMap.prototype.getSubscriptions = function (eventName) { + return this.subEventNameMap[eventName] || []; + }; + + /** + * An object which maintains a map of subscriptions and serves as the + * mechanism for triggering events to be handled by subscribers. + */ + var EventBus = function EventBus(paramsIn) { + var params = paramsIn || {}; + this.subMap = new SubscriptionMap(); + this.logEvents = params.logEvents || false; + }; + + /** + * Subscribe to the named event. Returns a new Subscription object + * which can be used to unsubscribe. + */ + EventBus.prototype.subscribe = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.subMap.subscribe(eventName, f); + }; + + /** + * Subscribe a function to be called on all events. + */ + EventBus.prototype.subscribeAll = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.subMap.subscribe(ALL_EVENTS, f); + }; + + /** + * Get a list of subscriptions for the given event name, or an empty + * list if there are no subscriptions. + */ + EventBus.prototype.getSubscriptions = function (eventName) { + return this.subMap.getSubscriptions(eventName); + }; + + /** + * Trigger the given event with the given data. All methods subscribed + * to this event will be called and are provided with the given arbitrary + * data object and the name of the event, in that order. + */ + EventBus.prototype.trigger = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + var self = this; + var allEventSubs = this.subMap.getSubscriptions(ALL_EVENTS); + var eventSubs = this.subMap.getSubscriptions(eventName); + if (this.logEvents && eventName !== connect.EventType.LOG && eventName !== connect.EventType.MASTER_RESPONSE && eventName !== connect.EventType.API_METRIC && eventName !== connect.EventType.SERVER_BOUND_INTERNAL_LOG) { + connect.getLog().trace("Publishing event: %s", eventName).sendInternalLogToServer(); + } + if (eventName.startsWith(connect.ContactEvents.ACCEPTED) && data && data.contactId && !(data instanceof connect.Contact)) { + data = new connect.Contact(data.contactId); + } + allEventSubs.concat(eventSubs).forEach(function (sub) { + try { + sub.f(data || null, eventName, self); + } catch (e) { + connect.getLog().error("'%s' event handler failed.", eventName).withException(e).sendInternalLogToServer(); + } + }); + }; + + /** + * Returns a closure which bridges an event from another EventBus to this bus. + * + * Usage: + * conduit.onUpstream("MyEvent", bus.bridge()); + */ + EventBus.prototype.bridge = function () { + var self = this; + return function (data, event) { + self.trigger(event, data); + }; + }; + + /** + * Unsubscribe all events in the event bus. + */ + EventBus.prototype.unsubscribeAll = function () { + this.subMap.getAllSubscriptions().forEach(function (sub) { + sub.unsubscribe(); + }); + }; + connect.EventBus = EventBus; + connect.EventFactory = EventFactory; + connect.EventType = EventType; + connect.AgentEvents = AgentEvents; + connect.ConfigurationEvents = ConfigurationEvents; + connect.ConnectionEvents = ConnectionEvents; + connect.ConnnectionEvents = ConnectionEvents; //deprecate on next major version release. + connect.ContactEvents = ContactEvents; + connect.ChannelViewEvents = ChannelViewEvents; + connect.TaskEvents = TaskEvents; + connect.VoiceIdEvents = VoiceIdEvents; + connect.WebSocketEvents = WebSocketEvents; + connect.MasterTopics = MasterTopics; +})(); - /** - * Get a list of streams in the multiplexer. - */ - StreamMultiplexer.prototype.getStreams = function (stream) { - return connect.values(this.streamMap); - }; +/***/ }), - /** - * Get the stream matching the given port. - */ - StreamMultiplexer.prototype.getStreamForPort = function (port) { - return connect.find(this.getStreams(), function (s) { - return s.port === port; - }); - }; +/***/ 42: +/***/ (() => { - /**--------------------------------------------------------------- - * class Conduit - * - * An object which bridges an upstream and a downstream, allowing messages - * to be passed to and from each and providing an event bus for event - * subscriptions to be made upstream and downstream. - */ - var Conduit = function Conduit(name, upstream, downstream) { - this.name = name; - this.upstream = upstream || new NullStream(); - this.downstream = downstream || new NullStream(); - this.downstreamBus = new connect.EventBus(); - this.upstreamBus = new connect.EventBus(); - this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)); - this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)); - }; - Conduit.prototype.onUpstream = function (eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.upstreamBus.subscribe(eventName, f); - }; - Conduit.prototype.onAllUpstream = function (f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.upstreamBus.subscribeAll(f); - }; - Conduit.prototype.onDownstream = function (eventName, f) { - connect.assertNotNull(eventName, 'eventName'); - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.downstreamBus.subscribe(eventName, f); - }; - Conduit.prototype.onAllDownstream = function (f) { - connect.assertNotNull(f, 'f'); - connect.assertTrue(connect.isFunction(f), 'f must be a function'); - return this.downstreamBus.subscribeAll(f); - }; - Conduit.prototype.sendUpstream = function (eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - this.upstream.send({ - event: eventName, - data: data - }); - }; - Conduit.prototype.sendDownstream = function (eventName, data) { - connect.assertNotNull(eventName, 'eventName'); - this.downstream.send({ - event: eventName, - data: data - }); - }; - Conduit.prototype._dispatchEvent = function (bus, messageEvent) { - var message = messageEvent.data; - if (message.event) { - bus.trigger(message.event, message.data); +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +!function (e) { + var n = {}; + function t(o) { + if (n[o]) return n[o].exports; + var r = n[o] = { + i: o, + l: !1, + exports: {} + }; + return e[o].call(r.exports, r, r.exports, t), r.l = !0, r.exports; + } + t.m = e, t.c = n, t.d = function (e, n, o) { + t.o(e, n) || Object.defineProperty(e, n, { + enumerable: !0, + get: o + }); + }, t.r = function (e) { + "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { + value: "Module" + }), Object.defineProperty(e, "__esModule", { + value: !0 + }); + }, t.t = function (e, n) { + if (1 & n && (e = t(e)), 8 & n) return e; + if (4 & n && "object" == _typeof(e) && e && e.__esModule) return e; + var o = Object.create(null); + if (t.r(o), Object.defineProperty(o, "default", { + enumerable: !0, + value: e + }), 2 & n && "string" != typeof e) for (var r in e) t.d(o, r, function (n) { + return e[n]; + }.bind(null, r)); + return o; + }, t.n = function (e) { + var n = e && e.__esModule ? function () { + return e["default"]; + } : function () { + return e; + }; + return t.d(n, "a", n), n; + }, t.o = function (e, n) { + return Object.prototype.hasOwnProperty.call(e, n); + }, t.p = "", t(t.s = 2); +}([function (e, n, t) { + "use strict"; + + var o = t(1), + r = "NULL", + i = "CLIENT_LOGGER", + c = "DEBUG", + s = 2e3, + a = "aws/subscribe", + u = "aws/unsubscribe", + l = "aws/heartbeat", + f = "connected", + p = "disconnected"; + function d(e) { + return (d = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { + return _typeof(e); + } : function (e) { + return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); + })(e); + } + var b = { + assertTrue: function assertTrue(e, n) { + if (!e) throw new Error(n); + }, + assertNotNull: function assertNotNull(e, n) { + return b.assertTrue(null !== e && void 0 !== d(e), Object(o.sprintf)("%s must be provided", n || "A value")), e; + }, + isNonEmptyString: function isNonEmptyString(e) { + return "string" == typeof e && e.length > 0; + }, + assertIsList: function assertIsList(e, n) { + if (!Array.isArray(e)) throw new Error(n + " is not an array"); + }, + isFunction: function isFunction(e) { + return !!(e && e.constructor && e.call && e.apply); + }, + isObject: function isObject(e) { + return !("object" !== d(e) || null === e); + }, + isString: function isString(e) { + return "string" == typeof e; + }, + isNumber: function isNumber(e) { + return "number" == typeof e; + } + }, + g = new RegExp("^(wss://)\\w*"); + b.validWSUrl = function (e) { + return g.test(e); + }, b.getSubscriptionResponse = function (e, n, t) { + return { + topic: e, + content: { + status: n ? "success" : "failure", + topics: t + } + }; + }, b.assertIsObject = function (e, n) { + if (!b.isObject(e)) throw new Error(n + " is not an object!"); + }, b.addJitter = function (e) { + var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1; + n = Math.min(n, 1); + var t = Math.random() > .5 ? 1 : -1; + return Math.floor(e + t * e * Math.random() * n); + }, b.isNetworkOnline = function () { + return navigator.onLine; + }, b.isNetworkFailure = function (e) { + return !(!e._debug || !e._debug.type) && "NetworkingError" === e._debug.type; + }; + var y = b; + function m(e) { + return (m = "function" == typeof Symbol && "symbol" == _typeof(Symbol.iterator) ? function (e) { + return _typeof(e); + } : function (e) { + return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : _typeof(e); + })(e); + } + function S(e, n) { + return !n || "object" !== m(n) && "function" != typeof n ? function (e) { + if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + return e; + }(e) : n; + } + function k(e) { + return (k = Object.setPrototypeOf ? Object.getPrototypeOf : function (e) { + return e.__proto__ || Object.getPrototypeOf(e); + })(e); + } + function h(e, n) { + return (h = Object.setPrototypeOf || function (e, n) { + return e.__proto__ = n, e; + })(e, n); + } + function v(e, n) { + if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); + } + function w(e, n) { + for (var t = 0; t < n.length; t++) { + var o = n[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); + } + } + function C(e, n, t) { + return n && w(e.prototype, n), t && w(e, t), e; + } + var T = function () { + function e() { + v(this, e); + } + return C(e, [{ + key: "debug", + value: function value(e) {} + }, { + key: "info", + value: function value(e) {} + }, { + key: "warn", + value: function value(e) {} + }, { + key: "error", + value: function value(e) {} + }]), e; + }(), + O = { + DEBUG: 10, + INFO: 20, + WARN: 30, + ERROR: 40 + }, + I = function () { + function e() { + v(this, e), this.updateLoggerConfig(), this.consoleLoggerWrapper = _(); + } + return C(e, [{ + key: "writeToClientLogger", + value: function value(e, n) { + if (this.hasClientLogger()) switch (e) { + case O.DEBUG: + return this._clientLogger.debug(n); + case O.INFO: + return this._clientLogger.info(n); + case O.WARN: + return this._clientLogger.warn(n); + case O.ERROR: + return this._clientLogger.error(n); + } + } + }, { + key: "isLevelEnabled", + value: function value(e) { + return e >= this._level; + } + }, { + key: "hasClientLogger", + value: function value() { + return null !== this._clientLogger; + } + }, { + key: "getLogger", + value: function value(e) { + var n = e.prefix || ""; + return this._logsDestination === c ? this.consoleLoggerWrapper : new N(n); + } + }, { + key: "updateLoggerConfig", + value: function value(e) { + var n = e || {}; + this._level = n.level || O.DEBUG, this._clientLogger = n.logger || null, this._logsDestination = r, n.debug && (this._logsDestination = c), n.logger && (this._logsDestination = i); + } + }]), e; + }(), + W = function () { + function e() { + v(this, e); + } + return C(e, [{ + key: "debug", + value: function value() {} + }, { + key: "info", + value: function value() {} + }, { + key: "warn", + value: function value() {} + }, { + key: "error", + value: function value() {} + }]), e; + }(), + N = function (e) { + function n(e) { + var t; + return v(this, n), (t = S(this, k(n).call(this))).prefix = e || "", t; + } + return function (e, n) { + if ("function" != typeof n && null !== n) throw new TypeError("Super expression must either be null or a function"); + e.prototype = Object.create(n && n.prototype, { + constructor: { + value: e, + writable: !0, + configurable: !0 + } + }), n && h(e, n); + }(n, W), C(n, [{ + key: "debug", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.DEBUG, n); + } + }, { + key: "info", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.INFO, n); + } + }, { + key: "warn", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.WARN, n); + } + }, { + key: "error", + value: function value() { + for (var e = arguments.length, n = new Array(e), t = 0; t < e; t++) n[t] = arguments[t]; + return this._log(O.ERROR, n); + } + }, { + key: "_shouldLog", + value: function value(e) { + return E.hasClientLogger() && E.isLevelEnabled(e); + } + }, { + key: "_writeToClientLogger", + value: function value(e, n) { + return E.writeToClientLogger(e, n); + } + }, { + key: "_log", + value: function value(e, n) { + if (this._shouldLog(e)) { + var t = this._convertToSingleStatement(n); + return this._writeToClientLogger(e, t); + } + } + }, { + key: "_convertToSingleStatement", + value: function value(e) { + var n = ""; + this.prefix && (n += this.prefix + " "); + for (var t = 0; t < e.length; t++) { + var o = e[t]; + n += this._convertToString(o) + " "; + } + return n; + } + }, { + key: "_convertToString", + value: function value(e) { + try { + if (!e) return ""; + if (y.isString(e)) return e; + if (y.isObject(e) && y.isFunction(e.toString)) { + var n = e.toString(); + if ("[object Object]" !== n) return n; + } + return JSON.stringify(e); + } catch (n) { + return console.error("Error while converting argument to string", e, n), ""; + } + } + }]), n; + }(), + _ = function _() { + var e = new W(); + return e.debug = console.debug, e.info = console.info, e.warn = console.warn, e.error = console.error, e; + }, + E = new I(); + function F(e, n) { + for (var t = 0; t < n.length; t++) { + var o = n[t]; + o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, o.key, o); + } + } + var L = function () { + function e(n) { + var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : s; + !function (e, n) { + if (!(e instanceof n)) throw new TypeError("Cannot call a class as a function"); + }(this, e), this.numAttempts = 0, this.executor = n, this.hasActiveReconnection = !1, this.defaultRetry = t; + } + var n, t, o; + return n = e, (t = [{ + key: "retry", + value: function value() { + var e = this; + this.hasActiveReconnection || (this.hasActiveReconnection = !0, setTimeout(function () { + e._execute(); + }, this._getDelay())); + } + }, { + key: "_execute", + value: function value() { + this.hasActiveReconnection = !1, this.executor(), this.numAttempts++; + } + }, { + key: "connected", + value: function value() { + this.numAttempts = 0; + } + }, { + key: "_getDelay", + value: function value() { + var e = Math.pow(2, this.numAttempts) * this.defaultRetry; + return e <= 3e4 ? e : 3e4; + } + }]) && F(n.prototype, t), o && F(n, o), e; + }(); + t.d(n, "a", function () { + return R; + }); + var x = function x() { + var e = E.getLogger({}), + n = y.isNetworkOnline(), + t = { + primary: null, + secondary: null + }, + o = { + reconnectWebSocket: !0, + websocketInitFailed: !1, + exponentialBackOffTime: 1e3, + exponentialTimeoutHandle: null, + lifeTimeTimeoutHandle: null, + webSocketInitCheckerTimeoutId: null, + connState: null + }, + r = { + connectWebSocketRetryCount: 0, + connectionAttemptStartTime: null, + noOpenConnectionsTimestamp: null + }, + i = { + pendingResponse: !1, + intervalHandle: null + }, + c = { + initFailure: new Set(), + getWebSocketTransport: null, + subscriptionUpdate: new Set(), + subscriptionFailure: new Set(), + topic: new Map(), + allMessage: new Set(), + connectionGain: new Set(), + connectionLost: new Set(), + connectionOpen: new Set(), + connectionClose: new Set() + }, + s = { + connConfig: null, + promiseHandle: null, + promiseCompleted: !0 + }, + d = { + subscribed: new Set(), + pending: new Set(), + subscriptionHistory: new Set() + }, + b = { + responseCheckIntervalId: null, + requestCompleted: !0, + reSubscribeIntervalId: null, + consecutiveFailedSubscribeAttempts: 0, + consecutiveNoResponseRequest: 0 + }, + g = new L(function () { + U(); + }), + m = new Set([a, u, l]), + S = setInterval(function () { + if (n !== y.isNetworkOnline()) { + if (!(n = y.isNetworkOnline())) return void J(e.info("Network offline")); + var t = O(); + n && (!t || w(t, WebSocket.CLOSING) || w(t, WebSocket.CLOSED)) && (J(e.info("Network online, connecting to WebSocket server")), U()); + } + }, 250), + k = function k(n, t) { + n.forEach(function (n) { + try { + n(t); + } catch (n) { + J(e.error("Error executing callback", n)); } - }; - - /** - * Returns a closure which passes events upstream. - * - * Usage: - * conduit.onDownstream("MyEvent", conduit.passUpstream()); - */ - Conduit.prototype.passUpstream = function () { - var self = this; - return function (data, eventName) { - self.upstream.send({ - event: eventName, - data: data - }); - }; - }; - - /** - * Returns a closure which passes events downstream. - * - * Usage: - * conduit.onUpstream("MyEvent", conduit.passDownstream()); - */ - Conduit.prototype.passDownstream = function () { - var self = this; - return function (data, eventName) { - self.downstream.send({ - event: eventName, - data: data + }); + }, + h = function h(e) { + if (null === e) return "NULL"; + switch (e.readyState) { + case WebSocket.CONNECTING: + return "CONNECTING"; + case WebSocket.OPEN: + return "OPEN"; + case WebSocket.CLOSING: + return "CLOSING"; + case WebSocket.CLOSED: + return "CLOSED"; + default: + return "UNDEFINED"; + } + }, + v = function v() { + var n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : ""; + J(e.debug("[" + n + "] Primary WebSocket: " + h(t.primary) + " | Secondary WebSocket: " + h(t.secondary))); + }, + w = function w(e, n) { + return e && e.readyState === n; + }, + C = function C(e) { + return w(e, WebSocket.OPEN); + }, + T = function T(e) { + return null === e || void 0 === e.readyState || w(e, WebSocket.CLOSED); + }, + O = function O() { + return null !== t.secondary ? t.secondary : t.primary; + }, + I = function I() { + return C(O()); + }, + W = function W() { + if (i.pendingResponse) return J(e.warn("Heartbeat response not received")), clearInterval(i.intervalHandle), i.pendingResponse = !1, void U(); + I() ? (J(e.debug("Sending heartbeat")), O().send(G(l)), i.pendingResponse = !0) : (J(e.warn("Failed to send heartbeat since WebSocket is not open")), v("sendHeartBeat"), U()); + }, + N = function N() { + o.exponentialBackOffTime = 1e3, i.pendingResponse = !1, o.reconnectWebSocket = !0, clearTimeout(o.lifeTimeTimeoutHandle), clearInterval(i.intervalHandle), clearTimeout(o.exponentialTimeoutHandle), clearTimeout(o.webSocketInitCheckerTimeoutId); + }, + _ = function _() { + b.consecutiveFailedSubscribeAttempts = 0, b.consecutiveNoResponseRequest = 0, clearInterval(b.responseCheckIntervalId), clearInterval(b.reSubscribeIntervalId); + }, + F = function F() { + r.connectWebSocketRetryCount = 0, r.connectionAttemptStartTime = null, r.noOpenConnectionsTimestamp = null; + }, + x = function x() { + try { + J(e.info("WebSocket connection established!")), v("webSocketOnOpen"), null !== o.connState && o.connState !== p || k(c.connectionGain), o.connState = f; + var n = Date.now(); + k(c.connectionOpen, { + connectWebSocketRetryCount: r.connectWebSocketRetryCount, + connectionAttemptStartTime: r.connectionAttemptStartTime, + noOpenConnectionsTimestamp: r.noOpenConnectionsTimestamp, + connectionEstablishedTime: n, + timeToConnect: n - r.connectionAttemptStartTime, + timeWithoutConnection: r.noOpenConnectionsTimestamp ? n - r.noOpenConnectionsTimestamp : null + }), F(), N(), O().openTimestamp = Date.now(), 0 === d.subscribed.size && C(t.secondary) && D(t.primary, "[Primary WebSocket] Closing WebSocket"), (d.subscribed.size > 0 || d.pending.size > 0) && (C(t.secondary) && J(e.info("Subscribing secondary websocket to topics of primary websocket")), d.subscribed.forEach(function (e) { + d.subscriptionHistory.add(e), d.pending.add(e); + }), d.subscribed.clear(), A()), W(), i.intervalHandle = setInterval(W, 1e4); + var a = 1e3 * s.connConfig.webSocketTransport.transportLifeTimeInSeconds; + J(e.debug("Scheduling WebSocket manager reconnection, after delay " + a + " ms")), o.lifeTimeTimeoutHandle = setTimeout(function () { + J(e.debug("Starting scheduled WebSocket manager reconnection")), U(); + }, a); + } catch (n) { + J(e.error("Error after establishing WebSocket connection", n)); + } + }, + R = function R(n) { + v("webSocketOnError"), J(e.error("WebSocketManager Error, error_event: ", JSON.stringify(n))), U(); + }, + j = function j(n) { + var o = JSON.parse(n.data); + switch (o.topic) { + case a: + if (J(e.debug("Subscription Message received from webSocket server", n.data)), b.requestCompleted = !0, b.consecutiveNoResponseRequest = 0, "success" === o.content.status) b.consecutiveFailedSubscribeAttempts = 0, o.content.topics.forEach(function (e) { + d.subscriptionHistory["delete"](e), d.pending["delete"](e), d.subscribed.add(e); + }), 0 === d.subscriptionHistory.size ? C(t.secondary) && (J(e.info("Successfully subscribed secondary websocket to all topics of primary websocket")), D(t.primary, "[Primary WebSocket] Closing WebSocket")) : A(), k(c.subscriptionUpdate, o);else { + if (clearInterval(b.reSubscribeIntervalId), ++b.consecutiveFailedSubscribeAttempts, 5 === b.consecutiveFailedSubscribeAttempts) return k(c.subscriptionFailure, o), void (b.consecutiveFailedSubscribeAttempts = 0); + b.reSubscribeIntervalId = setInterval(function () { + A(); + }, 500); + } + break; + case l: + J(e.debug("Heartbeat response received")), i.pendingResponse = !1; + break; + default: + if (o.topic) { + if (J(e.debug("Message received for topic " + o.topic)), C(t.primary) && C(t.secondary) && 0 === d.subscriptionHistory.size && this === t.primary) return void J(e.warn("Ignoring Message for Topic " + o.topic + ", to avoid duplicates")); + if (0 === c.allMessage.size && 0 === c.topic.size) return void J(e.warn("No registered callback listener for Topic", o.topic)); + k(c.allMessage, o), c.topic.has(o.topic) && k(c.topic.get(o.topic), o); + } else o.message ? J(e.warn("WebSocketManager Message Error", o)) : J(e.warn("Invalid incoming message", o)); + } + }, + A = function n() { + if (b.consecutiveNoResponseRequest > 3) return J(e.warn("Ignoring subscribePendingTopics since we have exhausted max subscription retries with no response")), void k(c.subscriptionFailure, y.getSubscriptionResponse(a, !1, Array.from(d.pending))); + I() ? (clearInterval(b.responseCheckIntervalId), O().send(G(a, { + topics: Array.from(d.pending) + })), b.requestCompleted = !1, b.responseCheckIntervalId = setInterval(function () { + b.requestCompleted || (++b.consecutiveNoResponseRequest, n()); + }, 1e3)) : J(e.warn("Ignoring subscribePendingTopics call since Default WebSocket is not open")); + }, + D = function D(n, t) { + w(n, WebSocket.CONNECTING) || w(n, WebSocket.OPEN) ? n.close(1e3, t) : J(e.warn("Ignoring WebSocket Close request, WebSocket State: " + h(n))); + }, + M = function M(e) { + D(t.primary, "[Primary] WebSocket " + e), D(t.secondary, "[Secondary] WebSocket " + e); + }, + P = function P() { + r.connectWebSocketRetryCount++; + var n = y.addJitter(o.exponentialBackOffTime, .3); + Date.now() + n <= s.connConfig.urlConnValidTime ? (J(e.debug("Scheduling WebSocket reinitialization, after delay " + n + " ms")), o.exponentialTimeoutHandle = setTimeout(function () { + return q(); + }, n), o.exponentialBackOffTime *= 2) : (J(e.warn("WebSocket URL cannot be used to establish connection")), U()); + }, + H = function H(n) { + N(), _(), J(e.error("WebSocket Initialization failed")), o.websocketInitFailed = !0, M("Terminating WebSocket Manager"), clearInterval(S), k(c.initFailure, { + connectWebSocketRetryCount: r.connectWebSocketRetryCount, + connectionAttemptStartTime: r.connectionAttemptStartTime, + reason: n + }), F(); + }, + G = function G(e, n) { + return JSON.stringify({ + topic: e, + content: n + }); + }, + z = function z(n) { + return !!(y.isObject(n) && y.isObject(n.webSocketTransport) && y.isNonEmptyString(n.webSocketTransport.url) && y.validWSUrl(n.webSocketTransport.url) && 1e3 * n.webSocketTransport.transportLifeTimeInSeconds >= 3e5) || (J(e.error("Invalid WebSocket Connection Configuration", n)), !1); + }, + U = function U() { + if (y.isNetworkOnline()) { + if (o.websocketInitFailed) J(e.debug("WebSocket Init had failed, ignoring this getWebSocketConnConfig request"));else { + if (s.promiseCompleted) return N(), J(e.info("Fetching new WebSocket connection configuration")), r.connectionAttemptStartTime = r.connectionAttemptStartTime || Date.now(), s.promiseCompleted = !1, s.promiseHandle = c.getWebSocketTransport(), s.promiseHandle.then(function (n) { + return s.promiseCompleted = !0, J(e.debug("Successfully fetched webSocket connection configuration", n)), z(n) ? (s.connConfig = n, s.connConfig.urlConnValidTime = Date.now() + 85e3, g.connected(), q()) : (H("Invalid WebSocket connection configuration: " + n), { + webSocketConnectionFailed: !0 + }); + }, function (n) { + return s.promiseCompleted = !0, J(e.error("Failed to fetch webSocket connection configuration", n)), y.isNetworkFailure(n) ? (J(e.info("Retrying fetching new WebSocket connection configuration")), g.retry()) : H("Failed to fetch webSocket connection configuration: " + JSON.stringify(n)), { + webSocketConnectionFailed: !0 + }; }); - }; - }; - - /** - * Shutdown the conduit's event busses and remove all subscriptions. - */ - Conduit.prototype.shutdown = function () { - this.upstreamBus.unsubscribeAll(); - this.downstreamBus.unsubscribeAll(); + J(e.debug("There is an ongoing getWebSocketConnConfig request, this request will be ignored")); + } + } else J(e.info("Network offline, ignoring this getWebSocketConnConfig request")); + }, + q = function q() { + if (o.websocketInitFailed) return J(e.info("web-socket initializing had failed, aborting re-init")), { + webSocketConnectionFailed: !0 }; - - /**--------------------------------------------------------------- - * class IFrameConduit extends Conduit - * - * Creates a conduit for the given IFrame element. - */ - var IFrameConduit = function IFrameConduit(name, window, iframe, domain) { - Conduit.call(this, name, new WindowIOStream(window, iframe.contentWindow, domain || '*'), null); + if (!y.isNetworkOnline()) return J(e.warn("System is offline aborting web-socket init")), { + webSocketConnectionFailed: !0 }; - IFrameConduit.prototype = Object.create(Conduit.prototype); - IFrameConduit.prototype.constructor = IFrameConduit; - connect.Stream = Stream; - connect.NullStream = NullStream; - connect.WindowStream = WindowStream; - connect.WindowIOStream = WindowIOStream; - connect.PortStream = PortStream; - connect.StreamMultiplexer = StreamMultiplexer; - connect.Conduit = Conduit; - connect.IFrameConduit = IFrameConduit; - })(); - - /***/ -}), + J(e.info("Initializing Websocket Manager")), v("initWebSocket"); + try { + if (z(s.connConfig)) { + var n = null; + return C(t.primary) ? (J(e.debug("Primary Socket connection is already open")), w(t.secondary, WebSocket.CONNECTING) || (J(e.debug("Establishing a secondary web-socket connection")), t.secondary = B()), n = t.secondary) : (w(t.primary, WebSocket.CONNECTING) || (J(e.debug("Establishing a primary web-socket connection")), t.primary = B()), n = t.primary), o.webSocketInitCheckerTimeoutId = setTimeout(function () { + C(n) || P(); + }, 1e3), { + webSocketConnectionFailed: !1 + }; + } + } catch (n) { + return J(e.error("Error Initializing web-socket-manager", n)), H("Failed to initialize new WebSocket: " + n.message), { + webSocketConnectionFailed: !0 + }; + } + }, + B = function B() { + var n = new WebSocket(s.connConfig.webSocketTransport.url); + return n.addEventListener("open", x), n.addEventListener("message", j), n.addEventListener("error", R), n.addEventListener("close", function (i) { + return function (n, i) { + J(e.info("Socket connection is closed", n)), v("webSocketOnClose before-cleanup"), k(c.connectionClose, { + openTimestamp: i.openTimestamp, + closeTimestamp: Date.now(), + connectionDuration: Date.now() - i.openTimestamp, + code: n.code, + reason: n.reason + }), T(t.primary) && (t.primary = null), T(t.secondary) && (t.secondary = null), o.reconnectWebSocket && (C(t.primary) || C(t.secondary) ? T(t.primary) && C(t.secondary) && (J(e.info("[Primary] WebSocket Cleanly Closed")), t.primary = t.secondary, t.secondary = null) : (J(e.warn("Neither primary websocket and nor secondary websocket have open connections, attempting to re-establish connection")), o.connState === p ? J(e.info("Ignoring connectionLost callback invocation")) : (k(c.connectionLost, { + openTimestamp: i.openTimestamp, + closeTimestamp: Date.now(), + connectionDuration: Date.now() - i.openTimestamp, + code: n.code, + reason: n.reason + }), r.noOpenConnectionsTimestamp = Date.now()), o.connState = p, U()), v("webSocketOnClose after-cleanup")); + }(i, n); + }), n; + }, + J = function J(e) { + return e && "function" == typeof e.sendInternalLogToServer && e.sendInternalLogToServer(), e; + }; + this.init = function (n) { + if (y.assertTrue(y.isFunction(n), "transportHandle must be a function"), null === c.getWebSocketTransport) return c.getWebSocketTransport = n, U(); + J(e.warn("Web Socket Manager was already initialized")); + }, this.onInitFailure = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.initFailure.add(e), o.websocketInitFailed && e(), function () { + return c.initFailure["delete"](e); + }; + }, this.onConnectionOpen = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionOpen.add(e), function () { + return c.connectionOpen["delete"](e); + }; + }, this.onConnectionClose = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionClose.add(e), function () { + return c.connectionClose["delete"](e); + }; + }, this.onConnectionGain = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionGain.add(e), I() && e(), function () { + return c.connectionGain["delete"](e); + }; + }, this.onConnectionLost = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.connectionLost.add(e), o.connState === p && e(), function () { + return c.connectionLost["delete"](e); + }; + }, this.onSubscriptionUpdate = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.subscriptionUpdate.add(e), function () { + return c.subscriptionUpdate["delete"](e); + }; + }, this.onSubscriptionFailure = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.subscriptionFailure.add(e), function () { + return c.subscriptionFailure["delete"](e); + }; + }, this.onMessage = function (e, n) { + return y.assertNotNull(e, "topicName"), y.assertTrue(y.isFunction(n), "cb must be a function"), c.topic.has(e) ? c.topic.get(e).add(n) : c.topic.set(e, new Set([n])), function () { + return c.topic.get(e)["delete"](n); + }; + }, this.onAllMessage = function (e) { + return y.assertTrue(y.isFunction(e), "cb must be a function"), c.allMessage.add(e), function () { + return c.allMessage["delete"](e); + }; + }, this.subscribeTopics = function (e) { + y.assertNotNull(e, "topics"), y.assertIsList(e), e.forEach(function (e) { + d.subscribed.has(e) || d.pending.add(e); + }), b.consecutiveNoResponseRequest = 0, A(); + }, this.sendMessage = function (n) { + if (y.assertIsObject(n, "payload"), void 0 === n.topic || m.has(n.topic)) J(e.warn("Cannot send message, Invalid topic", n));else { + try { + n = JSON.stringify(n); + } catch (t) { + return void J(e.warn("Error stringify message", n)); + } + I() ? O().send(n) : J(e.warn("Cannot send message, web socket connection is not open")); + } + }, this.closeWebSocket = function () { + N(), _(), o.reconnectWebSocket = !1, clearInterval(S), M("User request to close WebSocket"); + }, this.terminateWebSocketManager = H; + }, + R = { + create: function create() { + return new x(); + }, + setGlobalConfig: function setGlobalConfig(e) { + var n = e.loggerConfig; + E.updateLoggerConfig(n); + }, + LogLevel: O, + Logger: T + }; +}, function (e, n, t) { + var o; + !function () { + "use strict"; + + var r = { + not_string: /[^s]/, + not_bool: /[^t]/, + not_type: /[^T]/, + not_primitive: /[^v]/, + number: /[diefg]/, + numeric_arg: /[bcdiefguxX]/, + json: /[j]/, + not_json: /[^j]/, + text: /^[^\x25]+/, + modulo: /^\x25{2}/, + placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/, + key: /^([a-z_][a-z_\d]*)/i, + key_access: /^\.([a-z_][a-z_\d]*)/i, + index_access: /^\[(\d+)\]/, + sign: /^[+-]/ + }; + function i(e) { + return function (e, n) { + var t, + o, + c, + s, + a, + u, + l, + f, + p, + d = 1, + b = e.length, + g = ""; + for (o = 0; o < b; o++) if ("string" == typeof e[o]) g += e[o];else if ("object" == _typeof(e[o])) { + if ((s = e[o]).keys) for (t = n[d], c = 0; c < s.keys.length; c++) { + if (null == t) throw new Error(i('[sprintf] Cannot access property "%s" of undefined value "%s"', s.keys[c], s.keys[c - 1])); + t = t[s.keys[c]]; + } else t = s.param_no ? n[s.param_no] : n[d++]; + if (r.not_type.test(s.type) && r.not_primitive.test(s.type) && t instanceof Function && (t = t()), r.numeric_arg.test(s.type) && "number" != typeof t && isNaN(t)) throw new TypeError(i("[sprintf] expecting number but found %T", t)); + switch (r.number.test(s.type) && (f = t >= 0), s.type) { + case "b": + t = parseInt(t, 10).toString(2); + break; + case "c": + t = String.fromCharCode(parseInt(t, 10)); + break; + case "d": + case "i": + t = parseInt(t, 10); + break; + case "j": + t = JSON.stringify(t, null, s.width ? parseInt(s.width) : 0); + break; + case "e": + t = s.precision ? parseFloat(t).toExponential(s.precision) : parseFloat(t).toExponential(); + break; + case "f": + t = s.precision ? parseFloat(t).toFixed(s.precision) : parseFloat(t); + break; + case "g": + t = s.precision ? String(Number(t.toPrecision(s.precision))) : parseFloat(t); + break; + case "o": + t = (parseInt(t, 10) >>> 0).toString(8); + break; + case "s": + t = String(t), t = s.precision ? t.substring(0, s.precision) : t; + break; + case "t": + t = String(!!t), t = s.precision ? t.substring(0, s.precision) : t; + break; + case "T": + t = Object.prototype.toString.call(t).slice(8, -1).toLowerCase(), t = s.precision ? t.substring(0, s.precision) : t; + break; + case "u": + t = parseInt(t, 10) >>> 0; + break; + case "v": + t = t.valueOf(), t = s.precision ? t.substring(0, s.precision) : t; + break; + case "x": + t = (parseInt(t, 10) >>> 0).toString(16); + break; + case "X": + t = (parseInt(t, 10) >>> 0).toString(16).toUpperCase(); + } + r.json.test(s.type) ? g += t : (!r.number.test(s.type) || f && !s.sign ? p = "" : (p = f ? "+" : "-", t = t.toString().replace(r.sign, "")), u = s.pad_char ? "0" === s.pad_char ? "0" : s.pad_char.charAt(1) : " ", l = s.width - (p + t).length, a = s.width && l > 0 ? u.repeat(l) : "", g += s.align ? p + t + a : "0" === u ? p + a + t : a + p + t); + } + return g; + }(function (e) { + if (s[e]) return s[e]; + var n, + t = e, + o = [], + i = 0; + for (; t;) { + if (null !== (n = r.text.exec(t))) o.push(n[0]);else if (null !== (n = r.modulo.exec(t))) o.push("%");else { + if (null === (n = r.placeholder.exec(t))) throw new SyntaxError("[sprintf] unexpected placeholder"); + if (n[2]) { + i |= 1; + var c = [], + a = n[2], + u = []; + if (null === (u = r.key.exec(a))) throw new SyntaxError("[sprintf] failed to parse named argument key"); + for (c.push(u[1]); "" !== (a = a.substring(u[0].length));) if (null !== (u = r.key_access.exec(a))) c.push(u[1]);else { + if (null === (u = r.index_access.exec(a))) throw new SyntaxError("[sprintf] failed to parse named argument key"); + c.push(u[1]); + } + n[2] = c; + } else i |= 2; + if (3 === i) throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported"); + o.push({ + placeholder: n[0], + param_no: n[1], + keys: n[2], + sign: n[3], + pad_char: n[4], + align: n[5], + width: n[6], + precision: n[7], + type: n[8] + }); + } + t = t.substring(n[0].length); + } + return s[e] = o; + }(e), arguments); + } + function c(e, n) { + return i.apply(null, [e].concat(n || [])); + } + var s = Object.create(null); + n.sprintf = i, n.vsprintf = c, "undefined" != typeof window && (window.sprintf = i, window.vsprintf = c, void 0 === (o = function () { + return { + sprintf: i, + vsprintf: c + }; + }.call(n, t, n, e)) || (e.exports = o)); + }(); +}, function (e, n, t) { + "use strict"; + + t.r(n), function (e) { + t.d(n, "WebSocketManager", function () { + return r; + }); + var o = t(0); + e.connect = e.connect || {}, connect.WebSocketManager = o.a; + var r = o.a; + }.call(this, t(3)); +}, function (e, n) { + var t; + t = function () { + return this; + }(); + try { + t = t || new Function("return this")(); + } catch (e) { + "object" == (typeof window === "undefined" ? "undefined" : _typeof(window)) && (t = window); + } + e.exports = t; +}]); + +/***/ }), -/***/ 738: +/***/ 312: /***/ (() => { - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - - /**------------------------------------------------------------------------- - * GraphLink <> - * - * Represents the association of one or more attributes to a state transition. - */ - var GraphLink = function GraphLink(fromState, toState) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - this.fromState = fromState; - this.toState = toState; - }; - GraphLink.prototype.getAssociations = function (context) { - throw connect.NotImplementedError(); - }; - GraphLink.prototype.getFromState = function () { - return this.fromState; - }; - GraphLink.prototype.getToState = function () { - return this.toState; - }; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + + // How frequently softphone logs should be collected and reported to shared worker. + var SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS = 5000; + + // How frequently logs should be collected and sent downstream + var LOGS_REPORT_INTERVAL_MILLIS = 5000; + + // The default log roll interval (30min) + var DEFAULT_LOG_ROLL_INTERVAL = 1800000; + + /** + * An enumeration of common logging levels. + */ + var LogLevel = { + TEST: "TEST", + TRACE: "TRACE", + DEBUG: "DEBUG", + INFO: "INFO", + LOG: "LOG", + WARN: "WARN", + ERROR: "ERROR", + CRITICAL: "CRITICAL" + }; + + /** + * An enumeration of common logging components. + */ + var LogComponent = { + CCP: "ccp", + SOFTPHONE: "softphone", + CHAT: "chat", + TASK: "task" + }; + + /** + * The numeric order of the logging levels above. + * They are spaced to allow the addition of other log + * levels at a later time. + */ + var LogLevelOrder = { + TEST: 0, + TRACE: 10, + DEBUG: 20, + INFO: 30, + LOG: 40, + WARN: 50, + ERROR: 100, + CRITICAL: 200 + }; + + /** + * A map from log level to console logger function. + */ + var CONSOLE_LOGGER_MAP = { + TRACE: function TRACE(text) { + console.info(text); + }, + DEBUG: function DEBUG(text) { + console.info(text); + }, + INFO: function INFO(text) { + console.info(text); + }, + LOG: function LOG(text) { + console.log(text); + }, + TEST: function TEST(text) { + console.log(text); + }, + WARN: function WARN(text) { + console.warn(text); + }, + ERROR: function ERROR(text) { + console.error(text); + }, + CRITICAL: function CRITICAL(text) { + console.error(text); + } + }; + + /** + * Checks if it is a valid log component enum + */ + + var isValidLogComponent = function isValidLogComponent(component) { + return Object.values(LogComponent).indexOf(component) !== -1; + }; + + /** + * Extract the custom arguments as required by the logger + */ + var extractLoggerArgs = function extractLoggerArgs(loggerArgs) { + var args = Array.prototype.slice.call(loggerArgs, 0); + var firstArg = args.shift(); + var format; + var component; + if (isValidLogComponent(firstArg)) { + component = firstArg; + format = args.shift(); + } else { + //default to CCP component + format = firstArg; + component = LogComponent.CCP; + } + return { + format: format, + component: component, + args: args + }; + }; + + /** + * A log entry. + * + * @param component The logging component. + * @param level The log level of this log entry. + * @param text The text contained in the log entry. + * @param loggerId The root logger id. + * + * Log entries are aware of their timestamp, order, + * and can contain objects and exception stack traces. + */ + var LogEntry = function LogEntry(component, level, text, loggerId) { + this.component = component; + this.level = level; + this.text = text; + this.time = new Date(); + this.exception = null; + this.objects = []; + this.line = 0; + this.agentResourceId = null; + try { + if (connect.agent.initialized) { + this.agentResourceId = new connect.Agent()._getResourceId(); + } + } catch (e) { + console.log("Issue finding agentResourceId: ", e); //can't use our logger here as we might infinitely attempt to log this error. + } + + this.loggerId = loggerId; + }; + LogEntry.fromObject = function (obj) { + var entry = new LogEntry(LogComponent.CCP, obj.level, obj.text, obj.loggerId); + + // Required to check for Date objects sent across frame boundaries + if (Object.prototype.toString.call(obj.time) === '[object Date]') { + entry.time = new Date(obj.time.getTime()); + } else if (typeof obj.time === 'number') { + entry.time = new Date(obj.time); + } else if (typeof obj.time === 'string') { + entry.time = Date.parse(obj.time); + } else { + entry.time = new Date(); + } + entry.exception = obj.exception; + entry.objects = obj.objects; + return entry; + }; + + /** + * Private method to remove sensitive info from client log + */ + var redactSensitiveInfo = function redactSensitiveInfo(data) { + var regex = /AuthToken.*\=/g; + if (data && _typeof(data) === 'object') { + Object.keys(data).forEach(function (key) { + if (_typeof(data[key]) === 'object') { + redactSensitiveInfo(data[key]); + } else if (typeof data[key] === 'string') { + if (key === "url" || key === "text") { + data[key] = data[key].replace(regex, "[redacted]"); + } else if (key === "quickConnectName") { + data[key] = "[redacted]"; + } + } + }); + } + }; + + /** + * Pulls the type, message, and stack trace + * out of the given exception for JSON serialization. + */ + var LoggedException = function LoggedException(e) { + this.type = e instanceof Error ? e.name : e.code || Object.prototype.toString.call(e); + this.message = e.message; + this.stack = e.stack ? e.stack.split('\n') : []; + }; + + /** + * Minimally stringify this log entry for printing + * to the console. + */ + LogEntry.prototype.toString = function () { + return connect.sprintf("[%s] [%s] [%s]: %s", this.getTime() && this.getTime().toISOString ? this.getTime().toISOString() : "???", this.getLevel(), this.getAgentResourceId(), this.getText()); + }; + + /** + * Get the log entry timestamp. + */ + LogEntry.prototype.getTime = function () { + return this.time; + }; + LogEntry.prototype.getAgentResourceId = function () { + return this.agentResourceId; + }; + + /** + * Get the level of the log entry. + */ + LogEntry.prototype.getLevel = function () { + return this.level; + }; + + /** + * Get the log entry text. + */ + LogEntry.prototype.getText = function () { + return this.text; + }; + + /** + * Get the log entry component. + */ + LogEntry.prototype.getComponent = function () { + return this.component; + }; + + /** + * Add an exception stack trace to this log entry. + * A log entry may contain only one exception stack trace. + */ + LogEntry.prototype.withException = function (e) { + this.exception = new LoggedException(e); + return this; + }; + + /** + * Add an arbitrary object to the log entry. A log entry + * may contain any number of objects. + */ + LogEntry.prototype.withObject = function (obj) { + var copiedObj = connect.deepcopy(obj); + redactSensitiveInfo(copiedObj); + this.objects.push(copiedObj); + return this; + }; + + /** + * Add a cross origin event object to the log entry. A log entry + * may contain any number of objects. + */ + LogEntry.prototype.withCrossOriginEventObject = function (obj) { + var copiedObj = connect.deepcopyCrossOriginEvent(obj); + redactSensitiveInfo(copiedObj); + this.objects.push(copiedObj); + return this; + }; + + /** + * Indicate that this log entry should be sent to the server + * NOTE: This should be used for internal logs only + */ + LogEntry.prototype.sendInternalLogToServer = function () { + connect.getLog()._serverBoundInternalLogs.push(this); + return this; + }; + + /** + * The logger instance. + */ + var Logger = function Logger() { + this._logs = []; + this._rolledLogs = []; + this._logsToPush = []; + this._serverBoundInternalLogs = []; + this._echoLevel = LogLevelOrder.INFO; + this._logLevel = LogLevelOrder.INFO; + this._lineCount = 0; + this._logRollInterval = 0; + this._logRollTimer = null; + this._loggerId = new Date().getTime() + "-" + Math.random().toString(36).slice(2); + this.setLogRollInterval(DEFAULT_LOG_ROLL_INTERVAL); + this._startLogIndexToPush = 0; + }; + + /** + * Sets the interval in milliseconds that the logs will be rotated. + * Logs are rotated out completely at the end of the second roll + * and will eventually be garbage collected. + */ + Logger.prototype.setLogRollInterval = function (interval) { + var self = this; + if (!this._logRollTimer || interval !== this._logRollInterval) { + if (this._logRollTimer) { + global.clearInterval(this._logRollTimer); + } + this._logRollInterval = interval; + this._logRollTimer = global.setInterval(function () { + this._rolledLogs = this._logs; + this._logs = []; + this._startLogIndexToPush = 0; + self.info("Log roll interval occurred."); + }, this._logRollInterval); + } else { + this.warn("Logger is already set to the given interval: %d", this._logRollInterval); + } + }; + + /** + * Set the log level. This is the minimum level at which logs will + * be kept for later archiving. + */ + Logger.prototype.setLogLevel = function (level) { + if (level in LogLevelOrder) { + this._logLevel = LogLevelOrder[level]; + } else { + throw new Error("Unknown logging level: " + level); + } + }; + + /** + * Set the echo level. This is the minimum level at which logs will + * be printed to the javascript console. + */ + Logger.prototype.setEchoLevel = function (level) { + if (level in LogLevelOrder) { + this._echoLevel = LogLevelOrder[level]; + } else { + throw new Error("Unknown logging level: " + level); + } + }; + + /** + * Write a particular log entry. + * + * @param level The logging level of the entry. + * @param text The text contents of the entry. + * + * @returns The new log entry. + */ + Logger.prototype.write = function (component, level, text) { + var logEntry = new LogEntry(component, level, text, this.getLoggerId()); + redactSensitiveInfo(logEntry); + this.addLogEntry(logEntry); + return logEntry; + }; + Logger.prototype.addLogEntry = function (logEntry) { + // Call this second time as in some places this function is called directly + redactSensitiveInfo(logEntry); + this._logs.push(logEntry); + + //For now only send softphone logs only. + //TODO add CCP logs once we are sure that no sensitive data is being logged. + if (LogComponent.SOFTPHONE === logEntry.component) { + this._logsToPush.push(logEntry); + } + if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { + if (LogLevelOrder[logEntry.level] >= this._echoLevel) { + CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); + } + logEntry.line = this._lineCount++; + } + }; + Logger.prototype.sendInternalLogEntryToServer = function (logEntry) { + this._serverBoundInternalLogs.push(logEntry); + if (logEntry.level in LogLevelOrder && LogLevelOrder[logEntry.level] >= this._logLevel) { + if (LogLevelOrder[logEntry.level] >= this._echoLevel) { + CONSOLE_LOGGER_MAP[logEntry.getLevel()](logEntry.toString()); + } + logEntry.line = this._lineCount++; + } + }; + + /** + * Remove all objects from all log entries. + */ + Logger.prototype.clearObjects = function () { + for (var x = 0; x < this._logs.length; x++) { + if (this._logs[x].objects) { + delete this._logs[x].objects; + } + } + }; + + /** + * Remove all exception stack traces from the log entries. + */ + Logger.prototype.clearExceptions = function () { + for (var x = 0; x < this._logs.length; x++) { + if (this._logs[x].exception) { + delete this._logs[x].exception; + } + } + }; + Logger.prototype.trace = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.TRACE, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.debug = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.DEBUG, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.info = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.INFO, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.log = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.LOG, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.test = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.TEST, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.warn = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.WARN, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.error = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); + }; + Logger.prototype.critical = function () { + var logArgs = extractLoggerArgs(arguments); + return this.write(logArgs.component, LogLevel.ERROR, connect.vsprintf(logArgs.format, logArgs.args)); + }; + + /** + * Create a string representation of the logger contents. + */ + Logger.prototype.toString = function () { + var lines = []; + for (var x = 0; x < this._logs.length; x++) { + lines.push(this._logs[x].toString()); + } + return lines.join("\n"); + }; + + /** + * Download/Archive logs to a file, + * By default, it returns all logs. + * To filter logs by the minimum log level set by setLogLevel or the default set in _logLevel, + * pass in filterByLogLevel to true in options + * + * @param options download options [Object|String]. + * - of type Object: + * { logName: 'my-log-name', + * filterByLogLevel: false, //download all logs + * } + * - of type String (for backward compatibility), the file's name + */ + Logger.prototype.download = function (options) { + var logName = 'agent-log'; + var filterByLogLevel = false; + if (_typeof(options) === 'object') { + logName = options.logName || logName; + filterByLogLevel = options.filterByLogLevel || filterByLogLevel; + } else if (typeof options === 'string') { + logName = options || logName; + } + var self = this; + var logs = this._rolledLogs.concat(this._logs); + if (filterByLogLevel) { + logs = logs.filter(function (entry) { + return LogLevelOrder[entry.level] >= self._logLevel; + }); + } + var logBlob = new global.Blob([JSON.stringify(logs, undefined, 4)], ['text/plain']); + var downloadLink = document.createElement('a'); + var logName = logName || 'agent-log'; + downloadLink.href = global.URL.createObjectURL(logBlob); + downloadLink.download = logName + '.txt'; + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); + }; + Logger.prototype.scheduleUpstreamLogPush = function (conduit) { + if (!connect.upstreamLogPushScheduled) { + connect.upstreamLogPushScheduled = true; + /** Schedule pushing logs frequently to sharedworker upstream, sharedworker will report to LARS*/ + global.setInterval(connect.hitch(this, this.reportMasterLogsUpStream, conduit), SOFTPHONE_LOG_REPORT_INTERVAL_MILLIS); + } + }; + Logger.prototype.reportMasterLogsUpStream = function (conduit) { + var logsToPush = this._logsToPush.slice(); + this._logsToPush = []; + connect.ifMaster(connect.MasterTopics.SEND_LOGS, function () { + if (logsToPush.length > 0) { + conduit.sendUpstream(connect.EventType.SEND_LOGS, logsToPush); + } + }); + }; + Logger.prototype.scheduleUpstreamOuterContextCCPserverBoundLogsPush = function (conduit) { + global.setInterval(connect.hitch(this, this.pushOuterContextCCPserverBoundLogsUpstream, conduit), 1000); + }; + Logger.prototype.scheduleUpstreamOuterContextCCPLogsPush = function (conduit) { + global.setInterval(connect.hitch(this, this.pushOuterContextCCPLogsUpstream, conduit), 1000); + }; + Logger.prototype.pushOuterContextCCPserverBoundLogsUpstream = function (conduit) { + if (this._serverBoundInternalLogs.length > 0) { + for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { + this._serverBoundInternalLogs[i].text = this._serverBoundInternalLogs[i].text; + } + conduit.sendUpstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs); + this._serverBoundInternalLogs = []; + } + }; + Logger.prototype.pushOuterContextCCPLogsUpstream = function (conduit) { + for (var i = this._startLogIndexToPush; i < this._logs.length; i++) { + if (this._logs[i].loggerId !== this._loggerId) { + continue; + } + conduit.sendUpstream(connect.EventType.LOG, this._logs[i]); + } + this._startLogIndexToPush = this._logs.length; + }; + Logger.prototype.getLoggerId = function () { + return this._loggerId; + }; + Logger.prototype.scheduleDownstreamClientSideLogsPush = function () { + global.setInterval(connect.hitch(this, this.pushClientSideLogsDownstream), LOGS_REPORT_INTERVAL_MILLIS); + }; + Logger.prototype.pushClientSideLogsDownstream = function () { + var logs = []; + + // We do not send a request if we have less than 50 records so that we minimize the number of + // requests per second. + // 500 is the max we accept on the server. + // We chose 500 because this is the limit imposed by Firehose for a put batch request + if (this._serverBoundInternalLogs.length < 50) { + return; + } else if (this._serverBoundInternalLogs.length > 500) { + logs = this._serverBoundInternalLogs.splice(0, 500); + } else { + logs = this._serverBoundInternalLogs; + this._serverBoundInternalLogs = []; + } + connect.publishClientSideLogs(logs); + }; + var DownstreamConduitLogger = function DownstreamConduitLogger(conduit) { + Logger.call(this); + this.conduit = conduit; + global.setInterval(connect.hitch(this, this._pushLogsDownstream), DownstreamConduitLogger.LOG_PUSH_INTERVAL); + + // Disable log rolling, we will purge our own logs once they have + // been pushed downstream. + global.clearInterval(this._logRollTimer); + this._logRollTimer = null; + }; + // How frequently logs should be collected and delivered downstream. + DownstreamConduitLogger.LOG_PUSH_INTERVAL = 1000; + DownstreamConduitLogger.prototype = Object.create(Logger.prototype); + DownstreamConduitLogger.prototype.constructor = DownstreamConduitLogger; + DownstreamConduitLogger.prototype.pushLogsDownstream = function (logs) { + var self = this; + logs.forEach(function (log) { + self.conduit.sendDownstream(connect.EventType.LOG, log); + }); + }; + DownstreamConduitLogger.prototype._pushLogsDownstream = function () { + var self = this; + this._logs.forEach(function (log) { + self.conduit.sendDownstream(connect.EventType.LOG, log); + }); + this._logs = []; + for (var i = 0; i < this._serverBoundInternalLogs.length; i++) { + this.conduit.sendDownstream(connect.EventType.SERVER_BOUND_INTERNAL_LOG, this._serverBoundInternalLogs[i]); + } + this._serverBoundInternalLogs = []; + }; + + /** + * Wrap a function with try catch block + */ + var tryCatchWrapperMethod = function tryCatchWrapperMethod(fn) { + var wrappedfunction = function wrappedfunction() { + try { + return fn.apply(this, arguments); + } catch (e) { + // Since this wraps Logger class, we can only print it in the console and eat it. + CONSOLE_LOGGER_MAP.ERROR(e); + } + }; + return wrappedfunction; + }; + /** + * This is a wrapper method to wrap each function + * in an object with try catch block. + */ + var tryCatchWrapperObject = function tryCatchWrapperObject(obj) { + for (var method in obj) { + if (typeof obj[method] === 'function') { + obj[method] = tryCatchWrapperMethod(obj[method]); + } + } + }; + + /** Create the singleton logger instance. */ + connect.rootLogger = new Logger(); + tryCatchWrapperObject(connect.rootLogger); + + /** Fetch the singleton logger instance. */ + var getLog = function getLog() { + return connect.rootLogger; + }; + connect = connect || {}; + connect.getLog = getLog; + connect.LogEntry = LogEntry; + connect.Logger = Logger; + connect.LogLevel = LogLevel; + connect.LogComponent = LogComponent; + connect.DownstreamConduitLogger = DownstreamConduitLogger; +})(); - /**------------------------------------------------------------------------- - * DirectGraphLink <> extends GraphLink - * - * Represents the by-value representation of one or more attributes to a - * state transition. - */ - var DirectGraphLink = function DirectGraphLink(fromState, toState, associations) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - connect.assertNotNull(associations, 'associations'); - GraphLink.call(this, fromState, toState); - this.associations = associations; - }; - DirectGraphLink.prototype = Object.create(GraphLink.prototype); - DirectGraphLink.prototype.constructor = DirectGraphLink; - DirectGraphLink.prototype.getAssociations = function (context) { - return this.associations; - }; +/***/ }), - /** - * FunctionalGraphLink <> extends GraphLink - * - * Represents a functional association of one or more attributes to a - * state transition. - */ - var FunctionalGraphLink = function FunctionalGraphLink(fromState, toState, closure) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - connect.assertNotNull(closure, 'closure'); - connect.assertTrue(connect.isFunction(closure), 'closure must be a function'); - GraphLink.call(this, fromState, toState); - this.closure = closure; - }; - FunctionalGraphLink.prototype = Object.create(GraphLink.prototype); - FunctionalGraphLink.prototype.constructor = FunctionalGraphLink; - FunctionalGraphLink.prototype.getAssociations = function (context) { - return this.closure(context, this.getFromState(), this.getToState()); - }; +/***/ 158: +/***/ (() => { - /**------------------------------------------------------------------------- - * EventGraph <> - * - * Builds a map of associations from one state to another in context of a - * particular object. The associations can be direct (one or more values) - * or functional (a method returning one or more values), and are used to - * provide additional contextual event hooks for the UI to consume. - */ - var EventGraph = function EventGraph() { - this.fromMap = {}; - }; - EventGraph.ANY = "<>"; - EventGraph.prototype.assoc = function (fromStateObj, toStateObj, assocObj) { - var self = this; - if (!fromStateObj) { - throw new Error("fromStateObj is not defined."); - } - if (!toStateObj) { - throw new Error("toStateObj is not defined."); - } - if (!assocObj) { - throw new Error("assocObj is not defined."); - } - if (fromStateObj instanceof Array) { - fromStateObj.forEach(function (fromState) { - self.assoc(fromState, toStateObj, assocObj); - }); - } else if (toStateObj instanceof Array) { - toStateObj.forEach(function (toState) { - self.assoc(fromStateObj, toState, assocObj); - }); - } else { - if (typeof assocObj === "function") { - this._addAssociation(new FunctionalGraphLink(fromStateObj, toStateObj, assocObj)); - } else if (assocObj instanceof Array) { - this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, assocObj)); - } else { - this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, [assocObj])); - } - } - return this; - }; - EventGraph.prototype.getAssociations = function (context, fromState, toState) { - connect.assertNotNull(fromState, 'fromState'); - connect.assertNotNull(toState, 'toState'); - var associations = []; - var toMapFromAny = this.fromMap[EventGraph.ANY] || {}; - var toMap = this.fromMap[fromState] || {}; - associations = associations.concat(this._getAssociationsFromMap(toMapFromAny, context, fromState, toState)); - associations = associations.concat(this._getAssociationsFromMap(toMap, context, fromState, toState)); - return associations; - }; - EventGraph.prototype._addAssociation = function (assoc) { - var toMap = this.fromMap[assoc.getFromState()]; - if (!toMap) { - toMap = this.fromMap[assoc.getFromState()] = {}; - } - var assocList = toMap[assoc.getToState()]; - if (!assocList) { - assocList = toMap[assoc.getToState()] = []; - } - assocList.push(assoc); - }; - EventGraph.prototype._getAssociationsFromMap = function (map, context, fromState, toState) { - var assocList = (map[EventGraph.ANY] || []).concat(map[toState] || []); - return assocList.reduce(function (prev, assoc) { - return prev.concat(assoc.getAssociations(context)); - }, []); - }; - connect.EventGraph = EventGraph; - })(); +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.ChatMediaController = function (mediaInfo, metadata) { + var logger = connect.getLog(); + var logComponent = connect.LogComponent.CHAT; + var createMediaInstance = function createMediaInstance() { + publishTelemetryEvent("Chat media controller init", mediaInfo.contactId); + logger.info(logComponent, "Chat media controller init").withObject(mediaInfo).sendInternalLogToServer(); + connect.ChatSession.setGlobalConfig({ + loggerConfig: { + logger: logger + }, + region: metadata.region + }); + + /** Could be also CUSTOMER - For now we are creating only Agent connection media object */ + var controller = connect.ChatSession.create({ + chatDetails: mediaInfo, + type: "AGENT", + websocketManager: connect.core.getWebSocketManager() + }); + trackChatConnectionStatus(controller); + return controller.connect().then(function (data) { + logger.info(logComponent, "Chat Session Successfully established for contactId %s", mediaInfo.contactId).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session Successfully established", mediaInfo.contactId); + return controller; + })["catch"](function (error) { + logger.error(logComponent, "Chat Session establishement failed for contact %s", mediaInfo.contactId).withException(error).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); + throw error; + }); + }; + var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { + connect.publishMetric({ + name: eventName, + contactId: mediaInfo.contactId, + data: data || mediaInfo + }); + }; + var trackChatConnectionStatus = function trackChatConnectionStatus(controller) { + controller.onConnectionBroken(function (data) { + logger.error(logComponent, "Chat Session connection broken").withException(data).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session connection broken", data); + }); + controller.onConnectionEstablished(function (data) { + logger.info(logComponent, "Chat Session connection established").withObject(data).sendInternalLogToServer(); + publishTelemetryEvent("Chat Session connection established", data); + }); + }; + return { + get: function get() { + return createMediaInstance(); + } + }; + }; +})(); - /***/ -}), +/***/ }), -/***/ 420: +/***/ 7: /***/ (() => { - function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - var userAgent = navigator.userAgent; - var ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; - var DEFAULT_POPUP_HEIGHT = 578; - var DEFAULT_POPUP_WIDTH = 433; - var COPYABLE_EVENT_FIELDS = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; - - /** - * Unpollute sprintf functions from the global namespace. - */ - connect.sprintf = global.sprintf; - connect.vsprintf = global.vsprintf; - delete global.sprintf; - delete global.vsprintf; - connect.HTTP_STATUS_CODES = { - SUCCESS: 200, - TOO_MANY_REQUESTS: 429, - INTERNAL_SERVER_ERROR: 500 - }; - connect.TRANSPORT_TYPES = { - CHAT_TOKEN: "chat_token", - WEB_SOCKET: "web_socket" - }; - - /** - * Binds the given instance object as the context for - * the method provided. - * - * @param scope The instance object to be set as the scope - * of the function. - * @param method The method to be encapsulated. - * - * All other arguments, if any, are bound to the method - * invocation inside the closure. - * - * @return A closure encapsulating the invocation of the - * method provided in context of the given instance. - */ - connect.hitch = function () { - var args = Array.prototype.slice.call(arguments); - var scope = args.shift(); - var method = args.shift(); - connect.assertNotNull(scope, 'scope'); - connect.assertNotNull(method, 'method'); - connect.assertTrue(connect.isFunction(method), 'method must be a function'); - return function () { - var closureArgs = Array.prototype.slice.call(arguments); - return method.apply(scope, args.concat(closureArgs)); - }; - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.MediaFactory = function (params) { + /** controller holder */ + var mediaControllers = {}; + var toBeDestroyed = new Set(); + var logger = connect.getLog(); + var logComponent = connect.LogComponent.CHAT; + var metadata = connect.merge({}, params) || {}; + metadata.region = metadata.region || "us-west-2"; // Default it to us-west-2 + + var getMediaController = function getMediaController(connectionObj) { + var connectionId = connectionObj.getConnectionId(); + var mediaInfo = connectionObj.getMediaInfo(); + /** if we do not have the media info then just reject the request */ + if (!mediaInfo) { + logger.error(logComponent, "Media info does not exist for a media type %s", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); + return Promise.reject("Media info does not exist for this connection"); + } + if (!mediaControllers[connectionId]) { + logger.info(logComponent, "media controller of type %s init", connectionObj.getMediaType()).withObject(connectionObj).sendInternalLogToServer(); + switch (connectionObj.getMediaType()) { + case connect.MediaType.CHAT: + return mediaControllers[connectionId] = new connect.ChatMediaController(connectionObj.getMediaInfo(), metadata).get(); + case connect.MediaType.SOFTPHONE: + return mediaControllers[connectionId] = new connect.SoftphoneMediaController(connectionObj.getMediaInfo()).get(); + case connect.MediaType.TASK: + return mediaControllers[connectionId] = new connect.TaskMediaController(connectionObj.getMediaInfo()).get(); + default: + logger.error(logComponent, "Unrecognized media type %s ", connectionObj.getMediaType()).sendInternalLogToServer(); + return Promise.reject(); + } + } else { + return mediaControllers[connectionId]; + } + }; + + /** Check all the active states for the connection */ + var ifConnectionActive = function ifConnectionActive(connectionObj) { + return connectionObj.isActive(); + }; + var get = function get(connectionObj) { + if (ifConnectionActive(connectionObj)) { + return getMediaController(connectionObj); + } else { + destroy(connectionObj.getConnectionId()); + return Promise.reject("Media Controller is no longer available for this connection"); + } + }; + var destroy = function destroy(connectionId) { + if (mediaControllers[connectionId] && !toBeDestroyed.has(connectionId)) { + logger.info(logComponent, "Destroying mediaController for %s", connectionId); + toBeDestroyed.add(connectionId); + mediaControllers[connectionId].then(function () { + if (typeof controller.cleanUp === "function") controller.cleanUp(); + delete mediaControllers[connectionId]; + toBeDestroyed["delete"](connectionId); + })["catch"](function () { + delete mediaControllers[connectionId]; + toBeDestroyed["delete"](connectionId); + }); + } + }; + return { + get: get, + destroy: destroy + }; + }; +})(); - /** - * Determine if the given value is a callable function type. - * Borrowed from Underscore.js. - */ - connect.isFunction = function (obj) { - return !!(obj && obj.constructor && obj.call && obj.apply); - }; +/***/ }), - /** - * Determine if the given value is an array. - */ - connect.isArray = function (obj) { - return Object.prototype.toString.call(obj) === '[object Array]'; - }; +/***/ 6: +/***/ (() => { - /** - * Get a list of keys from a Javascript object used - * as a hash map. - */ - connect.keys = function (map) { - var keys = []; - connect.assertNotNull(map, 'map'); - for (var k in map) { - keys.push(k); - } - return keys; - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + + // TODO move softphone implementations here - Wil do this for GA + connect.SoftphoneMediaController = function (mediaInfo) { + return { + get: function get() { + return Promise.resolve(mediaInfo); + } + }; + }; +})(); - /** - * Get a list of values from a Javascript object used - * as a hash map. - */ - connect.values = function (map) { - var values = []; - connect.assertNotNull(map, 'map'); - for (var k in map) { - values.push(map[k]); - } - return values; - }; +/***/ }), - /** - * Get a list of key/value pairs from the given map. - */ - connect.entries = function (map) { - var entries = []; - for (var k in map) { - entries.push({ - key: k, - value: map[k] - }); - } - return entries; - }; +/***/ 487: +/***/ (() => { - /** - * Merge two or more maps together into a new map, - * or simply copy a single map. - */ - connect.merge = function () { - var argMaps = Array.prototype.slice.call(arguments, 0); - var resultMap = {}; - argMaps.forEach(function (map) { - connect.entries(map).forEach(function (kv) { - resultMap[kv.key] = kv.value; - }); - }); - return resultMap; - }; - connect.now = function () { - return new Date().getTime(); - }; - connect.find = function (array, predicate) { - for (var x = 0; x < array.length; x++) { - if (predicate(array[x])) { - return array[x]; - } - } - return null; - }; - connect.contains = function (obj, value) { - if (obj instanceof Array) { - return connect.find(obj, function (v) { - return v === value; - }) != null; - } else { - return value in obj; - } - }; - connect.containsValue = function (obj, value) { - if (obj instanceof Array) { - return connect.find(obj, function (v) { - return v === value; - }) != null; - } else { - return connect.find(connect.values(obj), function (v) { - return v === value; - }) != null; - } - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Amazon Software License (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/asl/ + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express + * or implied. See the License for the specific language governing permissions + * and limitations under the License. + */ + +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + connect.TaskMediaController = function (mediaInfo) { + var logger = connect.getLog(); + var logComponent = connect.LogComponent.TASK; + var createMediaInstance = function createMediaInstance() { + publishTelemetryEvent("Task media controller init", mediaInfo.contactId); + logger.info(logComponent, "Task media controller init").withObject(mediaInfo); + var controller = connect.TaskSession.create({ + contactId: mediaInfo.contactId, + initialContactId: mediaInfo.initialContactId, + websocketManager: connect.core.getWebSocketManager() + }); + trackTaskConnectionStatus(controller); + return controller.connect().then(function () { + logger.info(logComponent, "Task Session Successfully established for contactId %s", mediaInfo.contactId); + publishTelemetryEvent("Task Session Successfully established", mediaInfo.contactId); + return controller; + })["catch"](function (error) { + logger.error(logComponent, "Task Session establishement failed for contact %s", mediaInfo.contactId).withException(error); + publishTelemetryEvent("Chat Session establishement failed", mediaInfo.contactId, error); + throw error; + }); + }; + var publishTelemetryEvent = function publishTelemetryEvent(eventName, data) { + connect.publishMetric({ + name: eventName, + contactId: mediaInfo.contactId, + data: data || mediaInfo + }); + }; + var trackTaskConnectionStatus = function trackTaskConnectionStatus(controller) { + controller.onConnectionBroken(function (data) { + logger.error(logComponent, "Task Session connection broken").withException(data); + publishTelemetryEvent("Task Session connection broken", data); + }); + controller.onConnectionEstablished(function (data) { + logger.info(logComponent, "Task Session connection established").withObject(data); + publishTelemetryEvent("Task Session connection established", data); + }); + }; + return { + get: function get() { + return createMediaInstance(); + } + }; + }; +})(); - /** - * Generate a random ID consisting of the current timestamp - * and a random base-36 number based on Math.random(). - */ - connect.randomId = function () { - return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)); - }; +/***/ }), - /** - * Generate an enum from the given list of lower-case enum values, - * where the enum keys will be upper case. - * - * Conversion from pascal case based on code from here: - * http://stackoverflow.com/questions/30521224 - */ - connect.makeEnum = function (values) { - var enumObj = {}; - values.forEach(function (value) { - var key = value.replace(/\.?([a-z]+)_?/g, function (x, y) { - return y.toUpperCase() + "_"; - }).replace(/_$/, ""); - enumObj[key] = value; - }); - return enumObj; - }; - connect.makeNamespacedEnum = function (prefix, values) { - var enumObj = connect.makeEnum(values); - connect.keys(enumObj).forEach(function (key) { - enumObj[key] = connect.sprintf("%s::%s", prefix, enumObj[key]); - }); - return enumObj; - }; - connect.makeGenericNamespacedEnum = function (prefix, values, delimiter) { - var enumObj = connect.makeEnum(values); - connect.keys(enumObj).forEach(function (key) { - enumObj[key] = connect.sprintf("%s" + delimiter + "%s", prefix, enumObj[key]); - }); - return enumObj; - }; +/***/ 743: +/***/ (() => { - /** - * Methods to determine browser type and versions, used for softphone initialization. - */ - connect.isChromeBrowser = function () { - return userAgent.indexOf("Chrome") !== -1; - }; - connect.isFirefoxBrowser = function () { - return userAgent.indexOf("Firefox") !== -1; - }; - connect.isOperaBrowser = function () { - return userAgent.indexOf("Opera") !== -1; - }; - connect.getChromeBrowserVersion = function () { - var chromeVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); - if (chromeVersion) { - return parseFloat(chromeVersion); - } else { - return -1; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/** + * Module which gets used for the Request storage access + * Exposes init, hasAccess, request and onRequest methods. + * utilizes core post message technique to communicate back to the parent which invokes the storage access + * + * @usage - Used by initCCP and customer can make use of onRequest callbacks , this will be called even before agent login + * + * Example - + * connect.storageAccess.onRequest({ + * onInit(){}, + * onDeny(){}, + * onGrant(){} + * }); + * + * There are 4 lifecycle methods in the storage access check + * + * a) Request - StreamJS would request for storage access check to the embedded Connect hosted storage access banner + * b) Init - Storage access banner inits the access check and sends back the current access state with hasAccess set to true or false + * this is the step where we show the actual RSA banner to agents and for custom use cases hidden container will be shown + * c) Grant [optional] - Executes when Agent/user accepts storage access or already given grant + * d) Deny [optional] - Executes when Agent/user deny the storage access/ + * + * In a positive flow - we should expect Request, Init, Grant and negative Request, Init, Deny + * + * Chrome Implementation of RSA API can be found here - https://github.com/cfredric/chrome-storage-access-api + */ +(function () { + var global = this || globalThis; + var connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var requestStorageAccessPath = "/request-storage-access"; + /** + * Configurable options exposed via initCCP + * By default canRequest will be set to false to make this as a explicit opt in + */ + var defaultStorageAccessParams = { + /* Config which controls the opt out/in - we expect customers to explicitely opt in. */ + canRequest: true, + /* ["custom", "default"] - decides the rsa page view */ + mode: "default", + custom: { + /** + * Only applicable for custom type RSA page and these messages should be localized by customers + * + * title: 'Cookie Notice', + * header: 'Please provide access' + * + */ + } + }; + var storageParams = {}; + var originalCCPUrl = ""; + var rsaContainer = null; + var onGrantCallbackInvoked = false; + var requesthandlerUnsubscriber; + var storageAccessEvents = { + INIT: "storageAccess::init", + GRANTED: "storageAccess::granted", + DENIED: "storageAccess::denied", + REQUEST: "storageAccess::request" + }; + var initStorageParams = function initStorageParams() { + var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + params.custom = params.custom || {}; + storageParams = _objectSpread(_objectSpread(_objectSpread({}, defaultStorageAccessParams), params), {}, { + custom: _objectSpread(_objectSpread({}, defaultStorageAccessParams.custom), params.custom) + }); + storageParams.canRequest = !(storageParams.canRequest === "false" || storageParams.canRequest === false); + }; + var resetStorageAccessState = function resetStorageAccessState() { + storageParams = {}; + originalCCPUrl = ""; + rsaContainer = null; + }; + + /** + * Handle display none/block properties for the RTSA container, if customer have different settings like height, opacity, positions etc configured they are encouraged to use + * onRequest Callback handle to reset the same. + * */ + var getRSAContainer = function getRSAContainer() { + return { + show: function show() { + rsaContainer.style.display = "block"; + }, + hide: function hide() { + rsaContainer.style.display = "none"; + } + }; + }; + + /** + * Custom Mode will show minimalistic UI - without any Connect references or Connect headers + * This will allow fully Custom CCPs to use banner and use minimal real estate to show the storage access Content + * */ + var isCustomRequestAccessMode = function isCustomRequestAccessMode() { + return storageParams && storageParams.mode !== "default"; + }; + var isConnectDomain = function isConnectDomain(origin) { + return origin.match(/.connect.aws.a2z.com|.my.connect.aws|.govcloud.connect.aws|.awsapps.com/); + }; + + /** + * Given the URL, this method generates the prefixed connect domain request storage access URL + * @param {string} url + * @returns {string} + */ + var getRsaUrlWithprefix = function getRsaUrlWithprefix(url) { + var _URL = new URL(url), + origin = _URL.origin, + pathname = _URL.pathname; + if (origin.match(/.awsapps.com/)) { + var prefix = "connect"; + if (pathname.startsWith("/connect-gamma")) { + prefix = "connect-gamma"; + } + return "".concat(origin, "/").concat(prefix).concat(requestStorageAccessPath); + } else { + return "".concat(origin).concat(requestStorageAccessPath); + } + }; + var isLocalhost = function isLocalhost(url) { + return url.match(/^https?:\/\/localhost/); + }; + + /** + * Fetches the landat path for request storage access page to navigate. This is typically CCP path or channel view + * @returns {string} + */ + var getlandAtPath = function getlandAtPath() { + if (!originalCCPUrl) { + throw new Error("[StorageAccess] [getlandAtPath] Invoke connect.storageAccess.init first"); + } + if (isConnectDomain(originalCCPUrl) || isLocalhost(originalCCPUrl)) { + var _URL2 = new URL(originalCCPUrl), + pathname = _URL2.pathname; + return pathname; + } + return "/connect/ccp-v2"; + }; + + /** + * + * Method which returns the relative request-storage-access page path. + * Validates against localhost and connect domains and returns prefixed path + * @returns {string} + */ + var getRequestStorageAccessUrl = function getRequestStorageAccessUrl() { + // ccpUrl may contain non standard direct SSO URLs in which case we may ask customers to provide instanceUrl as part of storage access params + + if (!originalCCPUrl) { + throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invoke connect.storageAccess.init first"); + } + if (isConnectDomain(originalCCPUrl)) { + return getRsaUrlWithprefix(originalCCPUrl); + } else if (isLocalhost(originalCCPUrl)) { + connect.getLog().info("[StorageAccess] [CCP] Local testing"); + return "".concat(originalCCPUrl).concat(requestStorageAccessPath); + } else if (storageParams.instanceUrl && isConnectDomain(storageParams.instanceUrl)) { + connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Customer has provided storageParams.instanceUrl ".concat(storageParams.instanceUrl)); + return getRsaUrlWithprefix(storageParams.instanceUrl); + } else if (storageParams.instanceUrl && isLocalhost(storageParams.instanceUrl)) { + connect.getLog().info("[StorageAccess] [getRequestStorageAccessUrl] Local testing"); + return "".concat(storageParams.instanceUrl).concat(requestStorageAccessPath); + } else { + connect.getLog().error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the correct ccpUrl or storageAccess.instanceUrl parameters"); + // FIXME - For test cases to succeed passing original parameter back instead throw an error by fixing all the CCP URL parameters accross the tests. + throw new Error("[StorageAccess] [getRequestStorageAccessUrl] Invalid Connect instance/CCP URL provided, please pass the valid Connect CCP URL or in case CCP URL is configured to be the SSO URL then use storageAccess.instanceUrl and pass the Connect CCP URL"); + } + }; + + /** + * Method which allows customers to listen on Storage access request and it's state changes + * @param {Object} consists of callbacks for the onInit, onDeny and onGrants + */ + var onRequestHandler = function onRequestHandler(_ref) { + var onInit = _ref.onInit, + onDeny = _ref.onDeny, + onGrant = _ref.onGrant; + function handleUpstreamMessages(_ref2) { + var data = _ref2.data, + source = _ref2.source; + var iframeContainer = connect.core._getCCPIframe(); + if (iframeContainer.contentWindow !== source) { + // disabling the logs for now + // connect.getLog().error('[StorageAccess][onRequestHandler] Request Coming from unknown domain %s', origin); + return false; + } + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); + } + switch (data.event) { + case storageAccessEvents.INIT: + { + connect.getLog().info("[StorageAccess][INIT] message recieved").withObject(data); + if (onInit) { + onInit(data); + } + break; + } + case storageAccessEvents.GRANTED: + { + connect.getLog().info("[StorageAccess][GRANTED] message recieved").withObject(data); + if (onGrant) { + onGrant(data); } - }; - connect.getFirefoxBrowserVersion = function () { - var firefoxVersion = userAgent.substring(userAgent.indexOf("Firefox") + 8); - if (firefoxVersion) { - return parseFloat(firefoxVersion); - } else { - return -1; + break; + } + case storageAccessEvents.DENIED: + { + connect.getLog().info("[StorageAccess][DENIED] message recieved").withObject(data); + if (onDeny) { + onDeny(data); } - }; - connect.isValidLocale = function (locale) { - var languages = [{ - id: 'en_US', - label: 'English' - }, { - id: 'de_DE', - label: 'Deutsch' - }, { - id: 'es_ES', - label: 'Español' - }, { - id: 'fr_FR', - label: 'Français' - }, { - id: 'ja_JP', - label: '日本語' - }, { - id: 'it_IT', - label: 'Italiano' - }, { - id: 'ko_KR', - label: '한국어' - }, { - id: 'pt_BR', - label: 'Português' - }, { - id: 'zh_CN', - label: '中文(简体)' - }, { - id: 'zh_TW', - label: '中文(繁體)' - }]; - return languages.map(function (language) { - return language.id; - }).includes(locale); - }; - connect.getOperaBrowserVersion = function () { - var versionOffset = userAgent.indexOf("Opera"); - var operaVersion = userAgent.indexOf("Version") !== -1 ? userAgent.substring(versionOffset + 8) : userAgent.substring(versionOffset + 6); - if (operaVersion) { - return parseFloat(operaVersion); - } else { - return -1; + break; + } + default: + { + // Make sure to clean up the handler as soon as the access is granted. + if (connect.core.initialized) { + window.removeEventListener("message", handleUpstreamMessages); } - }; - - /** - * Return a map of items in the given list indexed by - * keys determined by the closure provided. - * - * @param iterable A list-like object. - * @param closure A closure to determine the index for the - * items in the iterable. - * @return A map from index to item for each item in the iterable. - */ - connect.index = function (iterable, closure) { - var map = {}; - iterable.forEach(function (item) { - map[closure(item)] = item; - }); - return map; - }; + break; + } + } + } + // do this only if canRequest is set to true + if (storageParams.canRequest) { + window.addEventListener("message", handleUpstreamMessages); + } + return { + unsubscribe: function unsubscribe() { + window.removeEventListener("message", handleUpstreamMessages); + } + }; + }; + + /** + * setupRequestHandlers - method which attaches post message handlers and let the initCCP flow to continue. + * In case of custom CCPs - it also does hide/show the container. + * @param {*} param0 + */ + var setupRequestHandlers = function setupRequestHandlers(_ref3) { + var onGrantCallback = _ref3.onGrant; + if (requesthandlerUnsubscriber) { + requesthandlerUnsubscriber.unsubscribe(); + } + requesthandlerUnsubscriber = onRequestHandler({ + onInit: function onInit(messageData) { + console.log("%c[INIT]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onInit] callback executed").withObject(messageData === null || messageData === void 0 ? void 0 : messageData.data); + if (!(messageData !== null && messageData !== void 0 && messageData.data.hasAccess) && isCustomRequestAccessMode()) { + getRSAContainer().show(); + } + }, + onDeny: function onDeny() { + console.log("%c[DENIED]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onDeny] callback executed"); + if (isCustomRequestAccessMode()) { + getRSAContainer().show(); + } + }, + onGrant: function onGrant() { + console.log("%c[Granted]", "background:lime; color: black; font-size:large"); + connect.getLog().info("[StorageAccess][onGrant] callback executed"); + if (isCustomRequestAccessMode()) { + getRSAContainer().hide(); + } + // Invoke onGrantCallback only once as it setsup initCCP callbacks and events + if (!onGrantCallbackInvoked) { + onGrantCallback(); + onGrantCallbackInvoked = true; + } + } + }); + }; + connect.storageAccess = Object.freeze({ + /** + * Checks wther user has opted out for storage Access checks or not + * @returns {boolean} + */ + canRequest: function canRequest() { + return storageParams.canRequest; + }, + /** + * Mainly used by Tests, by default storage access is enabled for all + */ + optOutFromRequestAccess: function optOutFromRequestAccess() { + defaultStorageAccessParams.canRequest = false; + }, + /** + * Mainly used by Tests + */ + optInForRequestAccess: function optInForRequestAccess() { + defaultStorageAccessParams.canRequest = true; + }, + /** + * Method which inits the Storage Access module with Customer paramters. + * and generates request storage access URL and apply customization to the default paramters + * @param {*} params - storage access params + * @param {*} container - Container where CCP is being shown + * @returns {{canRequest, requestAccessPageurl}} + */ + init: function init(ccpUrl, containerDiv) { + var params = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + connect.assertNotNull(ccpUrl, "ccpUrl"); + connect.assertNotNull(containerDiv, "container"); + rsaContainer = containerDiv; + originalCCPUrl = ccpUrl; + initStorageParams(params); + connect.getLog().info("[StorageAccess][init] Request Storage Acccess init called with ccpUrl - ".concat(ccpUrl, " - ").concat(!storageParams.canRequest ? "user has opted out, skipping request storage access" : "Proceeding with requesting storage access")).withObject(storageParams); + }, + setupRequestHandlers: setupRequestHandlers, + getRequestStorageAccessUrl: getRequestStorageAccessUrl, + storageAccessEvents: storageAccessEvents, + resetStorageAccessState: resetStorageAccessState, + getStorageAccessParams: function getStorageAccessParams() { + return storageParams; + }, + onRequest: onRequestHandler, + request: function request() { + var iframeContainer = connect.core._getCCPIframe(); + iframeContainer.contentWindow.postMessage({ + event: storageAccessEvents.REQUEST, + data: _objectSpread(_objectSpread({}, storageParams), {}, { + landat: getlandAtPath() + }) + }, "*"); + } + }); +})(); - /** - * Converts the given array into a map as a set, - * where elements in the array are mapped to 1. - */ - connect.set = function (arrayIn) { - var setMap = {}; - arrayIn.forEach(function (key) { - setMap[key] = 1; - }); - return setMap; - }; +/***/ }), - /** - * Returns a map for each key in mapB which - * is NOT in mapA. - */ - connect.relativeComplement = function (mapA, mapB) { - var compMap = {}; - connect.keys(mapB).forEach(function (key) { - if (!(key in mapA)) { - compMap[key] = mapB[key]; - } - }); - return compMap; - }; +/***/ 555: +/***/ (() => { - /** - * Asserts that a premise is true. - */ - connect.assertTrue = function (premise, message) { - if (!premise) { - throw new connect.ValueError(message); - } - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + var connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var RingtoneEngineBase = function RingtoneEngineBase(ringtoneConfig) { + var self = this; + this._prevContactId = null; + connect.assertNotNull(ringtoneConfig, "ringtoneConfig"); + if (!ringtoneConfig.ringtoneUrl) { + throw new Error("ringtoneUrl is required!"); + } + if (global.Audio && typeof global.Promise !== "undefined") { + this._playableAudioPromise = new Promise(function (resolve, reject) { + self._audio = new Audio(ringtoneConfig.ringtoneUrl); + self._audio.loop = true; + self._audio.addEventListener("canplay", function () { + self._audioPlayable = true; + resolve(self._audio); + }); + }); + } else { + this._audio = null; + connect.getLog().error("Unable to provide a ringtone.").sendInternalLogToServer(); + } + self._driveRingtone(); + }; + RingtoneEngineBase.prototype._driveRingtone = function () { + throw new Error("Not implemented."); + }; + RingtoneEngineBase.prototype._startRingtone = function (contact) { + if (this._audio) { + this._audio.play()["catch"](function (e) { + this._publishTelemetryEvent("Ringtone Playback Failure", contact); + connect.getLog().error("Ringtone Playback Failure").sendInternalLogToServer(); + }); + this._publishTelemetryEvent("Ringtone Start", contact); + connect.getLog().info("Ringtone Start").sendInternalLogToServer(); + } + }; + RingtoneEngineBase.prototype._stopRingtone = function (contact) { + if (this._audio) { + this._audio.pause(); + this._audio.currentTime = 0; + this._publishTelemetryEvent("Ringtone Stop", contact); + connect.getLog().info("Ringtone Stop").sendInternalLogToServer(); + } + }; + + /** + * Stop ringtone. + */ + RingtoneEngineBase.prototype.stopRingtone = function () { + this._stopRingtone(); + }; + RingtoneEngineBase.prototype._ringtoneSetup = function (contact) { + var self = this; + connect.ifMaster(connect.MasterTopics.RINGTONE, function () { + self._startRingtone(contact); + self._prevContactId = contact.getContactId(); + contact.onConnected(lily.hitch(self, self._stopRingtone)); + contact.onAccepted(lily.hitch(self, self._stopRingtone)); + contact.onEnded(lily.hitch(self, self._stopRingtone)); + // Just to make sure to stop the ringtone in case of the failures of specific callbacks(onAccepted,onConnected); + contact.onRefresh(function (contact) { + if (contact.getStatus().type !== connect.ContactStatusType.CONNECTING && contact.getStatus().type !== connect.ContactStatusType.INCOMING) { + self._stopRingtone(); + } + }); + }); + }; + RingtoneEngineBase.prototype._publishTelemetryEvent = function (eventName, contact) { + if (contact && contact.getContactId()) { + connect.publishMetric({ + name: eventName, + contactId: contact.getContactId() + }); + } + }; + + /** + * Change the audio device used to play ringtone. + * If audio element is not fully initialized, the API will wait _audioPlayablePromise for 3 seconds and fail on timeout. + * This API is supported only by browsers that implemented ES6 Promise and http://www.w3.org/TR/audio-output/ + * Return a Promise that indicates the result of changing output device. + */ + RingtoneEngineBase.prototype.setOutputDevice = function (deviceId) { + if (this._playableAudioPromise) { + var playableAudioWithTimeout = Promise.race([this._playableAudioPromise, new Promise(function (resolve, reject) { + global.setTimeout(function () { + reject("Timed out waiting for playable audio"); + }, 3000 /*ms*/); + })]); + + return playableAudioWithTimeout.then(function (audio) { + if (audio) { + if (audio.setSinkId) { + return Promise.resolve(audio.setSinkId(deviceId)); + } else { + return Promise.reject("Not supported"); + } + } else { + return Promise.reject("No audio found"); + } + }); + } + if (global.Promise) { + return Promise.reject("Not eligible ringtone owner"); + } + }; + var VoiceRingtoneEngine = function VoiceRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + VoiceRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + VoiceRingtoneEngine.prototype.constructor = VoiceRingtoneEngine; + VoiceRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.VOICE && contact.isSoftphoneCall() && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Ringtone Connecting", contact); + connect.getLog().info("Ringtone Connecting").sendInternalLogToServer(); + } + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); + }); + new connect.Agent().getContacts().forEach(function (contact) { + if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { + onContactConnect(contact); + } + }); + }; + var ChatRingtoneEngine = function ChatRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + ChatRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + ChatRingtoneEngine.prototype.constructor = ChatRingtoneEngine; + ChatRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.CHAT && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Chat Ringtone Connecting", contact); + connect.getLog().info("Chat Ringtone Connecting").sendInternalLogToServer(); + } + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); + }); + }; + var TaskRingtoneEngine = function TaskRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + TaskRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + TaskRingtoneEngine.prototype.constructor = TaskRingtoneEngine; + TaskRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + var onContactConnect = function onContactConnect(contact) { + if (contact.getType() === lily.ContactType.TASK && contact.isInbound()) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Task Ringtone Connecting", contact); + connect.getLog().info("Task Ringtone Connecting").sendInternalLogToServer(); + } + }; + connect.contact(function (contact) { + contact.onConnecting(onContactConnect); + }); + }; + var QueueCallbackRingtoneEngine = function QueueCallbackRingtoneEngine(ringtoneConfig) { + RingtoneEngineBase.call(this, ringtoneConfig); + }; + QueueCallbackRingtoneEngine.prototype = Object.create(RingtoneEngineBase.prototype); + QueueCallbackRingtoneEngine.prototype.constructor = QueueCallbackRingtoneEngine; + QueueCallbackRingtoneEngine.prototype._driveRingtone = function () { + var self = this; + connect.contact(function (contact) { + contact.onIncoming(function () { + if (contact.getType() === lily.ContactType.QUEUE_CALLBACK) { + self._ringtoneSetup(contact); + self._publishTelemetryEvent("Callback Ringtone Connecting", contact); + connect.getLog().info("Callback Ringtone Connecting").sendInternalLogToServer(); + } + }); + }); + }; + + /* export connect.RingtoneEngine */ + connect.VoiceRingtoneEngine = VoiceRingtoneEngine; + connect.ChatRingtoneEngine = ChatRingtoneEngine; + connect.TaskRingtoneEngine = TaskRingtoneEngine; + connect.QueueCallbackRingtoneEngine = QueueCallbackRingtoneEngine; +})(); - /** - * Asserts that a value is not null or undefined. - */ - connect.assertNotNull = function (value, name) { - connect.assertTrue(value != null && _typeof(value) !== undefined, connect.sprintf("%s must be provided", name || 'A value')); - return value; - }; - connect.deepcopy = function (src) { - return JSON.parse(JSON.stringify(src)); - }; - connect.deepcopyCrossOriginEvent = function (event) { - var obj = {}; - var listOfAcceptableKeys = COPYABLE_EVENT_FIELDS; - listOfAcceptableKeys.forEach(function (key) { - try { - obj[key] = event[key]; - } catch (e) { - connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", key).sendInternalLogToServer(); - } - }); - return connect.deepcopy(obj); - }; +/***/ }), - /** - * Get the current base url of the open page, e.g. if the page is - * https://example.com:9494/oranges, this will be "https://example.com:9494". - */ - connect.getBaseUrl = function () { - var location = global.location; - return connect.sprintf("%s//%s:%s", location.protocol, location.hostname, location.port); - }; - connect.getUrlWithProtocol = function (url) { - var protocol = global.location.protocol; - if (url.substr(0, protocol.length) !== protocol) { - return connect.sprintf("%s//%s", protocol, url); - } - return url; - }; +/***/ 960: +/***/ (() => { - /** - * Determine if the current window is in an iframe. - * Courtesy: http://stackoverflow.com/questions/326069/ - */ - connect.isFramed = function () { - try { - return window.self !== window.top; - } catch (e) { - return true; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + global.ccpVersion = "V2"; + var RTPJobIntervalMs = 1000; + var statsReportingJobIntervalMs = 30000; + var streamBufferSize = 500; + var CallTypeMap = {}; + CallTypeMap[connect.SoftphoneCallType.AUDIO_ONLY] = 'Audio'; + CallTypeMap[connect.SoftphoneCallType.VIDEO_ONLY] = 'Video'; + CallTypeMap[connect.SoftphoneCallType.AUDIO_VIDEO] = 'AudioVideo'; + CallTypeMap[connect.SoftphoneCallType.NONE] = 'None'; + var AUDIO_INPUT = 'audio_input'; + var AUDIO_OUTPUT = 'audio_output'; + var MediaTypeMap = {}; + MediaTypeMap[connect.ContactType.VOICE] = "Voice"; + var UNKNOWN_MEDIA_TYPE = "Unknown"; + var timeSeriesStreamStatsBuffer = []; + var aggregatedUserAudioStats = {}; + var aggregatedRemoteAudioStats = {}; + var rtpStatsJob = null; + var reportStatsJob = null; + //Logger specific to softphone. + var logger = null; + var SoftphoneErrorTypes = connect.SoftphoneErrorTypes; + var HANG_UP_MULTIPLE_SESSIONS_EVENT = "MultiSessionHangUp"; + var MULTIPLE_SESSIONS_EVENT = "MultiSessions"; + var localMediaStream = {}; + var softphoneClientId = connect.randomId(); + var requestIceAccess = function requestIceAccess(transport) { + return new Promise(function (resolve, reject) { + connect.core.getClient().call(connect.ClientMethods.CREATE_TRANSPORT, transport, { + success: function success(data) { + resolve(data.softphoneTransport.softphoneMediaConnections); + }, + failure: function failure(reason) { + if (reason.message && reason.message.includes("SoftphoneConnectionLimitBreachedException")) { + publishError("multiple_softphone_active_sessions", "Number of active sessions are more then allowed limit.", ""); + } + reject(Error("requestIceAccess failed")); + }, + authFailure: function authFailure() { + reject(Error("Authentication failed while requestIceAccess")); + }, + accessDenied: function accessDenied() { + reject(Error("Access Denied while requestIceAccess")); + } + }); + }); + }; + var SoftphoneManager = function SoftphoneManager(softphoneParams) { + var self = this; + logger = new SoftphoneLogger(connect.getLog()); + logger.info("[Softphone Manager] softphone manager initialization has begun").sendInternalLogToServer(); + var rtcPeerConnectionFactory; + if (connect.RtcPeerConnectionFactory) { + rtcPeerConnectionFactory = new connect.RtcPeerConnectionFactory(logger, connect.core.getWebSocketManager(), softphoneClientId, connect.hitch(self, requestIceAccess, { + transportType: "softphone", + softphoneClientId: softphoneClientId + }), connect.hitch(self, publishError)); + } + if (!isBrowserSoftPhoneSupported()) { + publishError(SoftphoneErrorTypes.UNSUPPORTED_BROWSER, "Connect does not support this browser. Some functionality may not work. ", ""); + } + var gumPromise = fetchUserMedia({ + success: function success(stream) { + connect.core.setSoftphoneUserMediaStream(stream); + }, + failure: function failure(err) { + publishError(err, "Your microphone is not enabled in your browser. ", ""); + } + }); + handleSoftPhoneMuteToggle(); + handleSpeakerDeviceChange(); + handleMicrophoneDeviceChange(); + this.ringtoneEngine = null; + var rtcSessions = {}; + // Tracks the agent connection ID, so that if the same contact gets re-routed to the same agent, it'll still set up softphone + var callsDetected = {}; + this.onInitContactSub = {}; + this.onInitContactSub.unsubscribe = function () {}; + + // variables for firefox multitab + var isSessionPending = false; + var pendingContact = null; + var pendingAgentConnectionId = null; + var postponeStartingSession = function postponeStartingSession(contact, agentConnectionId) { + isSessionPending = true; + pendingContact = contact; + pendingAgentConnectionId = agentConnectionId; + }; + var cancelPendingSession = function cancelPendingSession() { + isSessionPending = false; + pendingContact = null; + pendingAgentConnectionId = null; + }; + + // helper method to provide access to rtc sessions + this.getSession = function (connectionId) { + return rtcSessions[connectionId]; + }; + this.replaceLocalMediaTrack = function (connectionId, track) { + var stream = localMediaStream[connectionId].stream; + if (stream) { + var oldTrack = stream.getAudioTracks()[0]; + track.enabled = oldTrack.enabled; + oldTrack.enabled = false; + stream.removeTrack(oldTrack); + stream.addTrack(track); + } + }; + var isContactTerminated = function isContactTerminated(contact) { + return contact.getStatus().type === connect.ContactStatusType.ENDED || contact.getStatus().type === connect.ContactStatusType.ERROR || contact.getStatus().type === connect.ContactStatusType.MISSED; + }; + var destroySession = function destroySession(agentConnectionId) { + if (rtcSessions.hasOwnProperty(agentConnectionId)) { + var session = rtcSessions[agentConnectionId]; + // Currently the assumption is it will throw an exception only and if only it already has been hung up. + // TODO: Update once the hangup API does not throw exceptions + new Promise(function (resolve, reject) { + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + session.hangup(); + })["catch"](function (err) { + lily.getLog().warn("Clean up the session locally " + agentConnectionId, err.message).sendInternalLogToServer(); + }); + } + }; + + // When multiple RTC sessions detected, ignore the new call and hang up the previous sessions. + // TODO: Update when connect-rtc exposes an API to detect session status. + var sanityCheckActiveSessions = function sanityCheckActiveSessions(rtcSessions) { + if (Object.keys(rtcSessions).length > 0) { + // Error! our state doesn't match, tear it all down. + for (var connectionId in rtcSessions) { + if (rtcSessions.hasOwnProperty(connectionId)) { + // Log an error for the session we are about to end. + publishMultipleSessionsEvent(HANG_UP_MULTIPLE_SESSIONS_EVENT, rtcSessions[connectionId].callId, connectionId); + destroySession(connectionId); + } + } + throw new Error("duplicate session detected, refusing to setup new connection"); + } + }; + this.startSession = function (_contact, _agentConnectionId) { + var contact = isSessionPending ? pendingContact : _contact; + var agentConnectionId = isSessionPending ? pendingAgentConnectionId : _agentConnectionId; + if (!contact || !agentConnectionId) { + return; + } + cancelPendingSession(); + + // Set to true, this will block subsequent invokes from entering. + callsDetected[agentConnectionId] = true; + logger.info("Softphone call detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + + // Ensure our session state matches our contact state to prevent issues should we lose track of a contact. + sanityCheckActiveSessions(rtcSessions); + if (contact.getStatus().type === connect.ContactStatusType.CONNECTING) { + publishTelemetryEvent("Softphone Connecting", contact.getContactId()); + } + initializeParams(); + var softphoneInfo = contact.getAgentConnection().getSoftphoneMediaInfo(); + var callConfig = parseCallConfig(softphoneInfo.callConfigJson); + var webSocketProvider; + if (callConfig.useWebSocketProvider) { + webSocketProvider = connect.core.getWebSocketManager(); + } + var session = new connect.RTCSession(callConfig.signalingEndpoint, callConfig.iceServers, softphoneInfo.callContextToken, logger, contact.getContactId(), agentConnectionId, webSocketProvider); + rtcSessions[agentConnectionId] = session; + if (connect.core.getSoftphoneUserMediaStream()) { + session.mediaStream = connect.core.getSoftphoneUserMediaStream(); + } + + // Custom Event to indicate the session init operations + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConnectionEvents.SESSION_INIT, + data: { + connectionId: agentConnectionId + } + }); + session.onSessionFailed = function (rtcSession, reason) { + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + publishSoftphoneFailureLogs(rtcSession, reason); + publishSessionFailureTelemetryEvent(contact.getContactId(), reason); + stopJobsAndReport(contact, rtcSession.sessionReport); + }; + session.onSessionConnected = function (rtcSession) { + publishTelemetryEvent("Softphone Session Connected", contact.getContactId()); + // Become master to send logs, since we need logs from softphone tab. + connect.becomeMaster(connect.MasterTopics.SEND_LOGS); + //start stats collection and reporting jobs + startStatsCollectionJob(rtcSession); + startStatsReportingJob(contact); + fireContactAcceptedEvent(contact); + }; + session.onSessionCompleted = function (rtcSession) { + publishTelemetryEvent("Softphone Session Completed", contact.getContactId()); + delete rtcSessions[agentConnectionId]; + delete callsDetected[agentConnectionId]; + // Stop all jobs and perform one last job. + stopJobsAndReport(contact, rtcSession.sessionReport); + + // Cleanup the cached streams + deleteLocalMediaStream(agentConnectionId); + }; + session.onLocalStreamAdded = function (rtcSession, stream) { + // Cache the streams for mute/unmute + localMediaStream[agentConnectionId] = { + stream: stream + }; + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.LOCAL_MEDIA_STREAM_CREATED, + data: { + connectionId: agentConnectionId + } + }); + }; + session.remoteAudioElement = document.getElementById('remote-audio'); + if (rtcPeerConnectionFactory) { + session.connect(rtcPeerConnectionFactory.get(callConfig.iceServers)); + } else { + session.connect(); + } + }; + var onRefreshContact = function onRefreshContact(contact, agentConnectionId) { + if (rtcSessions[agentConnectionId] && isContactTerminated(contact)) { + destroySession(agentConnectionId); + cancelPendingSession(); + } + if (contact.isSoftphoneCall() && !callsDetected[agentConnectionId] && (contact.getStatus().type === connect.ContactStatusType.CONNECTING || contact.getStatus().type === connect.ContactStatusType.INCOMING)) { + if (connect.isFirefoxBrowser() && connect.hasOtherConnectedCCPs()) { + postponeStartingSession(contact, agentConnectionId); + } else { + self.startSession(contact, agentConnectionId); + } + } + }; + var onInitContact = function onInitContact(contact) { + var agentConnectionId = contact.getAgentConnection().connectionId; + logger.info("Contact detected:", "contactId " + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + if (!callsDetected[agentConnectionId]) { + contact.onRefresh(function () { + onRefreshContact(contact, agentConnectionId); + }); + } + }; + self.onInitContactSub = connect.contact(onInitContact); + + // Contact already in connecting state scenario - In this case contact INIT is missed hence the OnRefresh callback is missed. + new connect.Agent().getContacts().forEach(function (contact) { + var agentConnectionId = contact.getAgentConnection().connectionId; + logger.info("Contact exist in the snapshot. Reinitiate the Contact and RTC session creation for contactId" + contact.getContactId(), "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + onInitContact(contact); + onRefreshContact(contact, agentConnectionId); + }); + }; + var fireContactAcceptedEvent = function fireContactAcceptedEvent(contact) { + var conduit = connect.core.getUpstream(); + var agentConnection = contact.getAgentConnection(); + if (!agentConnection) { + logger.info("Not able to retrieve the auto-accept setting from null AgentConnection, ignoring event publish..").sendInternalLogToServer(); + return; + } + var softphoneMediaInfo = agentConnection.getSoftphoneMediaInfo(); + if (!softphoneMediaInfo) { + logger.info("Not able to retrieve the auto-accept setting from null SoftphoneMediaInfo, ignoring event publish..").sendInternalLogToServer(); + return; + } + if (softphoneMediaInfo.autoAccept === true) { + logger.info("Auto-accept is enabled, sending out Accepted event to stop ringtone..").sendInternalLogToServer(); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.ContactEvents.ACCEPTED, + data: new connect.Contact(contact.contactId) + }); + conduit.sendUpstream(connect.EventType.BROADCAST, { + event: connect.core.getContactEventName(connect.ContactEvents.ACCEPTED, contact.contactId), + data: new connect.Contact(contact.contactId) + }); + } else { + logger.info("Auto-accept is disabled, ringtone will be stopped by user action.").sendInternalLogToServer(); + } + }; + + // Bind events for mute + var handleSoftPhoneMuteToggle = function handleSoftPhoneMuteToggle() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.EventType.MUTE, muteToggle); + }; + var handleSpeakerDeviceChange = function handleSpeakerDeviceChange() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.ConfigurationEvents.SET_SPEAKER_DEVICE, setSpeakerDevice); + }; + var handleMicrophoneDeviceChange = function handleMicrophoneDeviceChange() { + var bus = connect.core.getEventBus(); + bus.subscribe(connect.ConfigurationEvents.SET_MICROPHONE_DEVICE, setMicrophoneDevice); + }; + + // Make sure once we disconnected we get the mute state back to normal + var deleteLocalMediaStream = function deleteLocalMediaStream(connectionId) { + delete localMediaStream[connectionId]; + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.MUTE_TOGGLE, + data: { + muted: false + } + }); + }; + + // Check for the local streams if exists - revert it + // And inform other clients about the change + var muteToggle = function muteToggle(data) { + var status; + if (connect.keys(localMediaStream).length === 0) { + return; + } + if (data && data.mute !== undefined) { + status = data.mute; + } + for (var connectionId in localMediaStream) { + if (localMediaStream.hasOwnProperty(connectionId)) { + var localMedia = localMediaStream[connectionId].stream; + if (localMedia) { + var audioTracks = localMedia.getAudioTracks()[0]; + if (status !== undefined) { + audioTracks.enabled = !status; + localMediaStream[connectionId].muted = status; + if (status) { + logger.info("Agent has muted the contact, connectionId - " + connectionId).sendInternalLogToServer(); + } else { + logger.info("Agent has unmuted the contact, connectionId - " + connectionId).sendInternalLogToServer(); } - }; - connect.hasOtherConnectedCCPs = function () { - return connect.numberOfConnectedCCPs > 1; - }; - connect.fetch = function (endpoint, options, milliInterval, maxRetry) { - maxRetry = maxRetry || 5; - milliInterval = milliInterval || 1000; - options = options || {}; - return new Promise(function (resolve, reject) { - function fetchData(maxRetry) { - fetch(endpoint, options).then(function (res) { - if (res.status === connect.HTTP_STATUS_CODES.SUCCESS) { - res.json().then(function (json) { - return resolve(json); - })["catch"](function () { - return resolve({}); - }); - } else if (maxRetry !== 1 && (res.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || res.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)) { - setTimeout(function () { - fetchData(--maxRetry); - }, milliInterval); - } else { - reject(res); - } - })["catch"](function (e) { - reject(e); - }); - } - fetchData(maxRetry); + } else { + status = localMediaStream[connectionId].muted || false; + } + } + } + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.MUTE_TOGGLE, + data: { + muted: status + } + }); + }; + var setSpeakerDevice = function setSpeakerDevice(data) { + if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { + return; + } + var deviceId = data.deviceId; + var remoteAudioElement = document.getElementById('remote-audio'); + try { + logger.info("Trying to set speaker to device " + deviceId); + if (remoteAudioElement && typeof remoteAudioElement.setSinkId === 'function') { + remoteAudioElement.setSinkId(deviceId); + } + } catch (e) { + logger.error("Failed to set speaker to device " + deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.SPEAKER_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); + }; + var setMicrophoneDevice = function setMicrophoneDevice(data) { + if (connect.keys(localMediaStream).length === 0 || !data || !data.deviceId) { + return; + } + var deviceId = data.deviceId; + var softphoneManager = connect.core.getSoftphoneManager(); + try { + navigator.mediaDevices.getUserMedia({ + audio: { + deviceId: { + exact: deviceId + } + } + }).then(function (newMicrophoneStream) { + var newMicrophoneTrack = newMicrophoneStream.getAudioTracks()[0]; + for (var connectionId in localMediaStream) { + if (localMediaStream.hasOwnProperty(connectionId)) { + var localMedia = localMediaStream[connectionId].stream; + var session = softphoneManager.getSession(connectionId); + //Replace the audio track in the RtcPeerConnection + session._pc.getSenders()[0].replaceTrack(newMicrophoneTrack).then(function () { + //Replace the audio track in the local media stream (for mute / unmute) + softphoneManager.replaceLocalMediaTrack(connectionId, newMicrophoneTrack); }); - }; + } + } + }); + } catch (e) { + logger.error("Failed to set microphone device " + deviceId); + } + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.ConfigurationEvents.MICROPHONE_DEVICE_CHANGED, + data: { + deviceId: deviceId + } + }); + }; + var publishSoftphoneFailureLogs = function publishSoftphoneFailureLogs(rtcSession, reason) { + if (reason === connect.RTCErrors.ICE_COLLECTION_TIMEOUT) { + var endPointUrl = "\n"; + for (var i = 0; i < rtcSession._iceServers.length; i++) { + for (var j = 0; j < rtcSession._iceServers[i].urls.length; j++) { + endPointUrl = endPointUrl + rtcSession._iceServers[i].urls[j] + "\n"; + } + } + publishError(SoftphoneErrorTypes.ICE_COLLECTION_TIMEOUT, "Ice collection timedout. ", endPointUrl); + } else if (reason === connect.RTCErrors.USER_BUSY) { + publishError(SoftphoneErrorTypes.USER_BUSY_ERROR, "Softphone call UserBusy error. ", ""); + } else if (reason === connect.RTCErrors.SIGNALLING_HANDSHAKE_FAILURE) { + publishError(SoftphoneErrorTypes.SIGNALLING_HANDSHAKE_FAILURE, "Handshaking with Signalling Server " + rtcSession._signalingUri + " failed. ", rtcSession._signalingUri); + } else if (reason === connect.RTCErrors.GUM_TIMEOUT_FAILURE || reason === connect.RTCErrors.GUM_OTHER_FAILURE) { + publishError(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED, "Your microphone is not enabled in your browser. ", ""); + } else if (reason === connect.RTCErrors.SIGNALLING_CONNECTION_FAILURE) { + publishError(SoftphoneErrorTypes.SIGNALLING_CONNECTION_FAILURE, "URL " + rtcSession._signalingUri + " cannot be reached. ", rtcSession._signalingUri); + } else if (reason === connect.RTCErrors.CALL_NOT_FOUND) { + // No need to publish any softphone error for this case. CCP UX will handle this case. + logger.error("Softphone call failed due to CallNotFoundException.").sendInternalLogToServer(); + } else { + publishError(SoftphoneErrorTypes.WEBRTC_ERROR, "webrtc system error. ", ""); + } + }; + + /** Parse the JSON encoded web call config into the data it represents. */ + var parseCallConfig = function parseCallConfig(serializedConfig) { + // Our underscore is too old for unescape + // https://issues.amazon.com/issues/CSWF-1467 + var decodedJSON = serializedConfig.replace(/"/g, '"'); + return JSON.parse(decodedJSON); + }; + var fetchUserMedia = function fetchUserMedia(callbacksIn) { + var callbacks = callbacksIn || {}; + callbacks.success = callbacks.success || function () {}; + callbacks.failure = callbacks.failure || function () {}; + var CONSTRAINT = { + audio: true + }; + var promise = null; + if (typeof Promise !== "function") { + callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); + return; + } + if (_typeof(navigator.mediaDevices) === "object" && typeof navigator.mediaDevices.getUserMedia === "function") { + promise = navigator.mediaDevices.getUserMedia(CONSTRAINT); + } else if (typeof navigator.webkitGetUserMedia === "function") { + promise = new Promise(function (resolve, reject) { + navigator.webkitGetUserMedia(CONSTRAINT, resolve, reject); + }); + } else { + callbacks.failure(SoftphoneErrorTypes.UNSUPPORTED_BROWSER); + return; + } + promise.then(function (stream) { + var audioTracks = stream.getAudioTracks(); + if (audioTracks && audioTracks.length > 0) { + callbacks.success(stream); + } else { + callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); + } + }, function (err) { + callbacks.failure(SoftphoneErrorTypes.MICROPHONE_NOT_SHARED); + }); + return promise; + }; + var publishError = function publishError(errorType, message, endPointUrl) { + logger.error("Softphone error occurred : ", errorType, message || "").sendInternalLogToServer(); + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.AgentEvents.SOFTPHONE_ERROR, + data: new connect.SoftphoneError(errorType, message, endPointUrl) + }); + }; + var publishSessionFailureTelemetryEvent = function publishSessionFailureTelemetryEvent(contactId, reason) { + publishTelemetryEvent("Softphone Session Failed", contactId, { + failedReason: reason + }); + }; + var publishTelemetryEvent = function publishTelemetryEvent(eventName, contactId, data) { + if (contactId) { + connect.publishMetric({ + name: eventName, + contactId: contactId, + data: data + }); + } + }; + + // Publish the contact and agent information in a multiple sessions scenarios + var publishMultipleSessionsEvent = function publishMultipleSessionsEvent(eventName, contactId, agentConnectionId) { + publishTelemetryEvent(eventName, contactId, [{ + name: "AgentConnectionId", + value: agentConnectionId + }]); + logger.info("Publish multiple session error metrics", eventName, "contactId " + contactId, "agent connectionId " + agentConnectionId).sendInternalLogToServer(); + }; + var isBrowserSoftPhoneSupported = function isBrowserSoftPhoneSupported() { + // In Opera, the true version is after "Opera" or after "Version" + if (connect.isOperaBrowser() && connect.getOperaBrowserVersion() > 17) { + return true; + } + // In Chrome, the true version is after "Chrome" + else if (connect.isChromeBrowser() && connect.getChromeBrowserVersion() > 22) { + return true; + } + // In Firefox, the true version is after "Firefox" + else if (connect.isFirefoxBrowser() && connect.getFirefoxBrowserVersion() > 21) { + return true; + } else { + return false; + } + }; + var sendSoftphoneMetrics = function sendSoftphoneMetrics(contact) { + var streamStats = timeSeriesStreamStatsBuffer.slice(); + timeSeriesStreamStatsBuffer = []; + if (streamStats.length > 0) { + contact.sendSoftphoneMetrics(streamStats, { + success: function success() { + logger.info("sendSoftphoneMetrics success" + JSON.stringify(streamStats)).sendInternalLogToServer(); + }, + failure: function failure(data) { + logger.error("sendSoftphoneMetrics failed.").withObject(data).sendInternalLogToServer(); + } + }); + } + }; + var sendSoftphoneReport = function sendSoftphoneReport(contact, report, userAudioStats, remoteAudioStats) { + report.streamStats = [addStreamTypeToStats(userAudioStats, AUDIO_INPUT), addStreamTypeToStats(remoteAudioStats, AUDIO_OUTPUT)]; + var callReport = { + callStartTime: report.sessionStartTime, + callEndTime: report.sessionEndTime, + gumTimeMillis: report.gumTimeMillis, + initializationTimeMillis: report.initializationTimeMillis, + iceCollectionTimeMillis: report.iceCollectionTimeMillis, + signallingConnectTimeMillis: report.signallingConnectTimeMillis, + handshakingTimeMillis: report.handshakingTimeMillis, + preTalkingTimeMillis: report.preTalkingTimeMillis, + talkingTimeMillis: report.talkingTimeMillis, + cleanupTimeMillis: report.cleanupTimeMillis, + iceCollectionFailure: report.iceCollectionFailure, + signallingConnectionFailure: report.signallingConnectionFailure, + handshakingFailure: report.handshakingFailure, + gumOtherFailure: report.gumOtherFailure, + gumTimeoutFailure: report.gumTimeoutFailure, + createOfferFailure: report.createOfferFailure, + setLocalDescriptionFailure: report.setLocalDescriptionFailure, + userBusyFailure: report.userBusyFailure, + invalidRemoteSDPFailure: report.invalidRemoteSDPFailure, + noRemoteIceCandidateFailure: report.noRemoteIceCandidateFailure, + setRemoteDescriptionFailure: report.setRemoteDescriptionFailure, + softphoneStreamStatistics: report.streamStats + }; + contact.sendSoftphoneReport(callReport, { + success: function success() { + logger.info("sendSoftphoneReport success" + JSON.stringify(callReport)).sendInternalLogToServer(); + }, + failure: function failure(data) { + logger.error("sendSoftphoneReport failed.").withObject(data).sendInternalLogToServer(); + } + }); + }; + var startStatsCollectionJob = function startStatsCollectionJob(rtcSession) { + rtpStatsJob = window.setInterval(function () { + rtcSession.getUserAudioStats().then(function (stats) { + var previousUserStats = aggregatedUserAudioStats; + aggregatedUserAudioStats = stats; + timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedUserAudioStats, previousUserStats, AUDIO_INPUT)); + }, function (error) { + logger.debug("Failed to get user audio stats.", error).sendInternalLogToServer(); + }); + rtcSession.getRemoteAudioStats().then(function (stats) { + var previousRemoteStats = aggregatedRemoteAudioStats; + aggregatedRemoteAudioStats = stats; + timeSeriesStreamStatsBuffer.push(getTimeSeriesStats(aggregatedRemoteAudioStats, previousRemoteStats, AUDIO_OUTPUT)); + }, function (error) { + logger.debug("Failed to get remote audio stats.", error).sendInternalLogToServer(); + }); + }, 1000); + }; + var startStatsReportingJob = function startStatsReportingJob(contact) { + reportStatsJob = window.setInterval(function () { + sendSoftphoneMetrics(contact); + }, statsReportingJobIntervalMs); + }; + var initializeParams = function initializeParams() { + aggregatedUserAudioStats = null; + aggregatedRemoteAudioStats = null; + timeSeriesStreamStatsBuffer = []; + rtpStatsJob = null; + reportStatsJob = null; + }; + var getTimeSeriesStats = function getTimeSeriesStats(currentStats, previousStats, streamType) { + if (previousStats && currentStats) { + var packetsLost = currentStats.packetsLost > previousStats.packetsLost ? currentStats.packetsLost - previousStats.packetsLost : 0; + var packetsCount = currentStats.packetsCount > previousStats.packetsCount ? currentStats.packetsCount - previousStats.packetsCount : 0; + return new RTPStreamStats(currentStats.timestamp, packetsLost, packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); + } else { + return new RTPStreamStats(currentStats.timestamp, currentStats.packetsLost, currentStats.packetsCount, streamType, currentStats.audioLevel, currentStats.jbMilliseconds, currentStats.rttMilliseconds); + } + }; + var stopJob = function stopJob(task) { + if (task !== null) { + window.clearInterval(task); + } + return null; + }; + var stopJobsAndReport = function stopJobsAndReport(contact, sessionReport) { + rtpStatsJob = stopJob(rtpStatsJob); + reportStatsJob = stopJob(reportStatsJob); + sendSoftphoneReport(contact, sessionReport, addStreamTypeToStats(aggregatedUserAudioStats, AUDIO_INPUT), addStreamTypeToStats(aggregatedRemoteAudioStats, AUDIO_OUTPUT)); + sendSoftphoneMetrics(contact); + }; + + /** + * Adding streamtype parameter on top of RTCJS RTStats object. + */ + var RTPStreamStats = function RTPStreamStats(timestamp, packetsLost, packetsCount, streamType, audioLevel, jitterBufferMillis, roundTripTimeMillis) { + this.softphoneStreamType = streamType; + this.timestamp = timestamp; + this.packetsLost = packetsLost; + this.packetsCount = packetsCount; + this.audioLevel = audioLevel; + this.jitterBufferMillis = jitterBufferMillis; + this.roundTripTimeMillis = roundTripTimeMillis; + }; + var addStreamTypeToStats = function addStreamTypeToStats(stats, streamType) { + stats = stats || {}; + return new RTPStreamStats(stats.timestamp, stats.packetsLost, stats.packetsCount, streamType, stats.audioLevel); + }; + var SoftphoneLogger = function SoftphoneLogger(logger) { + this._originalLogger = logger; + var self = this; + this._tee = function (level, method) { + return function () { + // call the original logger object to output to browser + //Connect logger follows %s format to print objects to console. + var args = Array.prototype.slice.call(arguments[0]); + var format = ""; + args.forEach(function () { + format = format + " %s"; + }); + return method.apply(self._originalLogger, [connect.LogComponent.SOFTPHONE, format].concat(args)); + }; + }; + }; + SoftphoneLogger.prototype.debug = function () { + return this._tee(1, this._originalLogger.debug)(arguments); + }; + SoftphoneLogger.prototype.info = function () { + return this._tee(2, this._originalLogger.info)(arguments); + }; + SoftphoneLogger.prototype.log = function () { + return this._tee(3, this._originalLogger.log)(arguments); + }; + SoftphoneLogger.prototype.warn = function () { + return this._tee(4, this._originalLogger.warn)(arguments); + }; + SoftphoneLogger.prototype.error = function () { + return this._tee(5, this._originalLogger.error)(arguments); + }; + connect.SoftphoneManager = SoftphoneManager; +})(); - /** - * Calling a function with exponential backoff with full jitter retry strategy - * It will retry calling the function for maximum maxRetry times if it fails. - * Success callback will be called if the function succeeded. - * Failure callback will be called only if the last try failed. - */ - connect.backoff = function (func, milliInterval, maxRetry, callbacks) { - connect.assertTrue(connect.isFunction(func), "func must be a Function"); - var self = this; - var ratio = 2; - func({ - success: function success(data) { - if (callbacks && callbacks.success) { - callbacks.success(data); - } - }, - failure: function failure(err, data) { - if (maxRetry > 0) { - var interval = milliInterval * 2 * Math.random(); - global.setTimeout(function () { - self.backoff(func, interval * ratio, --maxRetry, callbacks); - }, interval); - } else { - if (callbacks && callbacks.failure) { - callbacks.failure(err, data); - } - } - } - }); - }; - connect.publishMetric = function (metricData) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.CLIENT_METRIC, - data: metricData - }); - }; - connect.publishSoftphoneStats = function (stats) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.SOFTPHONE_STATS, - data: stats - }); - }; - connect.publishSoftphoneReport = function (report) { - connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { - event: connect.EventType.SOFTPHONE_REPORT, - data: report - }); - }; - connect.publishClientSideLogs = function (logs) { - var bus = connect.core.getEventBus(); - bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); - }; +/***/ }), - /** - * A wrapper around Window.open() for managing single instance popups. - */ - connect.PopupManager = function () { }; - connect.PopupManager.prototype.open = function (url, name, options) { - var then = this._getLastOpenedTimestamp(name); - var now = new Date().getTime(); - var win = null; - if (now - then > ONE_DAY_MILLIS) { - if (options) { - // default values are chosen to provide a minimum height without scrolling - // and a uniform margin based on the css of the ccp login page - var height = options.height || DEFAULT_POPUP_HEIGHT; - var width = options.width || DEFAULT_POPUP_WIDTH; - var top = options.top || 0; - var left = options.left || 0; - win = window.open('', name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); - if (win.location !== url) { - win = window.open(url, name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); - } +/***/ 778: +/***/ (() => { + +/*! @license sprintf.js | Copyright (c) 2007-2013 Alexandru Marasteanu | 3 clause BSD license */ + +(function () { + var ctx = this; + var sprintf = function sprintf() { + if (!sprintf.cache.hasOwnProperty(arguments[0])) { + sprintf.cache[arguments[0]] = sprintf.parse(arguments[0]); + } + return sprintf.format.call(null, sprintf.cache[arguments[0]], arguments); + }; + sprintf.format = function (parse_tree, argv) { + var cursor = 1, + tree_length = parse_tree.length, + node_type = '', + arg, + output = [], + i, + k, + match, + pad, + pad_character, + pad_length; + for (i = 0; i < tree_length; i++) { + node_type = get_type(parse_tree[i]); + if (node_type === 'string') { + output.push(parse_tree[i]); + } else if (node_type === 'array') { + match = parse_tree[i]; // convenience purposes only + if (match[2]) { + // keyword argument + arg = argv[cursor]; + for (k = 0; k < match[2].length; k++) { + if (!arg.hasOwnProperty(match[2][k])) { + throw sprintf('[sprintf] property "%s" does not exist', match[2][k]); + } + arg = arg[match[2][k]]; + } + } else if (match[1]) { + // positional argument (explicit) + arg = argv[match[1]]; + } else { + // positional argument (implicit) + arg = argv[cursor++]; + } + if (/[^s]/.test(match[8]) && get_type(arg) != 'number') { + throw sprintf('[sprintf] expecting number but found %s', get_type(arg)); + } + switch (match[8]) { + case 'b': + arg = arg.toString(2); + break; + case 'c': + arg = String.fromCharCode(arg); + break; + case 'd': + arg = parseInt(arg, 10); + break; + case 'e': + arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); + break; + case 'f': + arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); + break; + case 'o': + arg = arg.toString(8); + break; + case 's': + arg = (arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg; + break; + case 'u': + arg = arg >>> 0; + break; + case 'x': + arg = arg.toString(16); + break; + case 'X': + arg = arg.toString(16).toUpperCase(); + break; + } + arg = /[def]/.test(match[8]) && match[3] && arg >= 0 ? '+' + arg : arg; + pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; + pad_length = match[6] - String(arg).length; + pad = match[6] ? str_repeat(pad_character, pad_length) : ''; + output.push(match[5] ? arg + pad : pad + arg); + } + } + return output.join(''); + }; + sprintf.cache = {}; + sprintf.parse = function (fmt) { + var _fmt = fmt, + match = [], + parse_tree = [], + arg_names = 0; + while (_fmt) { + if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { + parse_tree.push(match[0]); + } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { + parse_tree.push('%'); + } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { + if (match[2]) { + arg_names |= 1; + var field_list = [], + replacement_field = match[2], + field_match = []; + if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { + if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); + } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { + field_list.push(field_match[1]); } else { - win = window.open('', name); - if (win.location !== url) { - win = window.open(url, name); - } + throw '[sprintf] huh?'; } - this._setLastOpenedTimestamp(name, now); - } - return win; - }; - connect.PopupManager.prototype.clear = function (name) { - var key = this._getLocalStorageKey(name); - global.localStorage.removeItem(key); - }; - connect.PopupManager.prototype._getLastOpenedTimestamp = function (name) { - var key = this._getLocalStorageKey(name); - var value = global.localStorage.getItem(key); - if (value) { - return parseInt(value, 10); - } else { - return 0; } - }; - connect.PopupManager.prototype._setLastOpenedTimestamp = function (name, ts) { - var key = this._getLocalStorageKey(name); - global.localStorage.setItem(key, '' + ts); - }; - connect.PopupManager.prototype._getLocalStorageKey = function (name) { - return "connectPopupManager::" + name; - }; + } else { + throw '[sprintf] huh?'; + } + match[2] = field_list; + } else { + arg_names |= 2; + } + if (arg_names === 3) { + throw '[sprintf] mixing positional and named placeholders is not (yet) supported'; + } + parse_tree.push(match); + } else { + throw '[sprintf] huh?'; + } + _fmt = _fmt.substring(match[0].length); + } + return parse_tree; + }; + var vsprintf = function vsprintf(fmt, argv, _argv) { + _argv = argv.slice(0); + _argv.splice(0, 0, fmt); + return sprintf.apply(null, _argv); + }; + + /** + * helpers + */ + function get_type(variable) { + return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); + } + function str_repeat(input, multiplier) { + for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} + return output.join(''); + } + + /** + * export to either browser or node.js + */ + ctx.sprintf = sprintf; + ctx.vsprintf = vsprintf; +})(); - /** - * An enumeration of the HTML5 notification permission values. - */ - var NotificationPermission = connect.makeEnum(['granted', 'denied', 'default']); - - /** - * A simple engine for showing notification popups. - */ - connect.NotificationManager = function () { - this.queue = []; - this.permission = NotificationPermission.DEFAULT; - }; - connect.NotificationManager.prototype.requestPermission = function () { - var self = this; - if (!("Notification" in global)) { - connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(); - this.permission = NotificationPermission.DENIED; - } else if (global.Notification.permission === NotificationPermission.DENIED) { - connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(); - this.permission = NotificationPermission.DENIED; - } else if (this.permission !== NotificationPermission.GRANTED) { - global.Notification.requestPermission().then(function (permission) { - self.permission = permission; - if (permission === NotificationPermission.GRANTED) { - self._showQueued(); - } else { - self.queue = []; - } - }); - } - }; - connect.NotificationManager.prototype.show = function (title, options) { - if (this.permission === NotificationPermission.GRANTED) { - return this._showImpl({ - title: title, - options: options - }); - } else if (this.permission === NotificationPermission.DENIED) { - connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({ - title: title, - options: options - }); - } else { - var params = { - title: title, - options: options - }; - connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(params).sendInternalLogToServer(); - this.queue.push(params); - } - }; - connect.NotificationManager.prototype._showQueued = function () { - var self = this; - var notifications = this.queue.map(function (params) { - return self._showImpl(params); - }); - this.queue = []; - return notifications; - }; - connect.NotificationManager.prototype._showImpl = function (params) { - var notification = new global.Notification(params.title, params.options); - if (params.options.clicked) { - notification.onclick = function () { - params.options.clicked.call(notification); - }; - } - return notification; - }; - connect.BaseError = function (format, args) { - global.Error.call(this, connect.vsprintf(format, args)); - }; - connect.BaseError.prototype = Object.create(Error.prototype); - connect.BaseError.prototype.constructor = connect.BaseError; - connect.ValueError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.ValueError.prototype = Object.create(connect.BaseError.prototype); - connect.ValueError.prototype.constructor = connect.ValueError; - connect.NotImplementedError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); - connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; - connect.StateError = function () { - var args = Array.prototype.slice.call(arguments, 0); - var format = args.shift(); - connect.BaseError.call(this, format, args); - }; - connect.StateError.prototype = Object.create(connect.BaseError.prototype); - connect.StateError.prototype.constructor = connect.StateError; - connect.VoiceIdError = function (type, message, err) { - var error = {}; - error.type = type; - error.message = message; - error.stack = Error(message).stack; - error.err = err; - return error; - }; +/***/ }), - // internal use only - connect.isCCP = function () { - var conduit = connect.core.getUpstream(); - return conduit.name === 'ConnectSharedWorkerConduit'; - }; - })(); +/***/ 768: +/***/ (() => { - /***/ -}), +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; -/***/ 744: + /**--------------------------------------------------------------- + * class Stream + * + * Represents an object from which messages can be read and to which + * messages can be sent. + */ + var Stream = function Stream() {}; + + /** + * Send a message to the stream. This method must be implemented by subclasses. + */ + Stream.prototype.send = function (message) { + throw new connect.NotImplementedError(); + }; + + /** + * Provide a method to be called when messages are received from this stream. + * This method must be implemented by subclasses. + */ + Stream.prototype.onMessage = function (f) { + throw new connect.NotImplementedError(); + }; + + /**--------------------------------------------------------------- + * class NullStream extends Stream + * + * A null stream which provides no message sending or receiving facilities. + */ + var NullStream = function NullStream() { + Stream.call(this); + }; + NullStream.prototype = Object.create(Stream.prototype); + NullStream.prototype.constructor = NullStream; + NullStream.prototype.onMessage = function (f) {}; + NullStream.prototype.send = function (message) {}; + + /**--------------------------------------------------------------- + * class WindowStream extends Stream + * + * A stream for communicating with a window object. The domain provided + * must match the allowed message domains of the downstream receiver + * or messages will be rejected, see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage + * for more info. + */ + var WindowStream = function WindowStream(win, domain) { + Stream.call(this); + this.window = win; + this.domain = domain || '*'; + }; + WindowStream.prototype = Object.create(Stream.prototype); + WindowStream.prototype.constructor = WindowStream; + WindowStream.prototype.send = function (message) { + this.window.postMessage(message, this.domain); + }; + WindowStream.prototype.onMessage = function (f) { + this.window.addEventListener("message", f); + }; + + /**--------------------------------------------------------------- + * class WindowIOStream extends Stream + * + * A stream used by IFrame/popup windows to communicate with their parents + * and vise versa. + * + * This object encapsulates the fact that incoming and outgoing messages + * arrive on different windows and allows this to be managed as a single + * Stream object. + */ + var WindowIOStream = function WindowIOStream(inputwin, outputwin, domain) { + Stream.call(this); + this.input = inputwin; + this.output = outputwin; + this.domain = domain || '*'; + }; + WindowIOStream.prototype = Object.create(Stream.prototype); + WindowIOStream.prototype.constructor = WindowIOStream; + WindowIOStream.prototype.send = function (message) { + this.output.postMessage(message, this.domain); + }; + WindowIOStream.prototype.onMessage = function (f) { + var _this = this; + this.input.addEventListener("message", function (message) { + if (message.source === _this.output) { + f(message); + } + }); + }; + + /**--------------------------------------------------------------- + * class PortStream extends Stream + * + * A stream wrapping an HTML5 Worker port. This could be the port + * used to connect to a Worker or one of the multitude of ports + * made available to a SharedWorker for communication back to + * its connected clients. + */ + var PortStream = function PortStream(port) { + Stream.call(this); + this.port = port; + this.id = connect.randomId(); + }; + PortStream.prototype = Object.create(Stream.prototype); + PortStream.prototype.constructor = PortStream; + PortStream.prototype.send = function (message) { + this.port.postMessage(message); + }; + PortStream.prototype.onMessage = function (f) { + this.port.addEventListener("message", f); + }; + PortStream.prototype.getId = function () { + return this.id; + }; + + /**--------------------------------------------------------------- + * class StreamMultiplexer extends Stream + * + * A wrapper for multiplexed downstream communication with + * multiple streams at once. Mainly useful for the SharedWorker to + * broadcast events to many PortStream objects at once. + */ + var StreamMultiplexer = function StreamMultiplexer(streams) { + Stream.call(this); + this.streamMap = streams ? connect.index(streams, function (s) { + return s.getId(); + }) : {}; + this.messageListeners = []; + }; + StreamMultiplexer.prototype = Object.create(Stream.prototype); + StreamMultiplexer.prototype.constructor = StreamMultiplexer; + + /** + * Send a message to all ports in the multiplexer. + */ + StreamMultiplexer.prototype.send = function (message) { + this.getStreams().forEach(function (stream) { + try { + stream.send(message); + } catch (e) { + // Couldn't send message to one of the downstreams for some reason... + // No reliable logging possible without further failures, + // no recovery, just eat it. + } + }); + }; + + /** + * Register a method which will be called when a message is received from + * any of the downstreams. + */ + StreamMultiplexer.prototype.onMessage = function (f) { + this.messageListeners.push(f); + + // Update existing streams with the new listener. + this.getStreams().forEach(function (stream) { + stream.onMessage(f); + }); + }; + + /** + * Add a stream to the multiplexer. + */ + StreamMultiplexer.prototype.addStream = function (stream) { + var self = this; + this.streamMap[stream.getId()] = stream; + + // Update stream with existing listeners. + this.messageListeners.forEach(function (messageListener) { + stream.onMessage(messageListener); + }); + }; + + /** + * Remove the given downstream. This is typically used in response + * to the SharedWorker's onclose event, indicating that a consumer + * tab has been closed. + */ + StreamMultiplexer.prototype.removeStream = function (stream) { + delete this.streamMap[stream.getId()]; + }; + + /** + * Get a list of streams in the multiplexer. + */ + StreamMultiplexer.prototype.getStreams = function (stream) { + return connect.values(this.streamMap); + }; + + /** + * Get the stream matching the given port. + */ + StreamMultiplexer.prototype.getStreamForPort = function (port) { + return connect.find(this.getStreams(), function (s) { + return s.port === port; + }); + }; + + /**--------------------------------------------------------------- + * class Conduit + * + * An object which bridges an upstream and a downstream, allowing messages + * to be passed to and from each and providing an event bus for event + * subscriptions to be made upstream and downstream. + */ + var Conduit = function Conduit(name, upstream, downstream) { + this.name = name; + this.upstream = upstream || new NullStream(); + this.downstream = downstream || new NullStream(); + this.downstreamBus = new connect.EventBus(); + this.upstreamBus = new connect.EventBus(); + this.upstream.onMessage(connect.hitch(this, this._dispatchEvent, this.upstreamBus)); + this.downstream.onMessage(connect.hitch(this, this._dispatchEvent, this.downstreamBus)); + }; + Conduit.prototype.onUpstream = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.upstreamBus.subscribe(eventName, f); + }; + Conduit.prototype.onAllUpstream = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.upstreamBus.subscribeAll(f); + }; + Conduit.prototype.onDownstream = function (eventName, f) { + connect.assertNotNull(eventName, 'eventName'); + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.downstreamBus.subscribe(eventName, f); + }; + Conduit.prototype.onAllDownstream = function (f) { + connect.assertNotNull(f, 'f'); + connect.assertTrue(connect.isFunction(f), 'f must be a function'); + return this.downstreamBus.subscribeAll(f); + }; + Conduit.prototype.sendUpstream = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + this.upstream.send({ + event: eventName, + data: data + }); + }; + Conduit.prototype.sendDownstream = function (eventName, data) { + connect.assertNotNull(eventName, 'eventName'); + this.downstream.send({ + event: eventName, + data: data + }); + }; + Conduit.prototype._dispatchEvent = function (bus, messageEvent) { + var message = messageEvent.data; + if (message.event) { + bus.trigger(message.event, message.data); + } + }; + + /** + * Returns a closure which passes events upstream. + * + * Usage: + * conduit.onDownstream("MyEvent", conduit.passUpstream()); + */ + Conduit.prototype.passUpstream = function () { + var self = this; + return function (data, eventName) { + self.upstream.send({ + event: eventName, + data: data + }); + }; + }; + + /** + * Returns a closure which passes events downstream. + * + * Usage: + * conduit.onUpstream("MyEvent", conduit.passDownstream()); + */ + Conduit.prototype.passDownstream = function () { + var self = this; + return function (data, eventName) { + self.downstream.send({ + event: eventName, + data: data + }); + }; + }; + + /** + * Shutdown the conduit's event busses and remove all subscriptions. + */ + Conduit.prototype.shutdown = function () { + this.upstreamBus.unsubscribeAll(); + this.downstreamBus.unsubscribeAll(); + }; + + /**--------------------------------------------------------------- + * class IFrameConduit extends Conduit + * + * Creates a conduit for the given IFrame element. + */ + var IFrameConduit = function IFrameConduit(name, window, iframe, domain) { + Conduit.call(this, name, new WindowIOStream(window, iframe.contentWindow, domain || '*'), null); + }; + IFrameConduit.prototype = Object.create(Conduit.prototype); + IFrameConduit.prototype.constructor = IFrameConduit; + connect.Stream = Stream; + connect.NullStream = NullStream; + connect.WindowStream = WindowStream; + connect.WindowIOStream = WindowIOStream; + connect.PortStream = PortStream; + connect.StreamMultiplexer = StreamMultiplexer; + connect.Conduit = Conduit; + connect.IFrameConduit = IFrameConduit; +})(); + +/***/ }), + +/***/ 738: /***/ (() => { - /* - * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * SPDX-License-Identifier: Apache-2.0 - */ - (function () { - var global = this; - connect = global.connect || {}; - global.connect = connect; - global.lily = connect; - connect.worker = {}; - var GET_AGENT_TIMEOUT_MS = 30000; - var GET_AGENT_RECOVERY_TIMEOUT_MS = 5000; - var GET_AGENT_SUCCESS_TIMEOUT_MS = 100; - var LOG_BUFFER_CAP_SIZE = 400; - var CHECK_AUTH_TOKEN_INTERVAL_MS = 300000; // 5 minuts - var REFRESH_AUTH_TOKEN_INTERVAL_MS = 10000; // 10 seconds - var REFRESH_AUTH_TOKEN_MAX_TRY = 4; - var GET_AGENT_CONFIGURATION_INTERVAL_MS = 30000; - - /**-----------------------------------------------------------------------*/ - var MasterTopicCoordinator = function MasterTopicCoordinator() { - this.topicMasterMap = {}; - }; - MasterTopicCoordinator.prototype.getMaster = function (topic) { - connect.assertNotNull(topic, 'topic'); - return this.topicMasterMap[topic] || null; - }; - MasterTopicCoordinator.prototype.setMaster = function (topic, id) { - connect.assertNotNull(topic, 'topic'); - connect.assertNotNull(id, 'id'); - this.topicMasterMap[topic] = id; - }; - MasterTopicCoordinator.prototype.removeMaster = function (id) { - connect.assertNotNull(id, 'id'); - var self = this; - connect.entries(this.topicMasterMap).filter(function (entry) { - return entry.value === id; - }).forEach(function (entry) { - delete self.topicMasterMap[entry.key]; - }); - }; +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; - /**--------------------------------------------------------------- - * class WorkerClient extends ClientBase - */ - var WorkerClient = function WorkerClient(conduit) { - connect.ClientBase.call(this); - this.conduit = conduit; - }; - WorkerClient.prototype = Object.create(connect.ClientBase.prototype); - WorkerClient.prototype.constructor = WorkerClient; - WorkerClient.prototype._callImpl = function (method, params, callbacks) { - var self = this; - var request_start = new Date().getTime(); - if (connect.containsValue(connect.AgentAppClientMethods, method)) { - connect.core.getAgentAppClient()._callImpl(method, params, { - success: function success(data) { - self._recordAPILatency(method, request_start); - callbacks.success(data); - }, - failure: function failure(error) { - self._recordAPILatency(method, request_start, error); - callbacks.failure(error); - } - }); - } else { - connect.core.getClient()._callImpl(method, params, { - success: function success(data) { - self._recordAPILatency(method, request_start); - callbacks.success(data); - }, - failure: function failure(error, data) { - self._recordAPILatency(method, request_start, error); - callbacks.failure(error, data); - }, - authFailure: function authFailure() { - self._recordAPILatency(method, request_start); - callbacks.authFailure(); - }, - accessDenied: function accessDenied() { - callbacks.accessDenied && callbacks.accessDenied(); - } - }); - } - }; - WorkerClient.prototype._recordAPILatency = function (method, request_start, err) { - var request_end = new Date().getTime(); - var request_time = request_end - request_start; - this._sendAPIMetrics(method, request_time, err); - }; - WorkerClient.prototype._sendAPIMetrics = function (method, time, err) { - this.conduit.sendDownstream(connect.EventType.API_METRIC, { - name: method, - time: time, - dimensions: [{ - name: "Category", - value: "API" - }], - error: err - }); - }; + /**------------------------------------------------------------------------- + * GraphLink <> + * + * Represents the association of one or more attributes to a state transition. + */ + var GraphLink = function GraphLink(fromState, toState) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + this.fromState = fromState; + this.toState = toState; + }; + GraphLink.prototype.getAssociations = function (context) { + throw connect.NotImplementedError(); + }; + GraphLink.prototype.getFromState = function () { + return this.fromState; + }; + GraphLink.prototype.getToState = function () { + return this.toState; + }; + + /**------------------------------------------------------------------------- + * DirectGraphLink <> extends GraphLink + * + * Represents the by-value representation of one or more attributes to a + * state transition. + */ + var DirectGraphLink = function DirectGraphLink(fromState, toState, associations) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + connect.assertNotNull(associations, 'associations'); + GraphLink.call(this, fromState, toState); + this.associations = associations; + }; + DirectGraphLink.prototype = Object.create(GraphLink.prototype); + DirectGraphLink.prototype.constructor = DirectGraphLink; + DirectGraphLink.prototype.getAssociations = function (context) { + return this.associations; + }; + + /** + * FunctionalGraphLink <> extends GraphLink + * + * Represents a functional association of one or more attributes to a + * state transition. + */ + var FunctionalGraphLink = function FunctionalGraphLink(fromState, toState, closure) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + connect.assertNotNull(closure, 'closure'); + connect.assertTrue(connect.isFunction(closure), 'closure must be a function'); + GraphLink.call(this, fromState, toState); + this.closure = closure; + }; + FunctionalGraphLink.prototype = Object.create(GraphLink.prototype); + FunctionalGraphLink.prototype.constructor = FunctionalGraphLink; + FunctionalGraphLink.prototype.getAssociations = function (context) { + return this.closure(context, this.getFromState(), this.getToState()); + }; + + /**------------------------------------------------------------------------- + * EventGraph <> + * + * Builds a map of associations from one state to another in context of a + * particular object. The associations can be direct (one or more values) + * or functional (a method returning one or more values), and are used to + * provide additional contextual event hooks for the UI to consume. + */ + var EventGraph = function EventGraph() { + this.fromMap = {}; + }; + EventGraph.ANY = "<>"; + EventGraph.prototype.assoc = function (fromStateObj, toStateObj, assocObj) { + var self = this; + if (!fromStateObj) { + throw new Error("fromStateObj is not defined."); + } + if (!toStateObj) { + throw new Error("toStateObj is not defined."); + } + if (!assocObj) { + throw new Error("assocObj is not defined."); + } + if (fromStateObj instanceof Array) { + fromStateObj.forEach(function (fromState) { + self.assoc(fromState, toStateObj, assocObj); + }); + } else if (toStateObj instanceof Array) { + toStateObj.forEach(function (toState) { + self.assoc(fromStateObj, toState, assocObj); + }); + } else { + if (typeof assocObj === "function") { + this._addAssociation(new FunctionalGraphLink(fromStateObj, toStateObj, assocObj)); + } else if (assocObj instanceof Array) { + this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, assocObj)); + } else { + this._addAssociation(new DirectGraphLink(fromStateObj, toStateObj, [assocObj])); + } + } + return this; + }; + EventGraph.prototype.getAssociations = function (context, fromState, toState) { + connect.assertNotNull(fromState, 'fromState'); + connect.assertNotNull(toState, 'toState'); + var associations = []; + var toMapFromAny = this.fromMap[EventGraph.ANY] || {}; + var toMap = this.fromMap[fromState] || {}; + associations = associations.concat(this._getAssociationsFromMap(toMapFromAny, context, fromState, toState)); + associations = associations.concat(this._getAssociationsFromMap(toMap, context, fromState, toState)); + return associations; + }; + EventGraph.prototype._addAssociation = function (assoc) { + var toMap = this.fromMap[assoc.getFromState()]; + if (!toMap) { + toMap = this.fromMap[assoc.getFromState()] = {}; + } + var assocList = toMap[assoc.getToState()]; + if (!assocList) { + assocList = toMap[assoc.getToState()] = []; + } + assocList.push(assoc); + }; + EventGraph.prototype._getAssociationsFromMap = function (map, context, fromState, toState) { + var assocList = (map[EventGraph.ANY] || []).concat(map[toState] || []); + return assocList.reduce(function (prev, assoc) { + return prev.concat(assoc.getAssociations(context)); + }, []); + }; + connect.EventGraph = EventGraph; +})(); - /**------------------------------------------------------------------------- - * The object responsible for polling and passing data downstream to all - * consumer ports. - */ - var ClientEngine = function ClientEngine() { - var self = this; - this.multiplexer = new connect.StreamMultiplexer(); - this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer); - this.client = new WorkerClient(this.conduit); - this.timeout = null; - this.agent = null; - this.nextToken = null; - this.initData = {}; - this.portConduitMap = {}; - this.masterCoord = new MasterTopicCoordinator(); - this.logsBuffer = []; - this.suppress = false; - this.forceOffline = false; - var webSocketManager = null; - connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit); - this.conduit.onDownstream(connect.EventType.SEND_LOGS, function (logsToUpload) { - // Add softphone logs downstream - connect.getLog().pushLogsDownstream(logsToUpload); - self.logsBuffer = self.logsBuffer.concat(logsToUpload); - //only call API to send logs if buffer reached cap - if (self.logsBuffer.length > LOG_BUFFER_CAP_SIZE) { - self.handleSendLogsRequest(self.logsBuffer); - } - }); - this.conduit.onDownstream(connect.EventType.CONFIGURE, function (data) { - if (data.authToken && data.authToken !== self.initData.authToken) { - self.initData = data; - connect.core.init(data); - // init only once. - if (!webSocketManager) { - connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(); - connect.WebSocketManager.setGlobalConfig({ - loggerConfig: { - logger: connect.getLog() - } - }); - webSocketManager = connect.WebSocketManager.create(); - webSocketManager.onInitFailure(function () { - self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); - }); - webSocketManager.onConnectionOpen(function (response) { - self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, response); - }); - webSocketManager.onConnectionClose(function (response) { - self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, response); - }); - webSocketManager.onConnectionGain(function () { - self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED); - self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN); - }); - webSocketManager.onConnectionLost(function (response) { - self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, response); - self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, response); - }); - webSocketManager.onSubscriptionUpdate(function (response) { - self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, response); - }); - webSocketManager.onSubscriptionFailure(function (response) { - self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, response); - }); - webSocketManager.onAllMessage(function (response) { - self.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, response); - }); - self.conduit.onDownstream(connect.WebSocketEvents.SEND, function (message) { - webSocketManager.sendMessage(message); - }); - self.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, function (topics) { - webSocketManager.subscribeTopics(topics); - }); - webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function (response) { - if (response && !response.webSocketConnectionFailed) { - // Start polling for agent data. - connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(); - self.pollForAgent(); - connect.getLog().info("Kicking off config polling").sendInternalLogToServer(); - self.pollForAgentConfiguration({ - repeatForever: true - }); - connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(); - global.setInterval(connect.hitch(self, self.checkAuthToken), CHECK_AUTH_TOKEN_INTERVAL_MS); - } else { - if (!connect.webSocketInitFailed) { - self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); - connect.webSocketInitFailed = true; - } - } - }); - } else { - connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer(); - } - } - }); - this.conduit.onDownstream(connect.EventType.TERMINATE, function () { - //upload pending logs before terminating. - self.handleSendLogsRequest(self.logsBuffer); - connect.core.terminate(); - self.conduit.sendDownstream(connect.EventType.TERMINATED); - }); - this.conduit.onDownstream(connect.EventType.SYNCHRONIZE, function () { - self.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE); - }); - this.conduit.onDownstream(connect.EventType.BROADCAST, function (data) { - self.conduit.sendDownstream(data.event, data.data); - }); +/***/ }), - /** - * Called when a consumer port connects to this SharedWorker. - * Let's add them to our multiplexer. - */ - global.onconnect = function (event) { - var port = event.ports[0]; - var stream = new connect.PortStream(port); - self.multiplexer.addStream(stream); - port.start(); - var portConduit = new connect.Conduit(stream.getId(), null, stream); - portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { - id: stream.getId() - }); - self.portConduitMap[stream.getId()] = portConduit; - self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { - length: Object.keys(self.portConduitMap).length - }); - if (self.agent !== null) { - self.updateAgent(); - } - portConduit.onDownstream(connect.EventType.API_REQUEST, connect.hitch(self, self.handleAPIRequest, portConduit)); - portConduit.onDownstream(connect.EventType.MASTER_REQUEST, connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); - portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(self, self.pollForAgentConfiguration)); - portConduit.onDownstream(connect.EventType.CLOSE, function () { - self.multiplexer.removeStream(stream); - delete self.portConduitMap[stream.getId()]; - self.masterCoord.removeMaster(stream.getId()); - self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { - length: Object.keys(self.portConduitMap).length - }); - }); - }; - }; - ClientEngine.prototype.pollForAgent = function () { - var self = this; - var onAuthFail = connect.hitch(self, self.handleAuthFail); - this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT, { - nextToken: self.nextToken, - timeout: GET_AGENT_TIMEOUT_MS - }, { - success: function success(data) { - try { - self.agent = self.agent || {}; - self.agent.snapshot = data.snapshot; - self.agent.snapshot.localTimestamp = connect.now(); - self.agent.snapshot.skew = self.agent.snapshot.snapshotTimestamp - self.agent.snapshot.localTimestamp; - self.nextToken = data.nextToken; - connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(data).sendInternalLogToServer(); - self.updateAgent(); - } catch (e) { - connect.getLog().error("Long poll failed to update agent.").withObject(data).withException(e).sendInternalLogToServer(); - } finally { - global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_SUCCESS_TIMEOUT_MS); - } - }, - failure: function failure(err, data) { - try { - connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - } finally { - global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_RECOVERY_TIMEOUT_MS); - } - }, - authFailure: function authFailure() { - onAuthFail(); - }, - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.pollForAgentConfiguration = function (paramsIn) { - var self = this; - var params = paramsIn || {}; - var onAuthFail = connect.hitch(self, self.handleAuthFail); - this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION, {}, { - success: function success(data) { - var configuration = data.configuration; - self.pollForAgentPermissions(configuration); - self.pollForAgentStates(configuration); - self.pollForDialableCountryCodes(configuration); - self.pollForRoutingProfileQueues(configuration); - if (params.repeatForever) { - global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration, params), GET_AGENT_CONFIGURATION_INTERVAL_MS); - } - }, - failure: function failure(err, data) { - try { - connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - } finally { - if (params.repeatForever) { - global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration), GET_AGENT_CONFIGURATION_INTERVAL_MS, params); - } - } - }, - authFailure: function authFailure() { - onAuthFail(); - }, - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.pollForAgentStates = function (configuration, paramsIn) { - var self = this; - var params = paramsIn || {}; - params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_AGENT_STATES, { - nextToken: params.nextToken || null, - maxResults: params.maxResults - }, { - success: function success(data) { - if (data.nextToken) { - self.pollForAgentStates(configuration, { - states: (params.states || []).concat(data.states), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - } else { - configuration.agentStates = (params.states || []).concat(data.states); - self.updateAgentConfiguration(configuration); - } - }, - failure: function failure(err, data) { - connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.pollForAgentPermissions = function (configuration, paramsIn) { - var self = this; - var params = paramsIn || {}; - params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS, { - nextToken: params.nextToken || null, - maxResults: params.maxResults - }, { - success: function success(data) { - if (data.nextToken) { - self.pollForAgentPermissions(configuration, { - permissions: (params.permissions || []).concat(data.permissions), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - } else { - configuration.permissions = (params.permissions || []).concat(data.permissions); - self.updateAgentConfiguration(configuration); - } - }, - failure: function failure(err, data) { - connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.pollForDialableCountryCodes = function (configuration, paramsIn) { - var self = this; - var params = paramsIn || {}; - params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, { - nextToken: params.nextToken || null, - maxResults: params.maxResults - }, { - success: function success(data) { - if (data.nextToken) { - self.pollForDialableCountryCodes(configuration, { - countryCodes: (params.countryCodes || []).concat(data.countryCodes), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - } else { - configuration.dialableCountries = (params.countryCodes || []).concat(data.countryCodes); - self.updateAgentConfiguration(configuration); - } - }, - failure: function failure(err, data) { - connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.pollForRoutingProfileQueues = function (configuration, paramsIn) { - var self = this; - var params = paramsIn || {}; - params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; - this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES, { - routingProfileARN: configuration.routingProfile.routingProfileARN, - nextToken: params.nextToken || null, - maxResults: params.maxResults - }, { - success: function success(data) { - if (data.nextToken) { - self.pollForRoutingProfileQueues(configuration, { - countryCodes: (params.queues || []).concat(data.queues), - nextToken: data.nextToken, - maxResults: params.maxResults - }); - } else { - configuration.routingProfile.queues = (params.queues || []).concat(data.queues); - self.updateAgentConfiguration(configuration); - } - }, - failure: function failure(err, data) { - connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - }, - authFailure: connect.hitch(self, self.handleAuthFail), - accessDenied: connect.hitch(self, self.handleAccessDenied) - }); - }; - ClientEngine.prototype.handleAPIRequest = function (portConduit, request) { - var self = this; - this.client.call(request.method, request.params, { - success: function success(data) { - var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data); - portConduit.sendDownstream(response.event, response); - }, - failure: function failure(err, data) { - var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data, JSON.stringify(err)); - portConduit.sendDownstream(response.event, response); - connect.getLog().error("'%s' API request failed", request.method).withObject({ - request: self.filterAuthToken(request), - response: response - }).withException(err).sendInternalLogToServer(); - }, - authFailure: connect.hitch(self, self.handleAuthFail) - }); - }; +/***/ 420: +/***/ (() => { - /** - * Handle incoming master query or modification requests from connected tab ports. - */ - ClientEngine.prototype.handleMasterRequest = function (portConduit, portId, request) { - var multiplexerConduit = this.conduit; - var response = null; - switch (request.method) { - case connect.MasterMethods.BECOME_MASTER: - var masterId = this.masterCoord.getMaster(request.params.topic); - var takeOver = Boolean(masterId) && masterId !== portId; - this.masterCoord.setMaster(request.params.topic, portId); - response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { - masterId: portId, - takeOver: takeOver, - topic: request.params.topic - }); - if (takeOver) { - multiplexerConduit.sendDownstream(response.event, response); - } - break; - case connect.MasterMethods.CHECK_MASTER: - var masterId = this.masterCoord.getMaster(request.params.topic); - if (!masterId && !request.params.shouldNotBecomeMasterIfNone) { - this.masterCoord.setMaster(request.params.topic, portId); - masterId = portId; - } - response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { - masterId: masterId, - isMaster: portId === masterId, - topic: request.params.topic - }); - break; - default: - throw new Error("Unknown master method: " + request.method); - } - portConduit.sendDownstream(response.event, response); - }; - ClientEngine.prototype.updateAgentConfiguration = function (configuration) { - if (configuration.permissions && configuration.dialableCountries && configuration.agentStates && configuration.routingProfile.queues) { - this.agent = this.agent || {}; - this.agent.configuration = configuration; - this.updateAgent(); - } else { - connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer(); - } - }; - ClientEngine.prototype.updateAgent = function () { - if (!this.agent) { - connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer(); - } else if (!this.agent.snapshot) { - connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer(); - } else if (!this.agent.configuration) { - connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer(); - } else { - // Alias some of the properties for backwards compatibility. - this.agent.snapshot.status = this.agent.state; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + var userAgent = navigator.userAgent; + var ONE_DAY_MILLIS = 24 * 60 * 60 * 1000; + var DEFAULT_POPUP_HEIGHT = 578; + var DEFAULT_POPUP_WIDTH = 433; + var COPYABLE_EVENT_FIELDS = ["bubbles", "cancelBubble", "cancelable", "composed", "data", "defaultPrevented", "eventPhase", "isTrusted", "lastEventId", "origin", "returnValue", "timeStamp", "type"]; + + /** + * Unpollute sprintf functions from the global namespace. + */ + connect.sprintf = global.sprintf; + connect.vsprintf = global.vsprintf; + delete global.sprintf; + delete global.vsprintf; + connect.HTTP_STATUS_CODES = { + SUCCESS: 200, + TOO_MANY_REQUESTS: 429, + INTERNAL_SERVER_ERROR: 500 + }; + connect.TRANSPORT_TYPES = { + CHAT_TOKEN: "chat_token", + WEB_SOCKET: "web_socket" + }; + + /** + * Binds the given instance object as the context for + * the method provided. + * + * @param scope The instance object to be set as the scope + * of the function. + * @param method The method to be encapsulated. + * + * All other arguments, if any, are bound to the method + * invocation inside the closure. + * + * @return A closure encapsulating the invocation of the + * method provided in context of the given instance. + */ + connect.hitch = function () { + var args = Array.prototype.slice.call(arguments); + var scope = args.shift(); + var method = args.shift(); + connect.assertNotNull(scope, 'scope'); + connect.assertNotNull(method, 'method'); + connect.assertTrue(connect.isFunction(method), 'method must be a function'); + return function () { + var closureArgs = Array.prototype.slice.call(arguments); + return method.apply(scope, args.concat(closureArgs)); + }; + }; + + /** + * Determine if the given value is a callable function type. + * Borrowed from Underscore.js. + */ + connect.isFunction = function (obj) { + return !!(obj && obj.constructor && obj.call && obj.apply); + }; + + /** + * Determine if the given value is an array. + */ + connect.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + + /** + * Get a list of keys from a Javascript object used + * as a hash map. + */ + connect.keys = function (map) { + var keys = []; + connect.assertNotNull(map, 'map'); + for (var k in map) { + keys.push(k); + } + return keys; + }; + + /** + * Get a list of values from a Javascript object used + * as a hash map. + */ + connect.values = function (map) { + var values = []; + connect.assertNotNull(map, 'map'); + for (var k in map) { + values.push(map[k]); + } + return values; + }; + + /** + * Get a list of key/value pairs from the given map. + */ + connect.entries = function (map) { + var entries = []; + for (var k in map) { + entries.push({ + key: k, + value: map[k] + }); + } + return entries; + }; + + /** + * Merge two or more maps together into a new map, + * or simply copy a single map. + */ + connect.merge = function () { + var argMaps = Array.prototype.slice.call(arguments, 0); + var resultMap = {}; + argMaps.forEach(function (map) { + connect.entries(map).forEach(function (kv) { + resultMap[kv.key] = kv.value; + }); + }); + return resultMap; + }; + connect.now = function () { + return new Date().getTime(); + }; + connect.find = function (array, predicate) { + for (var x = 0; x < array.length; x++) { + if (predicate(array[x])) { + return array[x]; + } + } + return null; + }; + connect.contains = function (obj, value) { + if (obj instanceof Array) { + return connect.find(obj, function (v) { + return v === value; + }) != null; + } else { + return value in obj; + } + }; + connect.containsValue = function (obj, value) { + if (obj instanceof Array) { + return connect.find(obj, function (v) { + return v === value; + }) != null; + } else { + return connect.find(connect.values(obj), function (v) { + return v === value; + }) != null; + } + }; + + /** + * Generate a random ID consisting of the current timestamp + * and a random base-36 number based on Math.random(). + */ + connect.randomId = function () { + return connect.sprintf("%s-%s", connect.now(), Math.random().toString(36).slice(2)); + }; + + /** + * Generate an enum from the given list of lower-case enum values, + * where the enum keys will be upper case. + * + * Conversion from pascal case based on code from here: + * http://stackoverflow.com/questions/30521224 + */ + connect.makeEnum = function (values) { + var enumObj = {}; + values.forEach(function (value) { + var key = value.replace(/\.?([a-z]+)_?/g, function (x, y) { + return y.toUpperCase() + "_"; + }).replace(/_$/, ""); + enumObj[key] = value; + }); + return enumObj; + }; + connect.makeNamespacedEnum = function (prefix, values) { + var enumObj = connect.makeEnum(values); + connect.keys(enumObj).forEach(function (key) { + enumObj[key] = connect.sprintf("%s::%s", prefix, enumObj[key]); + }); + return enumObj; + }; + connect.makeGenericNamespacedEnum = function (prefix, values, delimiter) { + var enumObj = connect.makeEnum(values); + connect.keys(enumObj).forEach(function (key) { + enumObj[key] = connect.sprintf("%s" + delimiter + "%s", prefix, enumObj[key]); + }); + return enumObj; + }; + + /** + * Methods to determine browser type and versions, used for softphone initialization. + */ + connect.isChromeBrowser = function () { + return userAgent.indexOf("Chrome") !== -1; + }; + connect.isFirefoxBrowser = function () { + return userAgent.indexOf("Firefox") !== -1; + }; + connect.isOperaBrowser = function () { + return userAgent.indexOf("Opera") !== -1; + }; + connect.getChromeBrowserVersion = function () { + var chromeVersion = userAgent.substring(userAgent.indexOf("Chrome") + 7); + if (chromeVersion) { + return parseFloat(chromeVersion); + } else { + return -1; + } + }; + connect.getFirefoxBrowserVersion = function () { + var firefoxVersion = userAgent.substring(userAgent.indexOf("Firefox") + 8); + if (firefoxVersion) { + return parseFloat(firefoxVersion); + } else { + return -1; + } + }; + connect.isValidLocale = function (locale) { + var languages = [{ + id: 'en_US', + label: 'English' + }, { + id: 'de_DE', + label: 'Deutsch' + }, { + id: 'es_ES', + label: 'Español' + }, { + id: 'fr_FR', + label: 'Français' + }, { + id: 'ja_JP', + label: '日本語' + }, { + id: 'it_IT', + label: 'Italiano' + }, { + id: 'ko_KR', + label: '한국어' + }, { + id: 'pt_BR', + label: 'Português' + }, { + id: 'zh_CN', + label: '中文(简体)' + }, { + id: 'zh_TW', + label: '中文(繁體)' + }]; + return languages.map(function (language) { + return language.id; + }).includes(locale); + }; + connect.getOperaBrowserVersion = function () { + var versionOffset = userAgent.indexOf("Opera"); + var operaVersion = userAgent.indexOf("Version") !== -1 ? userAgent.substring(versionOffset + 8) : userAgent.substring(versionOffset + 6); + if (operaVersion) { + return parseFloat(operaVersion); + } else { + return -1; + } + }; + + /** + * Return a map of items in the given list indexed by + * keys determined by the closure provided. + * + * @param iterable A list-like object. + * @param closure A closure to determine the index for the + * items in the iterable. + * @return A map from index to item for each item in the iterable. + */ + connect.index = function (iterable, closure) { + var map = {}; + iterable.forEach(function (item) { + map[closure(item)] = item; + }); + return map; + }; + + /** + * Converts the given array into a map as a set, + * where elements in the array are mapped to 1. + */ + connect.set = function (arrayIn) { + var setMap = {}; + arrayIn.forEach(function (key) { + setMap[key] = 1; + }); + return setMap; + }; + + /** + * Returns a map for each key in mapB which + * is NOT in mapA. + */ + connect.relativeComplement = function (mapA, mapB) { + var compMap = {}; + connect.keys(mapB).forEach(function (key) { + if (!(key in mapA)) { + compMap[key] = mapB[key]; + } + }); + return compMap; + }; + + /** + * Asserts that a premise is true. + */ + connect.assertTrue = function (premise, message) { + if (!premise) { + throw new connect.ValueError(message); + } + }; + + /** + * Asserts that a value is not null or undefined. + */ + connect.assertNotNull = function (value, name) { + connect.assertTrue(value != null && _typeof(value) !== undefined, connect.sprintf("%s must be provided", name || 'A value')); + return value; + }; + connect.deepcopy = function (src) { + return JSON.parse(JSON.stringify(src)); + }; + connect.deepcopyCrossOriginEvent = function (event) { + var obj = {}; + var listOfAcceptableKeys = COPYABLE_EVENT_FIELDS; + listOfAcceptableKeys.forEach(function (key) { + try { + obj[key] = event[key]; + } catch (e) { + connect.getLog().info("deepcopyCrossOriginEvent failed on key: ", key).sendInternalLogToServer(); + } + }); + return connect.deepcopy(obj); + }; + + /** + * Get the current base url of the open page, e.g. if the page is + * https://example.com:9494/oranges, this will be "https://example.com:9494". + */ + connect.getBaseUrl = function () { + var location = global.location; + return connect.sprintf("%s//%s:%s", location.protocol, location.hostname, location.port); + }; + connect.getUrlWithProtocol = function (url) { + var protocol = global.location.protocol; + if (url.substr(0, protocol.length) !== protocol) { + return connect.sprintf("%s//%s", protocol, url); + } + return url; + }; + + /** + * Determine if the current window is in an iframe. + * Courtesy: http://stackoverflow.com/questions/326069/ + */ + connect.isFramed = function () { + try { + return window.self !== window.top; + } catch (e) { + return true; + } + }; + connect.hasOtherConnectedCCPs = function () { + return connect.numberOfConnectedCCPs > 1; + }; + connect.fetch = function (endpoint, options, milliInterval, maxRetry) { + maxRetry = maxRetry || 5; + milliInterval = milliInterval || 1000; + options = options || {}; + return new Promise(function (resolve, reject) { + function fetchData(maxRetry) { + fetch(endpoint, options).then(function (res) { + if (res.status === connect.HTTP_STATUS_CODES.SUCCESS) { + res.json().then(function (json) { + return resolve(json); + })["catch"](function () { + return resolve({}); + }); + } else if (maxRetry !== 1 && (res.status >= connect.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR || res.status === connect.HTTP_STATUS_CODES.TOO_MANY_REQUESTS)) { + setTimeout(function () { + fetchData(--maxRetry); + }, milliInterval); + } else { + reject(res); + } + })["catch"](function (e) { + reject(e); + }); + } + fetchData(maxRetry); + }); + }; + + /** + * Calling a function with exponential backoff with full jitter retry strategy + * It will retry calling the function for maximum maxRetry times if it fails. + * Success callback will be called if the function succeeded. + * Failure callback will be called only if the last try failed. + */ + connect.backoff = function (func, milliInterval, maxRetry, callbacks) { + connect.assertTrue(connect.isFunction(func), "func must be a Function"); + var self = this; + var ratio = 2; + func({ + success: function success(data) { + if (callbacks && callbacks.success) { + callbacks.success(data); + } + }, + failure: function failure(err, data) { + if (maxRetry > 0) { + var interval = milliInterval * 2 * Math.random(); + global.setTimeout(function () { + self.backoff(func, interval * ratio, --maxRetry, callbacks); + }, interval); + } else { + if (callbacks && callbacks.failure) { + callbacks.failure(err, data); + } + } + } + }); + }; + connect.publishMetric = function (metricData) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.CLIENT_METRIC, + data: metricData + }); + }; + connect.publishSoftphoneStats = function (stats) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.SOFTPHONE_STATS, + data: stats + }); + }; + connect.publishSoftphoneReport = function (report) { + connect.core.getUpstream().sendUpstream(connect.EventType.BROADCAST, { + event: connect.EventType.SOFTPHONE_REPORT, + data: report + }); + }; + connect.publishClientSideLogs = function (logs) { + var bus = connect.core.getEventBus(); + bus.trigger(connect.EventType.CLIENT_SIDE_LOGS, logs); + }; + + /** + * A wrapper around Window.open() for managing single instance popups. + */ + connect.PopupManager = function () {}; + connect.PopupManager.prototype.open = function (url, name, options) { + var then = this._getLastOpenedTimestamp(name); + var now = new Date().getTime(); + var win = null; + if (now - then > ONE_DAY_MILLIS) { + if (options) { + // default values are chosen to provide a minimum height without scrolling + // and a uniform margin based on the css of the ccp login page + var height = options.height || DEFAULT_POPUP_HEIGHT; + var width = options.width || DEFAULT_POPUP_WIDTH; + var top = options.top || 0; + var left = options.left || 0; + win = window.open('', name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); + if (win.location !== url) { + win = window.open(url, name, "width=" + width + ", height=" + height + ", top=" + top + ", left=" + left); + } + } else { + win = window.open('', name); + if (win.location !== url) { + win = window.open(url, name); + } + } + this._setLastOpenedTimestamp(name, now); + } + return win; + }; + connect.PopupManager.prototype.clear = function (name) { + var key = this._getLocalStorageKey(name); + global.localStorage.removeItem(key); + }; + connect.PopupManager.prototype._getLastOpenedTimestamp = function (name) { + var key = this._getLocalStorageKey(name); + var value = global.localStorage.getItem(key); + if (value) { + return parseInt(value, 10); + } else { + return 0; + } + }; + connect.PopupManager.prototype._setLastOpenedTimestamp = function (name, ts) { + var key = this._getLocalStorageKey(name); + global.localStorage.setItem(key, '' + ts); + }; + connect.PopupManager.prototype._getLocalStorageKey = function (name) { + return "connectPopupManager::" + name; + }; + + /** + * An enumeration of the HTML5 notification permission values. + */ + var NotificationPermission = connect.makeEnum(['granted', 'denied', 'default']); + + /** + * A simple engine for showing notification popups. + */ + connect.NotificationManager = function () { + this.queue = []; + this.permission = NotificationPermission.DEFAULT; + }; + connect.NotificationManager.prototype.requestPermission = function () { + var self = this; + if (!("Notification" in global)) { + connect.getLog().warn("This browser doesn't support notifications.").sendInternalLogToServer(); + this.permission = NotificationPermission.DENIED; + } else if (global.Notification.permission === NotificationPermission.DENIED) { + connect.getLog().warn("The user has requested to not receive notifications.").sendInternalLogToServer(); + this.permission = NotificationPermission.DENIED; + } else if (this.permission !== NotificationPermission.GRANTED) { + global.Notification.requestPermission().then(function (permission) { + self.permission = permission; + if (permission === NotificationPermission.GRANTED) { + self._showQueued(); + } else { + self.queue = []; + } + }); + } + }; + connect.NotificationManager.prototype.show = function (title, options) { + if (this.permission === NotificationPermission.GRANTED) { + return this._showImpl({ + title: title, + options: options + }); + } else if (this.permission === NotificationPermission.DENIED) { + connect.getLog().warn("Unable to show notification.").sendInternalLogToServer().withObject({ + title: title, + options: options + }); + } else { + var params = { + title: title, + options: options + }; + connect.getLog().warn("Deferring notification until user decides to allow or deny.").withObject(params).sendInternalLogToServer(); + this.queue.push(params); + } + }; + connect.NotificationManager.prototype._showQueued = function () { + var self = this; + var notifications = this.queue.map(function (params) { + return self._showImpl(params); + }); + this.queue = []; + return notifications; + }; + connect.NotificationManager.prototype._showImpl = function (params) { + var notification = new global.Notification(params.title, params.options); + if (params.options.clicked) { + notification.onclick = function () { + params.options.clicked.call(notification); + }; + } + return notification; + }; + connect.BaseError = function (format, args) { + global.Error.call(this, connect.vsprintf(format, args)); + }; + connect.BaseError.prototype = Object.create(Error.prototype); + connect.BaseError.prototype.constructor = connect.BaseError; + connect.ValueError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); + }; + connect.ValueError.prototype = Object.create(connect.BaseError.prototype); + connect.ValueError.prototype.constructor = connect.ValueError; + connect.NotImplementedError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); + }; + connect.NotImplementedError.prototype = Object.create(connect.BaseError.prototype); + connect.NotImplementedError.prototype.constructor = connect.NotImplementedError; + connect.StateError = function () { + var args = Array.prototype.slice.call(arguments, 0); + var format = args.shift(); + connect.BaseError.call(this, format, args); + }; + connect.StateError.prototype = Object.create(connect.BaseError.prototype); + connect.StateError.prototype.constructor = connect.StateError; + connect.VoiceIdError = function (type, message, err) { + var error = {}; + error.type = type; + error.message = message; + error.stack = Error(message).stack; + error.err = err; + return error; + }; + + // internal use only + connect.isCCP = function () { + var conduit = connect.core.getUpstream(); + return conduit.name === 'ConnectSharedWorkerConduit'; + }; +})(); - // Sort the contacts on the timestamp - if (this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1) { - this.agent.snapshot.contacts.sort(function (contactA, contactB) { - return contactA.state.timestamp.getTime() - contactB.state.timestamp.getTime(); - }); - } - this.agent.snapshot.contacts.forEach(function (contact) { - contact.status = contact.state; - contact.connections.forEach(function (connection) { - connection.address = connection.endpoint; - }); - }); - this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN; - this.agent.configuration.routingProfile.queues.forEach(function (queue) { - queue.queueId = queue.queueARN; - }); - this.agent.snapshot.contacts.forEach(function (contact) { - //contact.queue is null when monitoring - if (contact.queue !== undefined) { - contact.queue.queueId = contact.queue.queueARN; - } - }); - this.agent.configuration.routingProfile.routingProfileId = this.agent.configuration.routingProfile.routingProfileARN; - this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent); - } - }; +/***/ }), - /** - * Provides a websocket url through the create_transport API. - * @returns a promise which, upon success, returns the response from the createTransport API. - */ - ClientEngine.prototype.getWebSocketUrl = function () { - var self = this; - var client = connect.core.getClient(); - var onAuthFail = connect.hitch(self, self.handleAuthFail); - var onAccessDenied = connect.hitch(self, self.handleAccessDenied); - return new Promise(function (resolve, reject) { - client.call(connect.ClientMethods.CREATE_TRANSPORT, { - transportType: connect.TRANSPORT_TYPES.WEB_SOCKET - }, { - success: function success(data) { - connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(); - resolve(data); - }, - failure: function failure(err, data) { - connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({ - err: err, - data: data - }); - reject({ - reason: 'getWebSocketUrl failed', - _debug: err - }); - }, - authFailure: function authFailure() { - connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(); - reject(Error("Authentication failed while getting getWebSocketUrl")); - onAuthFail(); - }, - accessDenied: function accessDenied() { - connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(); - reject(Error("Access Denied Failure while getting getWebSocketUrl")); - onAccessDenied(); - } - }); - }); - }; +/***/ 744: +/***/ (() => { - /** - * Send a message downstream to all consumers when we detect that authentication - * against one of our APIs has failed. - */ - ClientEngine.prototype.handleSendLogsRequest = function () { - var self = this; - var logEvents = []; - var logsToSend = self.logsBuffer.slice(); - self.logsBuffer = []; - logsToSend.forEach(function (log) { - logEvents.push({ - timestamp: log.time, - component: log.component, - message: log.text - }); - }); - this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { - logEvents: logEvents - }, { - success: function success(data) { - connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer(); - }, - failure: function failure(err, data) { - connect.getLog().error("SendLogs request failed.").withObject(data).withException(err).sendInternalLogToServer(); - }, - authFailure: connect.hitch(self, self.handleAuthFail) - }); - }; - ClientEngine.prototype.handleAuthFail = function () { - var self = this; - self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); - }; - ClientEngine.prototype.handleAccessDenied = function () { - var self = this; - self.conduit.sendDownstream(connect.EventType.ACCESS_DENIED); - }; - ClientEngine.prototype.checkAuthToken = function () { - var self = this; - var expirationDate = new Date(self.initData.authTokenExpiration); - var currentTimeStamp = new Date().getTime(); - var thirtyMins = 30 * 60 * 1000; - - // refresh token 30 minutes before expiration - if (expirationDate.getTime() < currentTimeStamp + thirtyMins) { - connect.getLog().info("Auth token expires at " + expirationDate + " Start refreshing token with retry.").sendInternalLogToServer(); - connect.backoff(connect.hitch(self, self.authorize), REFRESH_AUTH_TOKEN_INTERVAL_MS, REFRESH_AUTH_TOKEN_MAX_TRY); +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ +(function () { + var global = this; + connect = global.connect || {}; + global.connect = connect; + global.lily = connect; + connect.worker = {}; + var GET_AGENT_TIMEOUT_MS = 30000; + var GET_AGENT_RECOVERY_TIMEOUT_MS = 5000; + var GET_AGENT_SUCCESS_TIMEOUT_MS = 100; + var LOG_BUFFER_CAP_SIZE = 400; + var CHECK_AUTH_TOKEN_INTERVAL_MS = 300000; // 5 minuts + var REFRESH_AUTH_TOKEN_INTERVAL_MS = 10000; // 10 seconds + var REFRESH_AUTH_TOKEN_MAX_TRY = 4; + var GET_AGENT_CONFIGURATION_INTERVAL_MS = 30000; + + /**-----------------------------------------------------------------------*/ + var MasterTopicCoordinator = function MasterTopicCoordinator() { + this.topicMasterMap = {}; + }; + MasterTopicCoordinator.prototype.getMaster = function (topic) { + connect.assertNotNull(topic, 'topic'); + return this.topicMasterMap[topic] || null; + }; + MasterTopicCoordinator.prototype.setMaster = function (topic, id) { + connect.assertNotNull(topic, 'topic'); + connect.assertNotNull(id, 'id'); + this.topicMasterMap[topic] = id; + }; + MasterTopicCoordinator.prototype.removeMaster = function (id) { + connect.assertNotNull(id, 'id'); + var self = this; + connect.entries(this.topicMasterMap).filter(function (entry) { + return entry.value === id; + }).forEach(function (entry) { + delete self.topicMasterMap[entry.key]; + }); + }; + + /**--------------------------------------------------------------- + * class WorkerClient extends ClientBase + */ + var WorkerClient = function WorkerClient(conduit) { + connect.ClientBase.call(this); + this.conduit = conduit; + }; + WorkerClient.prototype = Object.create(connect.ClientBase.prototype); + WorkerClient.prototype.constructor = WorkerClient; + WorkerClient.prototype._callImpl = function (method, params, callbacks) { + var self = this; + var request_start = new Date().getTime(); + if (connect.containsValue(connect.AgentAppClientMethods, method)) { + connect.core.getAgentAppClient()._callImpl(method, params, { + success: function success(data) { + self._recordAPILatency(method, request_start); + callbacks.success(data); + }, + failure: function failure(error) { + self._recordAPILatency(method, request_start, error); + callbacks.failure(error); + } + }); + } else { + connect.core.getClient()._callImpl(method, params, { + success: function success(data) { + self._recordAPILatency(method, request_start); + callbacks.success(data); + }, + failure: function failure(error, data) { + self._recordAPILatency(method, request_start, error); + callbacks.failure(error, data); + }, + authFailure: function authFailure() { + self._recordAPILatency(method, request_start); + callbacks.authFailure(); + }, + accessDenied: function accessDenied() { + callbacks.accessDenied && callbacks.accessDenied(); + } + }); + } + }; + WorkerClient.prototype._recordAPILatency = function (method, request_start, err) { + var request_end = new Date().getTime(); + var request_time = request_end - request_start; + this._sendAPIMetrics(method, request_time, err); + }; + WorkerClient.prototype._sendAPIMetrics = function (method, time, err) { + this.conduit.sendDownstream(connect.EventType.API_METRIC, { + name: method, + time: time, + dimensions: [{ + name: "Category", + value: "API" + }], + error: err + }); + }; + + /**------------------------------------------------------------------------- + * The object responsible for polling and passing data downstream to all + * consumer ports. + */ + var ClientEngine = function ClientEngine() { + var self = this; + this.multiplexer = new connect.StreamMultiplexer(); + this.conduit = new connect.Conduit("AmazonConnectSharedWorker", null, this.multiplexer); + this.client = new WorkerClient(this.conduit); + this.timeout = null; + this.agent = null; + this.nextToken = null; + this.initData = {}; + this.portConduitMap = {}; + this.masterCoord = new MasterTopicCoordinator(); + this.logsBuffer = []; + this.suppress = false; + this.forceOffline = false; + var webSocketManager = null; + connect.rootLogger = new connect.DownstreamConduitLogger(this.conduit); + this.conduit.onDownstream(connect.EventType.SEND_LOGS, function (logsToUpload) { + // Add softphone logs downstream + connect.getLog().pushLogsDownstream(logsToUpload); + self.logsBuffer = self.logsBuffer.concat(logsToUpload); + //only call API to send logs if buffer reached cap + if (self.logsBuffer.length > LOG_BUFFER_CAP_SIZE) { + self.handleSendLogsRequest(self.logsBuffer); + } + }); + this.conduit.onDownstream(connect.EventType.CONFIGURE, function (data) { + if (data.authToken && data.authToken !== self.initData.authToken) { + self.initData = data; + connect.core.init(data); + // init only once. + if (!webSocketManager) { + connect.getLog().info("Creating a new Websocket connection for CCP").sendInternalLogToServer(); + connect.WebSocketManager.setGlobalConfig({ + loggerConfig: { + logger: connect.getLog() } - }; - ClientEngine.prototype.authorize = function (callbacks) { - var self = this; - connect.core.authorize(this.initData.authorizeEndpoint).then(function (response) { - var expiration = new Date(response.expiration); - connect.getLog().info("Authorization succeeded and the token expires at %s", expiration).sendInternalLogToServer(); - self.initData.authToken = response.accessToken; - self.initData.authTokenExpiration = expiration; - connect.core.initClient(self.initData); - connect.core.initAgentAppClient(self.initData); - callbacks.success(); - })["catch"](function (response) { - connect.getLog().error("Authorization failed with code %s", response.status).sendInternalLogToServer(); - if (response.status === 401) { - self.handleAuthFail(); - } else { - callbacks.failure(); - } - }); - }; - - /** - * Filter the 'authentication' field of the request params from the given API_REQUEST event. - */ - ClientEngine.prototype.filterAuthToken = function (request) { - var new_request = {}; - for (var keyA in request) { - if (keyA === 'params') { - var new_params = {}; - for (var keyB in request.params) { - if (keyB !== 'authentication') { - new_params[keyB] = request.params[keyB]; - } - } - new_request.params = new_params; - } else { - new_request[keyA] = request[keyA]; + }); + webSocketManager = connect.WebSocketManager.create(); + webSocketManager.onInitFailure(function () { + self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); + }); + webSocketManager.onConnectionOpen(function (response) { + self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_OPEN, response); + }); + webSocketManager.onConnectionClose(function (response) { + self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_CLOSE, response); + }); + webSocketManager.onConnectionGain(function () { + self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_GAINED); + self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_GAIN); + }); + webSocketManager.onConnectionLost(function (response) { + self.conduit.sendDownstream(connect.AgentEvents.WEBSOCKET_CONNECTION_LOST, response); + self.conduit.sendDownstream(connect.WebSocketEvents.CONNECTION_LOST, response); + }); + webSocketManager.onSubscriptionUpdate(function (response) { + self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_UPDATE, response); + }); + webSocketManager.onSubscriptionFailure(function (response) { + self.conduit.sendDownstream(connect.WebSocketEvents.SUBSCRIPTION_FAILURE, response); + }); + webSocketManager.onAllMessage(function (response) { + self.conduit.sendDownstream(connect.WebSocketEvents.ALL_MESSAGE, response); + }); + self.conduit.onDownstream(connect.WebSocketEvents.SEND, function (message) { + webSocketManager.sendMessage(message); + }); + self.conduit.onDownstream(connect.WebSocketEvents.SUBSCRIBE, function (topics) { + webSocketManager.subscribeTopics(topics); + }); + webSocketManager.init(connect.hitch(self, self.getWebSocketUrl)).then(function (response) { + if (response && !response.webSocketConnectionFailed) { + // Start polling for agent data. + connect.getLog().info("Kicking off agent polling").sendInternalLogToServer(); + self.pollForAgent(); + connect.getLog().info("Kicking off config polling").sendInternalLogToServer(); + self.pollForAgentConfiguration({ + repeatForever: true + }); + connect.getLog().info("Kicking off auth token polling").sendInternalLogToServer(); + global.setInterval(connect.hitch(self, self.checkAuthToken), CHECK_AUTH_TOKEN_INTERVAL_MS); + } else { + if (!connect.webSocketInitFailed) { + self.conduit.sendDownstream(connect.WebSocketEvents.INIT_FAILURE); + connect.webSocketInitFailed = true; } } - return new_request; - }; - - /**-----------------------------------------------------------------------*/ - connect.worker.main = function () { - connect.worker.clientEngine = new ClientEngine(); - }; - })(); + }); + } else { + connect.getLog().info("Not Initializing a new WebsocketManager instance, since one already exists").sendInternalLogToServer(); + } + } + }); + this.conduit.onDownstream(connect.EventType.TERMINATE, function () { + //upload pending logs before terminating. + self.handleSendLogsRequest(self.logsBuffer); + connect.core.terminate(); + self.conduit.sendDownstream(connect.EventType.TERMINATED); + }); + this.conduit.onDownstream(connect.EventType.SYNCHRONIZE, function () { + self.conduit.sendDownstream(connect.EventType.ACKNOWLEDGE); + }); + this.conduit.onDownstream(connect.EventType.BROADCAST, function (data) { + self.conduit.sendDownstream(data.event, data.data); + }); + + /** + * Called when a consumer port connects to this SharedWorker. + * Let's add them to our multiplexer. + */ + global.onconnect = function (event) { + var port = event.ports[0]; + var stream = new connect.PortStream(port); + self.multiplexer.addStream(stream); + port.start(); + var portConduit = new connect.Conduit(stream.getId(), null, stream); + portConduit.sendDownstream(connect.EventType.ACKNOWLEDGE, { + id: stream.getId() + }); + self.portConduitMap[stream.getId()] = portConduit; + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { + length: Object.keys(self.portConduitMap).length + }); + if (self.agent !== null) { + self.updateAgent(); + } + portConduit.onDownstream(connect.EventType.API_REQUEST, connect.hitch(self, self.handleAPIRequest, portConduit)); + portConduit.onDownstream(connect.EventType.MASTER_REQUEST, connect.hitch(self, self.handleMasterRequest, portConduit, stream.getId())); + portConduit.onDownstream(connect.EventType.RELOAD_AGENT_CONFIGURATION, connect.hitch(self, self.pollForAgentConfiguration)); + portConduit.onDownstream(connect.EventType.CLOSE, function () { + self.multiplexer.removeStream(stream); + delete self.portConduitMap[stream.getId()]; + self.masterCoord.removeMaster(stream.getId()); + self.conduit.sendDownstream(connect.EventType.UPDATE_CONNECTED_CCPS, { + length: Object.keys(self.portConduitMap).length + }); + }); + }; + }; + ClientEngine.prototype.pollForAgent = function () { + var self = this; + var onAuthFail = connect.hitch(self, self.handleAuthFail); + this.client.call(connect.ClientMethods.GET_AGENT_SNAPSHOT, { + nextToken: self.nextToken, + timeout: GET_AGENT_TIMEOUT_MS + }, { + success: function success(data) { + try { + self.agent = self.agent || {}; + self.agent.snapshot = data.snapshot; + self.agent.snapshot.localTimestamp = connect.now(); + self.agent.snapshot.skew = self.agent.snapshot.snapshotTimestamp - self.agent.snapshot.localTimestamp; + self.nextToken = data.nextToken; + connect.getLog().trace("GET_AGENT_SNAPSHOT succeeded.").withObject(data).sendInternalLogToServer(); + self.updateAgent(); + } catch (e) { + connect.getLog().error("Long poll failed to update agent.").withObject(data).withException(e).sendInternalLogToServer(); + } finally { + global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_SUCCESS_TIMEOUT_MS); + } + }, + failure: function failure(err, data) { + try { + connect.getLog().error("Failed to get agent data.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + } finally { + global.setTimeout(connect.hitch(self, self.pollForAgent), GET_AGENT_RECOVERY_TIMEOUT_MS); + } + }, + authFailure: function authFailure() { + onAuthFail(); + }, + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.pollForAgentConfiguration = function (paramsIn) { + var self = this; + var params = paramsIn || {}; + var onAuthFail = connect.hitch(self, self.handleAuthFail); + this.client.call(connect.ClientMethods.GET_AGENT_CONFIGURATION, {}, { + success: function success(data) { + var configuration = data.configuration; + self.pollForAgentPermissions(configuration); + self.pollForAgentStates(configuration); + self.pollForDialableCountryCodes(configuration); + self.pollForRoutingProfileQueues(configuration); + if (params.repeatForever) { + global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration, params), GET_AGENT_CONFIGURATION_INTERVAL_MS); + } + }, + failure: function failure(err, data) { + try { + connect.getLog().error("Failed to fetch agent configuration data.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + } finally { + if (params.repeatForever) { + global.setTimeout(connect.hitch(self, self.pollForAgentConfiguration), GET_AGENT_CONFIGURATION_INTERVAL_MS, params); + } + } + }, + authFailure: function authFailure() { + onAuthFail(); + }, + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.pollForAgentStates = function (configuration, paramsIn) { + var self = this; + var params = paramsIn || {}; + params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; + this.client.call(connect.ClientMethods.GET_AGENT_STATES, { + nextToken: params.nextToken || null, + maxResults: params.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.pollForAgentStates(configuration, { + states: (params.states || []).concat(data.states), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.agentStates = (params.states || []).concat(data.states); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch agent states list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.pollForAgentPermissions = function (configuration, paramsIn) { + var self = this; + var params = paramsIn || {}; + params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; + this.client.call(connect.ClientMethods.GET_AGENT_PERMISSIONS, { + nextToken: params.nextToken || null, + maxResults: params.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.pollForAgentPermissions(configuration, { + permissions: (params.permissions || []).concat(data.permissions), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.permissions = (params.permissions || []).concat(data.permissions); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch agent permissions list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.pollForDialableCountryCodes = function (configuration, paramsIn) { + var self = this; + var params = paramsIn || {}; + params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; + this.client.call(connect.ClientMethods.GET_DIALABLE_COUNTRY_CODES, { + nextToken: params.nextToken || null, + maxResults: params.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.pollForDialableCountryCodes(configuration, { + countryCodes: (params.countryCodes || []).concat(data.countryCodes), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.dialableCountries = (params.countryCodes || []).concat(data.countryCodes); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch dialable country codes list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.pollForRoutingProfileQueues = function (configuration, paramsIn) { + var self = this; + var params = paramsIn || {}; + params.maxResults = params.maxResults || connect.DEFAULT_BATCH_SIZE; + this.client.call(connect.ClientMethods.GET_ROUTING_PROFILE_QUEUES, { + routingProfileARN: configuration.routingProfile.routingProfileARN, + nextToken: params.nextToken || null, + maxResults: params.maxResults + }, { + success: function success(data) { + if (data.nextToken) { + self.pollForRoutingProfileQueues(configuration, { + countryCodes: (params.queues || []).concat(data.queues), + nextToken: data.nextToken, + maxResults: params.maxResults + }); + } else { + configuration.routingProfile.queues = (params.queues || []).concat(data.queues); + self.updateAgentConfiguration(configuration); + } + }, + failure: function failure(err, data) { + connect.getLog().error("Failed to fetch routing profile queues list.").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + }, + authFailure: connect.hitch(self, self.handleAuthFail), + accessDenied: connect.hitch(self, self.handleAccessDenied) + }); + }; + ClientEngine.prototype.handleAPIRequest = function (portConduit, request) { + var self = this; + this.client.call(request.method, request.params, { + success: function success(data) { + var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data); + portConduit.sendDownstream(response.event, response); + }, + failure: function failure(err, data) { + var response = connect.EventFactory.createResponse(connect.EventType.API_RESPONSE, request, data, JSON.stringify(err)); + portConduit.sendDownstream(response.event, response); + connect.getLog().error("'%s' API request failed", request.method).withObject({ + request: self.filterAuthToken(request), + response: response + }).withException(err).sendInternalLogToServer(); + }, + authFailure: connect.hitch(self, self.handleAuthFail) + }); + }; + + /** + * Handle incoming master query or modification requests from connected tab ports. + */ + ClientEngine.prototype.handleMasterRequest = function (portConduit, portId, request) { + var multiplexerConduit = this.conduit; + var response = null; + switch (request.method) { + case connect.MasterMethods.BECOME_MASTER: + var masterId = this.masterCoord.getMaster(request.params.topic); + var takeOver = Boolean(masterId) && masterId !== portId; + this.masterCoord.setMaster(request.params.topic, portId); + response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { + masterId: portId, + takeOver: takeOver, + topic: request.params.topic + }); + if (takeOver) { + multiplexerConduit.sendDownstream(response.event, response); + } + break; + case connect.MasterMethods.CHECK_MASTER: + var masterId = this.masterCoord.getMaster(request.params.topic); + if (!masterId && !request.params.shouldNotBecomeMasterIfNone) { + this.masterCoord.setMaster(request.params.topic, portId); + masterId = portId; + } + response = connect.EventFactory.createResponse(connect.EventType.MASTER_RESPONSE, request, { + masterId: masterId, + isMaster: portId === masterId, + topic: request.params.topic + }); + break; + default: + throw new Error("Unknown master method: " + request.method); + } + portConduit.sendDownstream(response.event, response); + }; + ClientEngine.prototype.updateAgentConfiguration = function (configuration) { + if (configuration.permissions && configuration.dialableCountries && configuration.agentStates && configuration.routingProfile.queues) { + this.agent = this.agent || {}; + this.agent.configuration = configuration; + this.updateAgent(); + } else { + connect.getLog().trace("Waiting to update agent configuration until all config data has been fetched.").sendInternalLogToServer(); + } + }; + ClientEngine.prototype.updateAgent = function () { + if (!this.agent) { + connect.getLog().trace("Waiting to update agent until the agent has been fully constructed.").sendInternalLogToServer(); + } else if (!this.agent.snapshot) { + connect.getLog().trace("Waiting to update agent until the agent snapshot is available.").sendInternalLogToServer(); + } else if (!this.agent.configuration) { + connect.getLog().trace("Waiting to update agent until the agent configuration is available.").sendInternalLogToServer(); + } else { + // Alias some of the properties for backwards compatibility. + this.agent.snapshot.status = this.agent.state; + + // Sort the contacts on the timestamp + if (this.agent.snapshot.contacts && this.agent.snapshot.contacts.length > 1) { + this.agent.snapshot.contacts.sort(function (contactA, contactB) { + return contactA.state.timestamp.getTime() - contactB.state.timestamp.getTime(); + }); + } + this.agent.snapshot.contacts.forEach(function (contact) { + contact.status = contact.state; + contact.connections.forEach(function (connection) { + connection.address = connection.endpoint; + }); + }); + this.agent.configuration.routingProfile.defaultOutboundQueue.queueId = this.agent.configuration.routingProfile.defaultOutboundQueue.queueARN; + this.agent.configuration.routingProfile.queues.forEach(function (queue) { + queue.queueId = queue.queueARN; + }); + this.agent.snapshot.contacts.forEach(function (contact) { + //contact.queue is null when monitoring + if (contact.queue !== undefined) { + contact.queue.queueId = contact.queue.queueARN; + } + }); + this.agent.configuration.routingProfile.routingProfileId = this.agent.configuration.routingProfile.routingProfileARN; + this.conduit.sendDownstream(connect.AgentEvents.UPDATE, this.agent); + } + }; + + /** + * Provides a websocket url through the create_transport API. + * @returns a promise which, upon success, returns the response from the createTransport API. + */ + ClientEngine.prototype.getWebSocketUrl = function () { + var self = this; + var client = connect.core.getClient(); + var onAuthFail = connect.hitch(self, self.handleAuthFail); + var onAccessDenied = connect.hitch(self, self.handleAccessDenied); + return new Promise(function (resolve, reject) { + client.call(connect.ClientMethods.CREATE_TRANSPORT, { + transportType: connect.TRANSPORT_TYPES.WEB_SOCKET + }, { + success: function success(data) { + connect.getLog().info("getWebSocketUrl succeeded").sendInternalLogToServer(); + resolve(data); + }, + failure: function failure(err, data) { + connect.getLog().error("getWebSocketUrl failed").sendInternalLogToServer().withObject({ + err: err, + data: data + }); + reject({ + reason: 'getWebSocketUrl failed', + _debug: err + }); + }, + authFailure: function authFailure() { + connect.getLog().error("getWebSocketUrl Auth Failure").sendInternalLogToServer(); + reject(Error("Authentication failed while getting getWebSocketUrl")); + onAuthFail(); + }, + accessDenied: function accessDenied() { + connect.getLog().error("getWebSocketUrl Access Denied Failure").sendInternalLogToServer(); + reject(Error("Access Denied Failure while getting getWebSocketUrl")); + onAccessDenied(); + } + }); + }); + }; + + /** + * Send a message downstream to all consumers when we detect that authentication + * against one of our APIs has failed. + */ + ClientEngine.prototype.handleSendLogsRequest = function () { + var self = this; + var logEvents = []; + var logsToSend = self.logsBuffer.slice(); + self.logsBuffer = []; + logsToSend.forEach(function (log) { + logEvents.push({ + timestamp: log.time, + component: log.component, + message: log.text + }); + }); + this.client.call(connect.ClientMethods.SEND_CLIENT_LOGS, { + logEvents: logEvents + }, { + success: function success(data) { + connect.getLog().info("SendLogs request succeeded.").sendInternalLogToServer(); + }, + failure: function failure(err, data) { + connect.getLog().error("SendLogs request failed.").withObject(data).withException(err).sendInternalLogToServer(); + }, + authFailure: connect.hitch(self, self.handleAuthFail) + }); + }; + ClientEngine.prototype.handleAuthFail = function () { + var self = this; + self.conduit.sendDownstream(connect.EventType.AUTH_FAIL); + }; + ClientEngine.prototype.handleAccessDenied = function () { + var self = this; + self.conduit.sendDownstream(connect.EventType.ACCESS_DENIED); + }; + ClientEngine.prototype.checkAuthToken = function () { + var self = this; + var expirationDate = new Date(self.initData.authTokenExpiration); + var currentTimeStamp = new Date().getTime(); + var thirtyMins = 30 * 60 * 1000; + + // refresh token 30 minutes before expiration + if (expirationDate.getTime() < currentTimeStamp + thirtyMins) { + connect.getLog().info("Auth token expires at " + expirationDate + " Start refreshing token with retry.").sendInternalLogToServer(); + connect.backoff(connect.hitch(self, self.authorize), REFRESH_AUTH_TOKEN_INTERVAL_MS, REFRESH_AUTH_TOKEN_MAX_TRY); + } + }; + ClientEngine.prototype.authorize = function (callbacks) { + var self = this; + connect.core.authorize(this.initData.authorizeEndpoint).then(function (response) { + var expiration = new Date(response.expiration); + connect.getLog().info("Authorization succeeded and the token expires at %s", expiration).sendInternalLogToServer(); + self.initData.authToken = response.accessToken; + self.initData.authTokenExpiration = expiration; + connect.core.initClient(self.initData); + connect.core.initAgentAppClient(self.initData); + callbacks.success(); + })["catch"](function (response) { + connect.getLog().error("Authorization failed with code %s", response.status).sendInternalLogToServer(); + if (response.status === 401) { + self.handleAuthFail(); + } else { + callbacks.failure(); + } + }); + }; + + /** + * Filter the 'authentication' field of the request params from the given API_REQUEST event. + */ + ClientEngine.prototype.filterAuthToken = function (request) { + var new_request = {}; + for (var keyA in request) { + if (keyA === 'params') { + var new_params = {}; + for (var keyB in request.params) { + if (keyB !== 'authentication') { + new_params[keyB] = request.params[keyB]; + } + } + new_request.params = new_params; + } else { + new_request[keyA] = request[keyA]; + } + } + return new_request; + }; + + /**-----------------------------------------------------------------------*/ + connect.worker.main = function () { + connect.worker.clientEngine = new ClientEngine(); + }; +})(); - /***/ -}) +/***/ }) - /******/ -}); +/******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; -/******/ +/******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; - /******/ -} +/******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} - /******/ -}; -/******/ +/******/ }; +/******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); -/******/ +/******/ /******/ // Return the exports of the module /******/ return module.exports; - /******/ -} -/******/ +/******/ } +/******/ /************************************************************************/ /******/ /* webpack/runtime/amd options */ /******/ (() => { /******/ __webpack_require__.amdO = {}; - /******/ -})(); -/******/ +/******/ })(); +/******/ /******/ /* webpack/runtime/global */ /******/ (() => { -/******/ __webpack_require__.g = (function () { +/******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); - /******/ -} catch (e) { +/******/ } catch (e) { /******/ if (typeof window === 'object') return window; - /******/ -} - /******/ -})(); - /******/ -})(); -/******/ +/******/ } +/******/ })(); +/******/ })(); +/******/ /************************************************************************/ -/******/ +/******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module used 'module' so it can't be inlined @@ -13607,7 +12667,6 @@ /******/ __webpack_require__(487); /******/ __webpack_require__(340); /******/ var __webpack_exports__ = __webpack_require__(228); - /******/ - /******/ -})() - ; \ No newline at end of file +/******/ +/******/ })() +; \ No newline at end of file diff --git a/src/request-storage-access.js b/src/request-storage-access.js index 65af146..b54ef9c 100644 --- a/src/request-storage-access.js +++ b/src/request-storage-access.js @@ -106,7 +106,7 @@ storageParams && storageParams.mode !== "default"; const isConnectDomain = (origin) => - origin.match(/.connect.aws.a2z.com|.my.connect.aws|.awsapps.com/); + origin.match(/.connect.aws.a2z.com|.my.connect.aws|.govcloud.connect.aws|.awsapps.com/); /** * Given the URL, this method generates the prefixed connect domain request storage access URL diff --git a/test/unit/request-storage-access.spec.js b/test/unit/request-storage-access.spec.js index b9c2106..6be484d 100644 --- a/test/unit/request-storage-access.spec.js +++ b/test/unit/request-storage-access.spec.js @@ -129,6 +129,14 @@ describe("Request Storage Access module", () => { ); }); + it('should return requestAccessPageurl for govcloud domain', () => { + connect.storageAccess.init('https://test122.govcloud.connect.aws/ccp-v2', container); + + expect(connect.storageAccess.getRequestStorageAccessUrl()).to.be.equal( + 'https://test122.govcloud.connect.aws/request-storage-access' + ); + }); + it("should return requestAccessPageurl as instanceUrl if ccpURL doesnt match the connect domains", () => { connect.storageAccess.init( "https://test122.com/connect/ccp-v2",