UNPKG

@mt-utils/mt-sse

Version:

明途SSE请求工具

304 lines (303 loc) 10.9 kB
import { fetchEventSource } from "@microsoft/fetch-event-source"; function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _construct(t, e, r) { if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments); var o = [null]; o.push.apply(o, e); var p = new (t.bind.apply(t, o))(); return r && _setPrototypeOf(p, r.prototype), p; } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: false }), e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t2) { return t2.__proto__ || Object.getPrototypeOf(t2); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: true, configurable: true } }), Object.defineProperty(t, "prototype", { writable: false }), e && _setPrototypeOf(t, e); } function _isNativeFunction(t) { try { return -1 !== Function.toString.call(t).indexOf("[native code]"); } catch (n) { return "function" == typeof t; } } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { })); } catch (t2) { } return (_isNativeReflectConstruct = function() { return !!t; })(); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function(r2) { return Object.getOwnPropertyDescriptor(e, r2).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { _defineProperty(e, r2, t[r2]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); }); } return e; } function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t2, e2) { return t2.__proto__ = e2, t2; }, _setPrototypeOf(t, e); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return String(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _wrapNativeSuper(t) { var r = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0; return _wrapNativeSuper = function(t2) { if (null === t2 || !_isNativeFunction(t2)) return t2; if ("function" != typeof t2) throw new TypeError("Super expression must either be null or a function"); if (void 0 !== r) { if (r.has(t2)) return r.get(t2); r.set(t2, Wrapper); } function Wrapper() { return _construct(t2, arguments, _getPrototypeOf(this).constructor); } return Wrapper.prototype = Object.create(t2.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }), _setPrototypeOf(Wrapper, t2); }, _wrapNativeSuper(t); } var SSECodeStatus = /* @__PURE__ */ function(SSECodeStatus2) { SSECodeStatus2["NORMAL"] = "112"; SSECodeStatus2["BAN"] = "100"; SSECodeStatus2["END"] = "114"; return SSECodeStatus2; }(SSECodeStatus || {}); var SSEErrorCode = /* @__PURE__ */ function(SSEErrorCode2) { SSEErrorCode2["USER_DEACTIVATIO"] = "4005"; SSEErrorCode2["UNKNOWN"] = "4004"; SSEErrorCode2["OPEN_ERROR"] = "4003"; SSEErrorCode2["BROWSER_NOT_SUPPORTED"] = "4001"; SSEErrorCode2["SSE_ERROR"] = "4002"; return SSEErrorCode2; }(SSEErrorCode || {}); var SSEError = /* @__PURE__ */ function(_Error) { function SSEError2(message, code) { var _this; _classCallCheck(this, SSEError2); _this = _callSuper(this, SSEError2, [message]); _defineProperty(_this, "code", void 0); _this.name = "SseError"; _this.code = code; return _this; } _inherits(SSEError2, _Error); return _createClass(SSEError2, null, [{ key: "create", value: function create(code, message) { var _ref, _codeMesssageMap$code; var codeMesssageMap = _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, SSEErrorCode.USER_DEACTIVATIO, "该账号涉及敏感信息较多,已停用24小时"), SSEErrorCode.UNKNOWN, "未知错误"), SSEErrorCode.OPEN_ERROR, "SSE 连接错误"), SSEErrorCode.BROWSER_NOT_SUPPORTED, "当前浏览器不支持sse"); return new SSEError2((_ref = (_codeMesssageMap$code = codeMesssageMap === null || codeMesssageMap === void 0 ? void 0 : codeMesssageMap[code]) !== null && _codeMesssageMap$code !== void 0 ? _codeMesssageMap$code : message) !== null && _ref !== void 0 ? _ref : "未知错误", code); } }]); }(/* @__PURE__ */ _wrapNativeSuper(Error)); var SSEClient = /* @__PURE__ */ function() { function SSEClient2(url, options) { _classCallCheck(this, SSEClient2); _defineProperty(this, "abortController", void 0); _defineProperty(this, "url", ""); _defineProperty(this, "method", "POST"); _defineProperty(this, "eventMap", /* @__PURE__ */ new Map()); _defineProperty(this, "headers", { "cache-control": "no-cache", Connection: "keep-alive", "content-type": "application/json", Language: "zh" }); _defineProperty(this, "options", {}); if (!("EventSource" in window)) { this.emit("error", SSEError.create(SSEErrorCode.BROWSER_NOT_SUPPORTED)); return; } this.url = url; this.options = options || {}; } return _createClass(SSEClient2, [{ key: "send", value: function send(data) { var _this = this; this.abortController = new AbortController(); var url = this.url, headers = this.headers, method = this.method, abortController = this.abortController, options = this.options; fetchEventSource(url, _objectSpread2(_objectSpread2({ openWhenHidden: true, headers, method }, options), {}, { body: JSON.stringify(data), signal: abortController.signal, onopen: function onopen(response) { var status = response.status; if (status !== 200) { _this.emit("error", SSEError.create(SSEErrorCode.OPEN_ERROR)); } else { _this.emit("start", response); } return Promise.resolve(); }, onmessage: function onmessage(res) { var result = JSON.parse(res.data); var extend = result.extend; var type = result.type; var codeStrategyMap = /* @__PURE__ */ new Map([[SSECodeStatus.BAN, function() { var _JSON$parse; if ((_JSON$parse = JSON.parse(extend)) !== null && _JSON$parse !== void 0 && _JSON$parse.ban) { _this.emit("error", SSEError.create(SSEErrorCode.USER_DEACTIVATIO)); } else { _this.emit("error", SSEError.create(SSEErrorCode.UNKNOWN)); } }], [SSECodeStatus.END, function() { _this.emit("end", result); }]]); if (codeStrategyMap.has(type)) { var _codeStrategyMap$get; (_codeStrategyMap$get = codeStrategyMap.get(type)) === null || _codeStrategyMap$get === void 0 || _codeStrategyMap$get(); } else { _this.emit("message", result); } }, onerror: function onerror(error) { _this.emit("error", SSEError.create(SSEErrorCode.UNKNOWN, error.message)); }, onclose: function onclose() { _this.emit("close"); } })); } /** * 关闭sse连接 */ }, { key: "closeSSE", value: function closeSSE() { if (this.abortController) { this.abortController.abort(); this.abortController = void 0; } } /** * 触发回调函数 * @param type 事件类型 * @param data 参数 */ }, { key: "emit", value: function emit(type, data) { var _this$eventMap$get; (_this$eventMap$get = this.eventMap.get(type)) === null || _this$eventMap$get === void 0 || _this$eventMap$get.forEach(function(item) { item(data); }); } /** * 消息队列添加事件 */ }, { key: "on", value: function on(type, callback) { var callbacks = this.eventMap.get(type); if (!callbacks) { this.eventMap.set(type, [callback]); } else { var _this$eventMap$get2; (_this$eventMap$get2 = this.eventMap.get(type)) === null || _this$eventMap$get2 === void 0 || _this$eventMap$get2.push(callback); } } /** * 移除事件 * @param type 事件类型 */ }, { key: "off", value: function off(type, callback) { var callbacks = this.eventMap.get(type); if (callback) { callbacks === null || callbacks === void 0 || callbacks.splice(callbacks === null || callbacks === void 0 ? void 0 : callbacks.indexOf(callback), 1); } else { this.eventMap.delete(type); } } }]); }(); export { SSECodeStatus, SSEErrorCode, SSEClient as default };