| 1 | function SSE(url, options) { |
| 2 | this.INITIALIZING = -1; |
| 3 | this.CONNECTING = 0; |
| 4 | this.OPEN = 1; |
| 5 | this.CLOSED = 2; |
| 6 | |
| 7 | this.url = url; |
| 8 | |
| 9 | options = options || {}; |
| 10 | this.headers = options.headers || {}; |
| 11 | this.payload = options.payload !== undefined ? options.payload : ''; |
| 12 | this.method = options.method || (this.payload && 'POST') || 'GET'; |
| 13 | this.withCredentials = !!options.withCredentials; |
| 14 | |
| 15 | this.FIELD_SEPARATOR = ':'; |
| 16 | this.listeners = {}; |
| 17 | |
| 18 | this.xhr = null; |
| 19 | this.readyState = this.INITIALIZING; |
| 20 | this.progress = 0; |
| 21 | this.chunk = ''; |
| 22 | |
| 23 | this.addEventListener = function (type, listener) { |
| 24 | if (this.listeners[type] === undefined) { |
| 25 | this.listeners[type] = []; |
| 26 | } |
| 27 | |
| 28 | if (this.listeners[type].indexOf(listener) === -1) { |
| 29 | this.listeners[type].push(listener); |
| 30 | } |
| 31 | }; |
| 32 | |
| 33 | this.removeEventListener = function (type, listener) { |
| 34 | if (this.listeners[type] === undefined) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | var filtered = []; |
| 39 | this.listeners[type].forEach(function (element) { |
| 40 | if (element !== listener) { |
| 41 | filtered.push(element); |
| 42 | } |
| 43 | }); |
| 44 | if (filtered.length === 0) { |
| 45 | delete this.listeners[type]; |
| 46 | } else { |
| 47 | this.listeners[type] = filtered; |
| 48 | } |
| 49 | }; |
| 50 | |
| 51 | this.dispatchEvent = function (e) { |
| 52 | if (!e) { |
| 53 | return true; |
| 54 | } |
| 55 | |
| 56 | e.source = this; |
| 57 | |
| 58 | var onHandler = 'on' + e.type; |
| 59 | if (this.hasOwnProperty(onHandler)) { |
| 60 | this[onHandler].call(this, e); |
| 61 | if (e.defaultPrevented) { |
| 62 | return false; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | if (this.listeners[e.type]) { |
| 67 | return this.listeners[e.type].every(function (callback) { |
| 68 | callback(e); |
| 69 | return !e.defaultPrevented; |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | return true; |
| 74 | }; |
| 75 | |
| 76 | this._setReadyState = function (state) { |
| 77 | var event = new CustomEvent('readystatechange'); |
| 78 | event.readyState = state; |
| 79 | this.readyState = state; |
| 80 | this.dispatchEvent(event); |
| 81 | }; |
| 82 | |
| 83 | this._onStreamFailure = function (e) { |
| 84 | var event = new CustomEvent('error'); |
| 85 | event.data = e.currentTarget.response; |
| 86 | this.dispatchEvent(event); |
| 87 | this.close(); |
| 88 | }; |
| 89 | |
| 90 | this._onStreamAbort = function (e) { |
| 91 | this.dispatchEvent(new CustomEvent('abort')); |
| 92 | this.close(); |
| 93 | }; |
| 94 | |
| 95 | this._onStreamProgress = function (e) { |
| 96 | if (!this.xhr) { |
| 97 | return; |
| 98 | } |
| 99 | |
| 100 | if (this.xhr.status !== 200) { |
| 101 | this._onStreamFailure(e); |
| 102 | return; |
| 103 | } |
| 104 | |
| 105 | if (this.readyState == this.CONNECTING) { |
| 106 | this.dispatchEvent(new CustomEvent('open')); |
| 107 | this._setReadyState(this.OPEN); |
| 108 | } |
| 109 | |
| 110 | var data = this.xhr.responseText.substring(this.progress); |
| 111 | this.progress += data.length; |
| 112 | data.split(/(\r\n|\r|\n){2}/g).forEach( |
| 113 | function (part) { |
| 114 | if (part.trim().length === 0) { |
| 115 | this.dispatchEvent(this._parseEventChunk(this.chunk.trim())); |
| 116 | this.chunk = ''; |
| 117 | } else { |
| 118 | this.chunk += part; |
| 119 | } |
| 120 | }.bind(this), |
| 121 | ); |
| 122 | }; |
| 123 | |
| 124 | this._onStreamLoaded = function (e) { |
| 125 | this._onStreamProgress(e); |
| 126 | |
| 127 | // Parse the last chunk. |
| 128 | this.dispatchEvent(this._parseEventChunk(this.chunk)); |
| 129 | this.chunk = ''; |
| 130 | }; |
| 131 | |
| 132 | /** |
| 133 | * Parse a received SSE event chunk into a constructed event object. |
| 134 | */ |
| 135 | this._parseEventChunk = function (chunk) { |
| 136 | if (!chunk || chunk.length === 0) { |
| 137 | return null; |
| 138 | } |
| 139 | |
| 140 | var e = { id: null, retry: null, data: '', event: 'message' }; |
| 141 | chunk.split(/\n|\r\n|\r/).forEach( |
| 142 | function (line) { |
| 143 | line = line.trimRight(); |
| 144 | var index = line.indexOf(this.FIELD_SEPARATOR); |
| 145 | if (index <= 0) { |
| 146 | // Line was either empty, or started with a separator and is a comment. |
| 147 | // Either way, ignore. |
| 148 | return; |
| 149 | } |
| 150 | |
| 151 | var field = line.substring(0, index); |
| 152 | if (!(field in e)) { |
| 153 | return; |
| 154 | } |
| 155 | |
| 156 | var value = line.substring(index + 1).trimLeft(); |
| 157 | if (field === 'data') { |
| 158 | e[field] += value; |
| 159 | } else { |
| 160 | e[field] = value; |
| 161 | } |
| 162 | }.bind(this), |
| 163 | ); |
| 164 | |
| 165 | var event = new CustomEvent(e.event); |
| 166 | event.data = e.data; |
| 167 | event.id = e.id; |
| 168 | return event; |
| 169 | }; |
| 170 | |
| 171 | this._checkStreamClosed = function () { |
| 172 | if (!this.xhr) { |
| 173 | return; |
| 174 | } |
| 175 | |
| 176 | if (this.xhr.readyState === XMLHttpRequest.DONE) { |
| 177 | this._setReadyState(this.CLOSED); |
| 178 | var event = new CustomEvent('end'); |
| 179 | event.data = this.xhr.responseText; |
| 180 | this.dispatchEvent(event); |
| 181 | } |
| 182 | }; |
| 183 | |
| 184 | this.stream = function () { |
| 185 | this._setReadyState(this.CONNECTING); |
| 186 | |
| 187 | this.xhr = new XMLHttpRequest(); |
| 188 | this.xhr.addEventListener('progress', this._onStreamProgress.bind(this)); |
| 189 | this.xhr.addEventListener('load', this._onStreamLoaded.bind(this)); |
| 190 | this.xhr.addEventListener('readystatechange', this._checkStreamClosed.bind(this)); |
| 191 | this.xhr.addEventListener('error', this._onStreamFailure.bind(this)); |
| 192 | this.xhr.addEventListener('abort', this._onStreamAbort.bind(this)); |
| 193 | this.xhr.open(this.method, this.url); |
| 194 | for (var header in this.headers) { |
| 195 | this.xhr.setRequestHeader(header, this.headers[header]); |
| 196 | } |
| 197 | this.xhr.withCredentials = this.withCredentials; |
| 198 | this.xhr.send(this.payload); |
| 199 | }; |
| 200 | |
| 201 | this.close = function () { |
| 202 | if (this.readyState === this.CLOSED) { |
| 203 | return; |
| 204 | } |
| 205 | |
| 206 | this.xhr.abort(); |
| 207 | this.xhr = null; |
| 208 | this._setReadyState(this.CLOSED); |
| 209 | }; |
| 210 | }; |
| 211 | |
| 212 | // export { SSE } |
| 213 | |
| 214 | /* |
| 215 | const url = 'https://xxx/chat'; |
| 216 | var source = new SSE(url, { |
| 217 | method: 'POST', |
| 218 | // withCredentials: true, |
| 219 | headers: { |
| 220 | 'Content-Type': 'application/json', |
| 221 | 'Cache-Control': 'no-cache' |
| 222 | }, |
| 223 | payload: JSON.stringify({ prompt: 'xxx' }), |
| 224 | }); |
| 225 | source.onmessage = function (data) { |
| 226 | console.log('chunk => ' + data.data) |
| 227 | }; |
| 228 | source.onend = function (data) { |
| 229 | console.log('结束'); |
| 230 | }; |
| 231 | source.onerror = function (err) { |
| 232 | console.error('异常', err); |
| 233 | }; |
| 234 | source.stream(); |
| 235 | */ |