wxyyxc1992 5 lat temu
rodzic
commit
d1cfbbe3c9
33 zmienionych plików z 1374 dodań i 2236 usunięć
  1. 3
    0
      package.json
  2. 7
    18
      packages/cts-api/dist/cjs/WebSocketClient.js
  3. 0
    291
      packages/cts-api/dist/cjs/client.js
  4. 0
    1
      packages/cts-api/dist/cjs/config.js
  5. 0
    24
      packages/cts-api/dist/cjs/error.js
  6. 0
    4
      packages/cts-api/dist/cjs/index.js
  7. 0
    46
      packages/cts-api/dist/cjs/packet.js
  8. 0
    2
      packages/cts-api/dist/cjs/types/callback.js
  9. 0
    113
      packages/cts-api/dist/cjs/utils.js
  10. 4
    4
      packages/cts-api/dist/index.js
  11. 11
    8
      packages/cts-api/dist/types/WebSocketClient.d.ts
  12. 0
    34
      packages/cts-api/dist/types/client.d.ts
  13. 0
    1
      packages/cts-api/dist/types/config.d.ts
  14. 0
    7
      packages/cts-api/dist/types/error.d.ts
  15. 0
    2
      packages/cts-api/dist/types/index.d.ts
  16. 0
    11
      packages/cts-api/dist/types/packet.d.ts
  17. 0
    12
      packages/cts-api/dist/types/types/callback.d.ts
  18. 0
    19
      packages/cts-api/dist/types/utils.d.ts
  19. 0
    45
      packages/cts-api/example/index.ts
  20. 0
    9
      packages/cts-api/example/types.d.ts
  21. 1
    0
      packages/cts-api/package.json
  22. 11
    18
      packages/cts-api/src/WebSocketClient.ts
  23. 0
    386
      packages/cts-api/src/client.ts
  24. 0
    2
      packages/cts-api/src/config.ts
  25. 0
    26
      packages/cts-api/src/error.ts
  26. 0
    2
      packages/cts-api/src/index.ts
  27. 0
    59
      packages/cts-api/src/packet.ts
  28. 1
    0
      packages/cts-api/src/types.d.ts
  29. 0
    14
      packages/cts-api/src/types/callback.ts
  30. 0
    1
      packages/cts-api/src/types/node-int64.d.ts
  31. 0
    157
      packages/cts-api/src/utils.ts
  32. 8
    0
      packages/cts-api/yarn.lock
  33. 1328
    920
      yarn.lock

+ 3
- 0
package.json Wyświetl plik

@@ -84,5 +84,8 @@
84 84
     "webpack-dashboard": "3.0.5",
85 85
     "webpack-dev-server": "^3.3.1",
86 86
     "workerize-loader": "^1.0.4"
87
+  },
88
+  "dependencies": {
89
+    "ts-linker-sdk": "^1.0.6"
87 90
   }
88 91
 }

+ 7
- 18
packages/cts-api/dist/cjs/WebSocketClient.js Wyświetl plik

@@ -46,9 +46,10 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
46 46
     }
47 47
 };
48 48
 Object.defineProperty(exports, "__esModule", { value: true });
49
-var client_1 = require("./client");
49
+var ts_linker_sdk_1 = require("ts-linker-sdk");
50 50
 var meta_1 = require("./meta");
51 51
 var meta = meta_1.getMetaData();
52
+var PING_INTERVAL = 50 * 1000;
52 53
 var WebSocketClient = (function () {
53 54
     function WebSocketClient(wsUrl, token, sid, chatToken) {
54 55
         this.status = {
@@ -81,7 +82,7 @@ var WebSocketClient = (function () {
81 82
                         if (!url) {
82 83
                             throw new Error('websocket url is required.');
83 84
                         }
84
-                        _this.client = client_1.getClient(url, {
85
+                        _this.client = ts_linker_sdk_1.Client.getInstance(url, {
85 86
                             onOpen: function () { return __awaiter(_this, void 0, void 0, function () {
86 87
                                 var data;
87 88
                                 var _this = this;
@@ -95,7 +96,7 @@ var WebSocketClient = (function () {
95 96
                                                 }, PING_INTERVAL);
96 97
                                             }
97 98
                                             catch (err) {
98
-                                                this.client.reconnect();
99
+                                                console.error(err);
99 100
                                             }
100 101
                                             return [4, this.connect()];
101 102
                                         case 1:
@@ -108,10 +109,10 @@ var WebSocketClient = (function () {
108 109
                                     }
109 110
                                 });
110 111
                             }); },
111
-                            onError: function (err) {
112
+                            onError: function () {
112 113
                                 resolve(false);
113 114
                             },
114
-                            onClose: function (CloseEvent) {
115
+                            onClose: function () {
115 116
                                 clearInterval(_this.interval);
116 117
                             }
117 118
                         });
@@ -130,20 +131,8 @@ var WebSocketClient = (function () {
130 131
     };
131 132
     WebSocketClient.prototype.request = function (url, data) {
132 133
         return __awaiter(this, void 0, void 0, function () {
133
-            var error;
134 134
             return __generator(this, function (_a) {
135
-                if (this.client.readyState !== 1) {
136
-                    error = 'websocket connection not ready!';
137
-                    throw new Error(error);
138
-                }
139
-                try {
140
-                    return [2, this.client.asyncSend(url, data)];
141
-                }
142
-                catch (e) {
143
-                    console.error(e);
144
-                    throw e;
145
-                }
146
-                return [2];
135
+                return [2, this.client.request(url, data)];
147 136
             });
148 137
         });
149 138
     };

+ 0
- 291
packages/cts-api/dist/cjs/client.js Wyświetl plik

@@ -1,291 +0,0 @@
1
-"use strict";
2
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
-    return new (P || (P = Promise))(function (resolve, reject) {
4
-        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
-        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
-        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
8
-    });
9
-};
10
-var __generator = (this && this.__generator) || function (thisArg, body) {
11
-    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
-    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
-    function verb(n) { return function (v) { return step([n, v]); }; }
14
-    function step(op) {
15
-        if (f) throw new TypeError("Generator is already executing.");
16
-        while (_) try {
17
-            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
-            if (y = 0, t) op = [op[0] & 2, t.value];
19
-            switch (op[0]) {
20
-                case 0: case 1: t = op; break;
21
-                case 4: _.label++; return { value: op[1], done: false };
22
-                case 5: _.label++; y = op[1]; op = [0]; continue;
23
-                case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
-                default:
25
-                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
-                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
-                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
-                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
-                    if (t[2]) _.ops.pop();
30
-                    _.trys.pop(); continue;
31
-            }
32
-            op = body.call(thisArg, _);
33
-        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
-        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
-    }
36
-};
37
-Object.defineProperty(exports, "__esModule", { value: true });
38
-var packet_1 = require("./packet");
39
-var utils_1 = require("./utils");
40
-var error_1 = require("./error");
41
-var clientError = 400;
42
-var Client = (function () {
43
-    function Client(url, readyStateCallback) {
44
-        this.listeners = new Map();
45
-        this.requestHeader = '';
46
-        this.requestHeader = '';
47
-        this._maxPayload = 1024 * 1024;
48
-        this.url = url;
49
-        this.reconnectTimes = 0;
50
-        this.readyStateCallback = readyStateCallback;
51
-        this._enableLogger = false;
52
-        this.socket = this.connect();
53
-    }
54
-    Object.defineProperty(Client.prototype, "maxPayload", {
55
-        get: function () {
56
-            return this._maxPayload;
57
-        },
58
-        set: function (maxPayload) {
59
-            this._maxPayload = maxPayload;
60
-        },
61
-        enumerable: true,
62
-        configurable: true
63
-    });
64
-    Object.defineProperty(Client.prototype, "enableLogger", {
65
-        get: function () {
66
-            return this._enableLogger;
67
-        },
68
-        set: function (enableLogger) {
69
-            this._enableLogger = enableLogger;
70
-        },
71
-        enumerable: true,
72
-        configurable: true
73
-    });
74
-    Client.prototype.ping = function (param) {
75
-        return __awaiter(this, void 0, void 0, function () {
76
-            var _this = this;
77
-            return __generator(this, function (_a) {
78
-                return [2, new Promise(function (resolve, reject) {
79
-                        if (_this.socket.readyState !== _this.socket.OPEN) {
80
-                            if (_this._enableLogger) {
81
-                                console.log('[ping]: connection refuse');
82
-                            }
83
-                            reject(new error_1.WebsocketError(clientError, 'connection refuse'));
84
-                        }
85
-                        var heartbeatOperator = 0;
86
-                        _this.listeners.set(heartbeatOperator, function (data) {
87
-                            var code = _this.getResponseProperty('code');
88
-                            if (code !== '') {
89
-                                var message = _this.getResponseProperty('message');
90
-                                reject(new error_1.WebsocketError(Number(code), message));
91
-                            }
92
-                            else {
93
-                                resolve(data);
94
-                            }
95
-                        });
96
-                        var p = new packet_1.Packet();
97
-                        _this.send(p.pack(heartbeatOperator, 0, _this.requestHeader, JSON.stringify(param)));
98
-                        if (_this._enableLogger) {
99
-                            console.info('[send data packet]', heartbeatOperator, 0, _this.requestHeader, param);
100
-                        }
101
-                    })];
102
-            });
103
-        });
104
-    };
105
-    Client.prototype.request = function (operator, param) {
106
-        return __awaiter(this, void 0, void 0, function () {
107
-            return __generator(this, function (_a) {
108
-                switch (_a.label) {
109
-                    case 0: return [4, this.asyncSend(operator, param)];
110
-                    case 1: return [2, _a.sent()];
111
-                }
112
-            });
113
-        });
114
-    };
115
-    Client.prototype.addMessageListener = function (operator, listener) {
116
-        this.listeners.set(utils_1.Utils.crc32(operator), listener);
117
-    };
118
-    Client.prototype.removeMessageListener = function (operator) {
119
-        delete this.listeners[utils_1.Utils.crc32(operator)];
120
-    };
121
-    Object.defineProperty(Client.prototype, "readyState", {
122
-        get: function () {
123
-            return this.socket.readyState;
124
-        },
125
-        enumerable: true,
126
-        configurable: true
127
-    });
128
-    Client.prototype.setRequestProperty = function (key, value) {
129
-        var v = this.getRequestProperty(key);
130
-        this.requestHeader = this.requestHeader.replace(key + '=' + v + ';', '');
131
-        this.requestHeader = this.requestHeader + key + '=' + value + ';';
132
-    };
133
-    Client.prototype.getRequestProperty = function (key) {
134
-        if (this.requestHeader !== undefined) {
135
-            var values = this.requestHeader.split(';');
136
-            for (var index in values) {
137
-                var kv = values[index].split('=');
138
-                if (kv[0] === key) {
139
-                    return kv[1];
140
-                }
141
-            }
142
-        }
143
-        return '';
144
-    };
145
-    Client.prototype.setResponseProperty = function (key, value) {
146
-        var v = this.getResponseProperty(key);
147
-        this.responseHeader = this.responseHeader.replace(key + '=' + v + ';', '');
148
-        this.responseHeader = this.responseHeader + key + '=' + value + ';';
149
-    };
150
-    Client.prototype.getResponseProperty = function (key) {
151
-        if (this.responseHeader !== undefined) {
152
-            var values = this.responseHeader.split(';');
153
-            for (var index in values) {
154
-                var kv = values[index].split('=');
155
-                if (kv[0] === key) {
156
-                    return kv[1];
157
-                }
158
-            }
159
-        }
160
-        return '';
161
-    };
162
-    Client.prototype.connect = function () {
163
-        var _this = this;
164
-        var readyStateCallback = this.readyStateCallback;
165
-        var ws = new WebSocket(this.url);
166
-        ws.binaryType = 'blob';
167
-        ws.onopen = function (ev) {
168
-            if (_this._enableLogger) {
169
-                console.info('[websocket] open connection');
170
-            }
171
-            _this.reconnectTimes = 0;
172
-            readyStateCallback.onOpen(ev);
173
-        };
174
-        ws.onclose = function (ev) {
175
-            if (_this._enableLogger) {
176
-                console.info('[websocket] close connection');
177
-            }
178
-            _this.reconnect();
179
-            readyStateCallback.onClose(ev);
180
-        };
181
-        ws.onerror = function (ev) {
182
-            if (_this._enableLogger) {
183
-                console.info('[websocket] error');
184
-            }
185
-            _this.reconnect();
186
-            readyStateCallback.onError(ev);
187
-        };
188
-        ws.onmessage = function (ev) {
189
-            if (ev.data instanceof Blob) {
190
-                var reader_1 = new FileReader();
191
-                reader_1.readAsArrayBuffer(ev.data);
192
-                reader_1.onload = function () {
193
-                    try {
194
-                        var packet = new packet_1.Packet().unPack(reader_1.result);
195
-                        var packetLength = packet.headerLength + packet.bodyLength + 20;
196
-                        if (packetLength > _this._maxPayload) {
197
-                            throw new Error('the packet is big than ' + _this._maxPayload);
198
-                        }
199
-                        var operator = Number(packet.operator) + Number(packet.sequence);
200
-                        if (_this.listeners.has(operator)) {
201
-                            if (packet.body === '') {
202
-                                packet.body = '{}';
203
-                            }
204
-                            _this.responseHeader = packet.header;
205
-                            _this.listeners.get(operator)(JSON.parse(packet.body));
206
-                        }
207
-                        if (_this._enableLogger) {
208
-                            if (operator !== 0 && packet.body !== 'null') {
209
-                                console.info('receive data packet', packet.body);
210
-                            }
211
-                        }
212
-                    }
213
-                    catch (e) {
214
-                        throw new Error(e);
215
-                    }
216
-                };
217
-            }
218
-            else {
219
-                throw new Error('unsupported data format');
220
-            }
221
-        };
222
-        return ws;
223
-    };
224
-    Client.prototype.reconnect = function () {
225
-        var _this = this;
226
-        if (!this.reconnectLock) {
227
-            this.reconnectLock = true;
228
-            if (this._enableLogger) {
229
-                console.info('websocket reconnect in ' + this.reconnectTimes + 's');
230
-            }
231
-            setTimeout(function () {
232
-                _this.reconnectTimes++;
233
-                _this.socket = _this.connect();
234
-                _this.reconnectLock = false;
235
-            }, this.reconnectTimes * 1000);
236
-        }
237
-    };
238
-    Client.prototype.send = function (data) {
239
-        if (this.socket.readyState !== this.socket.OPEN) {
240
-            if (this._enableLogger) {
241
-                console.error('[send] WebSocket is already in CLOSING or CLOSED state.');
242
-            }
243
-            return;
244
-        }
245
-        try {
246
-            this.socket.send(data);
247
-        }
248
-        catch (e) {
249
-            throw new Error('send data error' + e);
250
-        }
251
-    };
252
-    Client.prototype.asyncSend = function (operator, param) {
253
-        var _this = this;
254
-        return new Promise(function (resolve, reject) {
255
-            if (_this.socket.readyState !== _this.socket.OPEN) {
256
-                if (_this._enableLogger) {
257
-                    console.log('[ping]: connection refuse');
258
-                }
259
-                reject(new error_1.WebsocketError(clientError, 'asyncSend: connection refuse'));
260
-            }
261
-            var sequence = new Date().getTime();
262
-            var listener = utils_1.Utils.crc32(operator) + sequence;
263
-            _this.listeners.set(listener, function (data) {
264
-                var code = _this.getResponseProperty('code');
265
-                if (code !== '') {
266
-                    var message = _this.getResponseProperty('message');
267
-                    reject(new error_1.WebsocketError(Number(code), message));
268
-                }
269
-                else {
270
-                    resolve(data);
271
-                }
272
-                delete _this.listeners[listener];
273
-            });
274
-            var p = new packet_1.Packet();
275
-            _this.send(p.pack(utils_1.Utils.crc32(operator), sequence, _this.requestHeader, JSON.stringify(param)));
276
-            if (_this._enableLogger) {
277
-                console.info('[send data packet]', operator, sequence, _this.requestHeader, param);
278
-            }
279
-        });
280
-    };
281
-    return Client;
282
-}());
283
-exports.Client = Client;
284
-var client;
285
-function getClient(url, callback) {
286
-    if (!client) {
287
-        client = new Client(url, callback);
288
-    }
289
-    return client;
290
-}
291
-exports.getClient = getClient;

+ 0
- 1
packages/cts-api/dist/cjs/config.js Wyświetl plik

@@ -1 +0,0 @@
1
-var PING_INTERVAL = 50 * 1000;

+ 0
- 24
packages/cts-api/dist/cjs/error.js Wyświetl plik

@@ -1,24 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-var WebsocketError = (function () {
4
-    function WebsocketError(code, msg) {
5
-        this._code = code;
6
-        this._msg = msg;
7
-    }
8
-    Object.defineProperty(WebsocketError.prototype, "code", {
9
-        get: function () {
10
-            return this._code;
11
-        },
12
-        enumerable: true,
13
-        configurable: true
14
-    });
15
-    Object.defineProperty(WebsocketError.prototype, "msg", {
16
-        get: function () {
17
-            return this._msg;
18
-        },
19
-        enumerable: true,
20
-        configurable: true
21
-    });
22
-    return WebsocketError;
23
-}());
24
-exports.WebsocketError = WebsocketError;

+ 0
- 4
packages/cts-api/dist/cjs/index.js Wyświetl plik

@@ -2,7 +2,3 @@
2 2
 Object.defineProperty(exports, "__esModule", { value: true });
3 3
 var WebSocketClient_1 = require("./WebSocketClient");
4 4
 exports.WebSocketClient = WebSocketClient_1.WebSocketClient;
5
-var error_1 = require("./error");
6
-exports.WebsocketError = error_1.WebsocketError;
7
-var client_1 = require("./client");
8
-exports.Client = client_1.Client;

+ 0
- 46
packages/cts-api/dist/cjs/packet.js Wyświetl plik

@@ -1,46 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-var utils_1 = require("./utils");
4
-var Int64 = require("node-int64");
5
-var Packet = (function () {
6
-    function Packet() {
7
-        this.key = 'b8ca9aa66def05ff3f24919274bb4a66';
8
-    }
9
-    Packet.prototype.pack = function (operator, sequence, header, body) {
10
-        header = utils_1.Utils.encrypt(header, this.key, this.key);
11
-        body = utils_1.Utils.encrypt(body, this.key, this.key);
12
-        var headerLength = header.length;
13
-        var bodyLength = body.length;
14
-        var buf = new ArrayBuffer(20 + headerLength + bodyLength);
15
-        var dataView = new DataView(buf);
16
-        var nsBuf = new Int64(sequence).toBuffer();
17
-        dataView.setUint32(0, operator);
18
-        dataView.setUint32(12, headerLength);
19
-        dataView.setUint32(16, bodyLength);
20
-        var bufView = new Uint8Array(buf);
21
-        for (var i = 0; i < 8; i++) {
22
-            bufView[4 + i] = nsBuf[i];
23
-        }
24
-        for (var i_1 = 0; i_1 < headerLength; i_1++) {
25
-            bufView[20 + i_1] = header.charCodeAt(i_1);
26
-        }
27
-        for (var i_2 = 0; i_2 < bodyLength; i_2++) {
28
-            bufView[20 + headerLength + i_2] = body.charCodeAt(i_2);
29
-        }
30
-        return buf;
31
-    };
32
-    Packet.prototype.unPack = function (data) {
33
-        var dataView = new DataView(data);
34
-        this.operator = dataView.getUint32(0, false);
35
-        this.sequence = new Int64(new Uint8Array(dataView.buffer.slice(4, 12))).toNumber();
36
-        this.headerLength = dataView.getUint32(12, false);
37
-        this.bodyLength = dataView.getUint32(16, false);
38
-        var header = utils_1.Utils.ab2str(dataView.buffer.slice(20, 20 + this.headerLength));
39
-        var body = utils_1.Utils.ab2str(dataView.buffer.slice(20 + this.headerLength));
40
-        this.header = utils_1.Utils.decrypt(header, this.key, this.key);
41
-        this.body = utils_1.Utils.decrypt(body, this.key, this.key);
42
-        return this;
43
-    };
44
-    return Packet;
45
-}());
46
-exports.Packet = Packet;

+ 0
- 2
packages/cts-api/dist/cjs/types/callback.js Wyświetl plik

@@ -1,2 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });

+ 0
- 113
packages/cts-api/dist/cjs/utils.js Wyświetl plik

@@ -1,113 +0,0 @@
1
-"use strict";
2
-Object.defineProperty(exports, "__esModule", { value: true });
3
-var crypto_js_1 = require("crypto-js");
4
-var Utils = (function () {
5
-    function Utils() {
6
-    }
7
-    Utils.crc32 = function (str) {
8
-        var crcTable = window.crcTable || (window.crcTable = Utils.makeCRCTable());
9
-        var crc = 0 ^ -1;
10
-        for (var i = 0; i < str.length; i++) {
11
-            crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xff];
12
-        }
13
-        return (crc ^ -1) >>> 0;
14
-    };
15
-    Utils.ab2str = function (buf) {
16
-        if (buf && buf.byteLength < 1024) {
17
-            return String.fromCharCode.apply(null, new Uint8Array(buf));
18
-        }
19
-        var bufView = new Uint8Array(buf);
20
-        var len = bufView.length;
21
-        var byteStr = new Array(len);
22
-        for (var i = 0; i < len; i++) {
23
-            byteStr[i] = String.fromCharCode.call(null, bufView[i]);
24
-        }
25
-        return byteStr.join('');
26
-    };
27
-    Utils.str2ab = function (str) {
28
-        var buf = new ArrayBuffer(str.length);
29
-        var bufView = new Uint8Array(buf);
30
-        for (var i = 0, strLen = str.length; i < strLen; i++) {
31
-            bufView[i] = str.charCodeAt(i);
32
-        }
33
-        return buf;
34
-    };
35
-    Utils.decrypt = function (data, key, iv) {
36
-        var binData = Utils.stringToBin(data);
37
-        var base64Data = Utils.binToBase64(binData);
38
-        var bytes = crypto_js_1.AES.decrypt(base64Data, crypto_js_1.enc.Latin1.parse(key), {
39
-            iv: crypto_js_1.enc.Latin1.parse(iv),
40
-            mode: crypto_js_1.mode.CBC,
41
-            padding: crypto_js_1.pad.Pkcs7,
42
-        });
43
-        return bytes.toString(crypto_js_1.enc.Utf8);
44
-    };
45
-    Utils.encrypt = function (data, key, iv) {
46
-        var result = crypto_js_1.AES.encrypt(data, crypto_js_1.enc.Latin1.parse(key), {
47
-            iv: crypto_js_1.enc.Latin1.parse(iv),
48
-            mode: crypto_js_1.mode.CBC,
49
-            padding: crypto_js_1.pad.Pkcs7,
50
-        });
51
-        return Utils.binToString(Utils.base64ToBin(result.toString()));
52
-    };
53
-    Utils.binToBase64 = function (bitString) {
54
-        var tail = bitString.length % 6;
55
-        var bitStringTemp1 = bitString.substr(0, bitString.length - tail);
56
-        var result = '';
57
-        var bitStringTemp2 = bitString.substr(bitString.length - tail, tail);
58
-        for (var i = 0; i < bitStringTemp1.length; i += 6) {
59
-            var index = parseInt(bitStringTemp1.substr(i, 6), 2);
60
-            result += Utils.code[index];
61
-        }
62
-        bitStringTemp2 += new Array(7 - tail).join('0');
63
-        if (tail) {
64
-            result += Utils.code[parseInt(bitStringTemp2, 2)];
65
-            result += new Array((6 - tail) / 2 + 1).join('=');
66
-        }
67
-        return result;
68
-    };
69
-    Utils.base64ToBin = function (str) {
70
-        var bitString = '';
71
-        var tail = 0;
72
-        for (var i = 0; i < str.length; i++) {
73
-            if (str[i] !== '=') {
74
-                var decode = this.code.indexOf(str[i]).toString(2);
75
-                bitString += new Array(7 - decode.length).join('0') + decode;
76
-            }
77
-            else {
78
-                tail++;
79
-            }
80
-        }
81
-        return bitString.substr(0, bitString.length - tail * 2);
82
-    };
83
-    Utils.stringToBin = function (str) {
84
-        var result = '';
85
-        for (var i = 0; i < str.length; i++) {
86
-            var charCode = str.charCodeAt(i).toString(2);
87
-            result += new Array(9 - charCode.length).join('0') + charCode;
88
-        }
89
-        return result;
90
-    };
91
-    Utils.binToString = function (bin) {
92
-        var result = '';
93
-        for (var i = 0; i < bin.length; i += 8) {
94
-            result += String.fromCharCode(parseInt(bin.substr(i, 8), 2));
95
-        }
96
-        return result;
97
-    };
98
-    Utils.makeCRCTable = function () {
99
-        var c;
100
-        var crcTable = [];
101
-        for (var n = 0; n < 256; n++) {
102
-            c = n;
103
-            for (var k = 0; k < 8; k++) {
104
-                c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
105
-            }
106
-            crcTable[n] = c;
107
-        }
108
-        return crcTable;
109
-    };
110
-    Utils.code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
111
-    return Utils;
112
-}());
113
-exports.Utils = Utils;

+ 4
- 4
packages/cts-api/dist/index.js
Plik diff jest za duży
Wyświetl plik


+ 11
- 8
packages/cts-api/dist/types/WebSocketClient.d.ts Wyświetl plik

@@ -1,9 +1,12 @@
1
-import { Client, WebSocketResp } from './client';
1
+import { Client } from 'ts-linker-sdk';
2 2
 export interface WebSocketClientStatus {
3 3
     created: boolean;
4 4
     connected: boolean;
5 5
     login: boolean;
6 6
 }
7
+export interface WebSocketResp {
8
+    value: object | string;
9
+}
7 10
 export declare type ListenerCallback = (data: WebSocketResp) => void;
8 11
 export declare class WebSocketClient {
9 12
     client: Client;
@@ -19,12 +22,12 @@ export declare class WebSocketClient {
19 22
     create(): Promise<{}>;
20 23
     on(url: string, callback: (data: WebSocketResp) => void): void;
21 24
     off(url: string): void;
22
-    request(url: string, data: object): Promise<WebSocketResp>;
23
-    connect(): Promise<WebSocketResp>;
24
-    ping(): Promise<WebSocketResp>;
25
-    authentication(): Promise<WebSocketResp>;
25
+    request(url: string, data: object): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
26
+    connect(): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
27
+    ping(): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
28
+    authentication(): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
26 29
     onMessage(callback: ListenerCallback): void;
27
-    sendMessage(data: object): Promise<WebSocketResp>;
28
-    markServiced(data: object): Promise<WebSocketResp>;
29
-    getHistoryMessage(data: object): Promise<WebSocketResp>;
30
+    sendMessage(data: object): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
31
+    markServiced(data: object): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
32
+    getHistoryMessage(data: object): Promise<import("ts-linker-sdk/dist/types/types").WebSocketResp>;
30 33
 }

+ 0
- 34
packages/cts-api/dist/types/client.d.ts Wyświetl plik

@@ -1,34 +0,0 @@
1
-import { ReadyStateCallback } from './types/callback';
2
-export interface WebSocketResp {
3
-    value: object | string;
4
-}
5
-declare class Client {
6
-    private _maxPayload;
7
-    private _enableLogger;
8
-    private listeners;
9
-    private requestHeader;
10
-    private responseHeader;
11
-    private url;
12
-    private reconnectTimes;
13
-    private reconnectLock;
14
-    private socket;
15
-    private readyStateCallback;
16
-    constructor(url: string, readyStateCallback: ReadyStateCallback);
17
-    maxPayload: number;
18
-    enableLogger: boolean;
19
-    ping(param: object): Promise<WebSocketResp>;
20
-    request(operator: string, param: object): Promise<WebSocketResp>;
21
-    addMessageListener(operator: string, listener: (data: WebSocketResp) => void): void;
22
-    removeMessageListener(operator: string): void;
23
-    readonly readyState: number;
24
-    setRequestProperty(key: string, value: string): void;
25
-    getRequestProperty(key: string): string;
26
-    setResponseProperty(key: string, value: string): void;
27
-    getResponseProperty(key: string): string;
28
-    private connect;
29
-    reconnect(): void;
30
-    private send;
31
-    asyncSend(operator: string, param: object): Promise<WebSocketResp>;
32
-}
33
-declare function getClient(url: string, callback: ReadyStateCallback): Client;
34
-export { Client, getClient };

+ 0
- 1
packages/cts-api/dist/types/config.d.ts Wyświetl plik

@@ -1 +0,0 @@
1
-declare const PING_INTERVAL: number;

+ 0
- 7
packages/cts-api/dist/types/error.d.ts Wyświetl plik

@@ -1,7 +0,0 @@
1
-export declare class WebsocketError {
2
-    private _code;
3
-    private _msg;
4
-    constructor(code: number, msg: string);
5
-    readonly code: number;
6
-    readonly msg: string;
7
-}

+ 0
- 2
packages/cts-api/dist/types/index.d.ts Wyświetl plik

@@ -1,3 +1 @@
1 1
 export { WebSocketClient } from './WebSocketClient';
2
-export { WebsocketError } from './error';
3
-export { Client } from './client';

+ 0
- 11
packages/cts-api/dist/types/packet.d.ts Wyświetl plik

@@ -1,11 +0,0 @@
1
-export declare class Packet {
2
-    private key;
3
-    operator: number;
4
-    sequence: number;
5
-    headerLength: number;
6
-    bodyLength: number;
7
-    header: string;
8
-    body: string;
9
-    pack(operator: number, sequence: number, header: string, body: string): ArrayBuffer;
10
-    unPack(data: ArrayBuffer | SharedArrayBuffer): Packet;
11
-}

+ 0
- 12
packages/cts-api/dist/types/types/callback.d.ts Wyświetl plik

@@ -1,12 +0,0 @@
1
-interface ReadyStateCallback {
2
-    onOpen(ev: Event): void;
3
-    onError(ev: Event): void;
4
-    onClose(ev: Event): void;
5
-}
6
-interface RequestCallback {
7
-    onStart(): void;
8
-    onSuccess(data: string): void;
9
-    onError(code: number, message: string): void;
10
-    onEnd(): void;
11
-}
12
-export { ReadyStateCallback, RequestCallback };

+ 0
- 19
packages/cts-api/dist/types/utils.d.ts Wyświetl plik

@@ -1,19 +0,0 @@
1
-declare global {
2
-    interface Window {
3
-        crcTable: number[];
4
-    }
5
-}
6
-declare class Utils {
7
-    private static code;
8
-    static crc32(str: string): number;
9
-    static ab2str(buf: ArrayBuffer): string;
10
-    static str2ab(str: string): ArrayBuffer;
11
-    static decrypt(data: string, key: string, iv: string): string;
12
-    static encrypt(data: string, key: string, iv: string): string;
13
-    static binToBase64(bitString: string): string;
14
-    static base64ToBin(str: string): string;
15
-    static stringToBin(str: string): string;
16
-    static binToString(bin: string): string;
17
-    private static makeCRCTable;
18
-}
19
-export { Utils };

+ 0
- 45
packages/cts-api/example/index.ts Wyświetl plik

@@ -1,45 +0,0 @@
1
-import { Client } from '../src/client';
2
-import { WebsocketError } from '../src/error';
3
-import { WebSocketResp } from '../dist/types/client';
4
-
5
-const url = 'ws://127.0.0.1:8081';
6
-const client = new Client(url, {
7
-  onOpen(): void {
8
-    client
9
-      .ping({})
10
-      .then(
11
-        (res: WebSocketResp): void => {
12
-          console.log('ping sucessful:', res);
13
-        }
14
-      )
15
-      .catch(
16
-        (reason: WebsocketError): void => {
17
-          console.log('ping error:', reason.code, reason.msg);
18
-        }
19
-      );
20
-
21
-    client
22
-      .request('/v1/healthy', {})
23
-      .then(
24
-        (res: WebSocketResp): void => {
25
-          console.log('request successful:', res);
26
-        }
27
-      )
28
-      .catch(
29
-        (reason: WebsocketError): void => {
30
-          console.log('request error:', reason.code, reason.msg);
31
-        }
32
-      );
33
-  },
34
-
35
-  onClose(ev: Event): void {
36
-    console.log('connection error', ev);
37
-    console.log(ev);
38
-  },
39
-
40
-  onError(): void {
41
-    console.log('close connection');
42
-  }
43
-});
44
-
45
-client.enableLogger = true;

+ 0
- 9
packages/cts-api/example/types.d.ts Wyświetl plik

@@ -1,9 +0,0 @@
1
-declare module '*.less' {
2
-  const styles: Record<string, string>;
3
-  export = styles;
4
-}
5
-
6
-declare module '*.css' {
7
-  const content: any;
8
-  export default content;
9
-}

+ 1
- 0
packages/cts-api/package.json Wyświetl plik

@@ -36,6 +36,7 @@
36 36
   },
37 37
   "dependencies": {
38 38
     "node-int64": "^0.4.0",
39
+    "ts-linker-sdk": "^1.0.6",
39 40
     "uuid": "^3.3.2"
40 41
   },
41 42
   "devDependencies": {

+ 11
- 18
packages/cts-api/src/WebSocketClient.ts Wyświetl plik

@@ -1,4 +1,4 @@
1
-import { Client, getClient, WebSocketResp } from './client';
1
+import { Client } from 'ts-linker-sdk';
2 2
 import { getMetaData } from './meta';
3 3
 
4 4
 export interface WebSocketClientStatus {
@@ -7,9 +7,14 @@ export interface WebSocketClientStatus {
7 7
   login: boolean;
8 8
 }
9 9
 
10
+export interface WebSocketResp {
11
+  value: object | string;
12
+}
13
+
10 14
 export type ListenerCallback = (data: WebSocketResp) => void;
11 15
 
12 16
 const meta = getMetaData();
17
+const PING_INTERVAL = 50 * 1000;
13 18
 
14 19
 export class WebSocketClient {
15 20
   client: Client;
@@ -49,7 +54,7 @@ export class WebSocketClient {
49 54
       if (!url) {
50 55
         throw new Error('websocket url is required.');
51 56
       }
52
-      this.client = getClient(url, {
57
+      this.client = Client.getInstance(url, {
53 58
         onOpen: async () => {
54 59
           try {
55 60
             this.ping();
@@ -57,17 +62,17 @@ export class WebSocketClient {
57 62
               this.ping();
58 63
             }, PING_INTERVAL) as any;
59 64
           } catch (err) {
60
-            this.client.reconnect();
65
+            console.error(err);
61 66
           }
62 67
 
63 68
           const data = await this.connect();
64 69
           await this.authentication();
65 70
           resolve(data.value);
66 71
         },
67
-        onError: err => {
72
+        onError: () => {
68 73
           resolve(false);
69 74
         },
70
-        onClose: CloseEvent => {
75
+        onClose: () => {
71 76
           clearInterval(this.interval);
72 77
         }
73 78
       });
@@ -87,19 +92,7 @@ export class WebSocketClient {
87 92
   }
88 93
 
89 94
   async request(url: string, data: object) {
90
-    let error;
91
-
92
-    if (this.client.readyState !== 1) {
93
-      error = 'websocket connection not ready!';
94
-      throw new Error(error);
95
-    }
96
-
97
-    try {
98
-      return this.client.asyncSend(url, data);
99
-    } catch (e) {
100
-      console.error(e);
101
-      throw e;
102
-    }
95
+    return this.client.request(url, data);
103 96
   }
104 97
 
105 98
   async connect() {

+ 0
- 386
packages/cts-api/src/client.ts Wyświetl plik

@@ -1,386 +0,0 @@
1
-import { Packet } from './packet';
2
-import { Utils } from './utils';
3
-import { ReadyStateCallback } from './types/callback';
4
-import { WebsocketError } from './error';
5
-
6
-const clientError = 400;
7
-
8
-export interface WebSocketResp {
9
-  value: object | string;
10
-}
11
-
12
-/**
13
- * 初始化链接以及收发数据
14
- */
15
-class Client {
16
-  private _maxPayload: number;
17
-  private _enableLogger: boolean;
18
-  private listeners: Map<number, (data: WebSocketResp) => void>;
19
-  private requestHeader: string;
20
-  private responseHeader: string;
21
-  private url: string;
22
-  private reconnectTimes: number;
23
-  private reconnectLock: boolean;
24
-  private socket: WebSocket;
25
-  private readyStateCallback: ReadyStateCallback;
26
-
27
-  /**
28
-   * 构造函数,初始化客户端链接
29
-   * @param url websocket链接地址
30
-   * @param readyStateCallback 链接状态回调,可以处理onOpen、onClose、onError
31
-   */
32
-  public constructor(url: string, readyStateCallback: ReadyStateCallback) {
33
-    this.listeners = new Map<number, (data: WebSocketResp) => void>();
34
-    this.requestHeader = '';
35
-    this.requestHeader = '';
36
-    this._maxPayload = 1024 * 1024;
37
-    this.url = url;
38
-    this.reconnectTimes = 0;
39
-    this.readyStateCallback = readyStateCallback;
40
-    this._enableLogger = false;
41
-    this.socket = this.connect();
42
-  }
43
-
44
-  /**
45
-   * 设置可以处理的数据包上限
46
-   * @param maxPayload 最多可以处理的数据包大小
47
-   */
48
-  public set maxPayload(maxPayload: number) {
49
-    this._maxPayload = maxPayload;
50
-  }
51
-
52
-  /**
53
-   * 获取可以处理的数据包大小
54
-   */
55
-  public get maxPayload(): number {
56
-    return this._maxPayload;
57
-  }
58
-
59
-  /**
60
-   * 设置是否允许显示运行日志
61
-   */
62
-  public set enableLogger(enableLogger: boolean) {
63
-    this._enableLogger = enableLogger;
64
-  }
65
-
66
-  /**
67
-   * 获取是否显示日志的配置信息
68
-   */
69
-  public get enableLogger(): boolean {
70
-    return this._enableLogger;
71
-  }
72
-
73
-  /**
74
-   * 发送ping请求,来保持长连接
75
-   * @param param 请求参数,比如{"hello":"world"}
76
-   */
77
-  public async ping(param: object): Promise<WebSocketResp> {
78
-    return new Promise(
79
-      (resolve: (data: WebSocketResp) => void, reject: (err: WebsocketError) => void): void => {
80
-        if (this.socket.readyState !== this.socket.OPEN) {
81
-          if (this._enableLogger) {
82
-            console.log('[ping]: connection refuse');
83
-          }
84
-
85
-          reject(new WebsocketError(clientError, 'connection refuse'));
86
-        }
87
-
88
-        const heartbeatOperator = 0;
89
-
90
-        this.listeners.set(
91
-          heartbeatOperator,
92
-          (data: WebSocketResp): void => {
93
-            const code = this.getResponseProperty('code');
94
-            if (code !== '') {
95
-              const message = this.getResponseProperty('message');
96
-              reject(new WebsocketError(Number(code), message));
97
-            } else {
98
-              resolve(data);
99
-            }
100
-          }
101
-        );
102
-
103
-        const p = new Packet();
104
-        this.send(p.pack(heartbeatOperator, 0, this.requestHeader, JSON.stringify(param)));
105
-
106
-        if (this._enableLogger) {
107
-          console.info('[send data packet]', heartbeatOperator, 0, this.requestHeader, param);
108
-        }
109
-      }
110
-    );
111
-  }
112
-
113
-  /**
114
-   * 同步方式向服务端发送请求
115
-   * @param operator 路由地址
116
-   * @param param 请求参数,比如{"hello":"world"}
117
-   * @param callback 请求状态回调处理
118
-   */
119
-  public async request(operator: string, param: object): Promise<WebSocketResp> {
120
-    return await this.asyncSend(operator, param);
121
-  }
122
-
123
-  /**
124
-   * 添加消息监听
125
-   * @description 添加消息监听器,比如operator是/v1/message/listener,那么从服务端推送到/v1/message/listener的消息会进入到定义的listener里面进行处理
126
-   * @param operator 消息监听地址
127
-   * @param listener 定义如何处理从服务端返回的消息
128
-   */
129
-  public addMessageListener(operator: string, listener: (data: WebSocketResp) => void): void {
130
-    this.listeners.set(Utils.crc32(operator), listener);
131
-  }
132
-
133
-  /**
134
-   * 移除消息监听
135
-   * @param operator 消息监听地址
136
-   */
137
-  public removeMessageListener(operator: string): void {
138
-    delete this.listeners[Utils.crc32(operator)];
139
-  }
140
-
141
-  /**
142
-   * 返回Websocket链接状态
143
-   * @returns Websocket的链接状态
144
-   */
145
-  public get readyState(): number {
146
-    return this.socket.readyState;
147
-  }
148
-
149
-  /**
150
-   * 添加请求属性,会携带在数据帧里面发送到服务端
151
-   * @param key 属性名
152
-   * @param value 属性值
153
-   */
154
-  public setRequestProperty(key: string, value: string): void {
155
-    let v = this.getRequestProperty(key);
156
-
157
-    this.requestHeader = this.requestHeader.replace(key + '=' + v + ';', '');
158
-    this.requestHeader = this.requestHeader + key + '=' + value + ';';
159
-  }
160
-
161
-  /**
162
-   * 获取请求属性
163
-   * @param key 属性名
164
-   */
165
-  public getRequestProperty(key: string): string {
166
-    if (this.requestHeader !== undefined) {
167
-      let values = this.requestHeader.split(';');
168
-      for (let index in values) {
169
-        let kv = values[index].split('=');
170
-        if (kv[0] === key) {
171
-          return kv[1];
172
-        }
173
-      }
174
-    }
175
-
176
-    return '';
177
-  }
178
-
179
-  /**
180
-   * 设置响应属性,客户端基本用不到,都是服务端来进行设置
181
-   * @param key 属性名
182
-   * @param value 属性值
183
-   */
184
-  public setResponseProperty(key: string, value: string): void {
185
-    let v = this.getResponseProperty(key);
186
-
187
-    this.responseHeader = this.responseHeader.replace(key + '=' + v + ';', '');
188
-    this.responseHeader = this.responseHeader + key + '=' + value + ';';
189
-  }
190
-
191
-  /**
192
-   * 获取从服务端返回的属性
193
-   * @param key 获取响应属性
194
-   */
195
-  public getResponseProperty(key: string): string {
196
-    if (this.responseHeader !== undefined) {
197
-      let values = this.responseHeader.split(';');
198
-      for (let index in values) {
199
-        let kv = values[index].split('=');
200
-        if (kv[0] === key) {
201
-          return kv[1];
202
-        }
203
-      }
204
-    }
205
-
206
-    return '';
207
-  }
208
-
209
-  /**
210
-   * 创建websocket链接
211
-   */
212
-  private connect(): WebSocket {
213
-    const readyStateCallback = this.readyStateCallback;
214
-    let ws = new WebSocket(this.url);
215
-
216
-    ws.binaryType = 'blob';
217
-
218
-    ws.onopen = (ev): void => {
219
-      if (this._enableLogger) {
220
-        console.info('[websocket] open connection');
221
-      }
222
-
223
-      this.reconnectTimes = 0;
224
-
225
-      readyStateCallback.onOpen(ev);
226
-    };
227
-
228
-    ws.onclose = (ev): void => {
229
-      if (this._enableLogger) {
230
-        console.info('[websocket] close connection');
231
-      }
232
-
233
-      this.reconnect();
234
-
235
-      readyStateCallback.onClose(ev);
236
-    };
237
-
238
-    ws.onerror = (ev): void => {
239
-      if (this._enableLogger) {
240
-        console.info('[websocket] error');
241
-      }
242
-
243
-      this.reconnect();
244
-
245
-      readyStateCallback.onError(ev);
246
-    };
247
-
248
-    ws.onmessage = (ev): void => {
249
-      if (ev.data instanceof Blob) {
250
-        let reader = new FileReader();
251
-        reader.readAsArrayBuffer(ev.data);
252
-        reader.onload = (): void => {
253
-          try {
254
-            let packet = new Packet().unPack(reader.result as ArrayBuffer);
255
-            let packetLength = packet.headerLength + packet.bodyLength + 20;
256
-            if (packetLength > this._maxPayload) {
257
-              throw new Error('the packet is big than ' + this._maxPayload);
258
-            }
259
-
260
-            let operator = Number(packet.operator) + Number(packet.sequence);
261
-            if (this.listeners.has(operator)) {
262
-              if (packet.body === '') {
263
-                packet.body = '{}';
264
-              }
265
-
266
-              this.responseHeader = packet.header;
267
-
268
-              (this.listeners.get(operator) as (data: WebSocketResp) => void)(
269
-                JSON.parse(packet.body)
270
-              );
271
-            }
272
-
273
-            if (this._enableLogger) {
274
-              if (operator !== 0 && packet.body !== 'null') {
275
-                console.info('receive data packet', packet.body);
276
-              }
277
-            }
278
-          } catch (e) {
279
-            throw new Error(e);
280
-          }
281
-        };
282
-      } else {
283
-        throw new Error('unsupported data format');
284
-      }
285
-    };
286
-
287
-    return ws;
288
-  }
289
-
290
-  /**
291
-   * 断线重连
292
-   */
293
-  reconnect(): void {
294
-    if (!this.reconnectLock) {
295
-      this.reconnectLock = true;
296
-      if (this._enableLogger) {
297
-        console.info('websocket reconnect in ' + this.reconnectTimes + 's');
298
-      }
299
-
300
-      // 尝试重连
301
-      setTimeout((): void => {
302
-        this.reconnectTimes++;
303
-        this.socket = this.connect();
304
-        this.reconnectLock = false;
305
-      }, this.reconnectTimes * 1000);
306
-    }
307
-  }
308
-
309
-  /**
310
-   * 向服务端发送数据请求
311
-   * @param data 向服务端传送的数据
312
-   */
313
-  private send(data: ArrayBuffer): void {
314
-    if (this.socket.readyState !== this.socket.OPEN) {
315
-      if (this._enableLogger) {
316
-        console.error('[send] WebSocket is already in CLOSING or CLOSED state.');
317
-      }
318
-
319
-      return;
320
-    }
321
-
322
-    try {
323
-      this.socket.send(data);
324
-    } catch (e) {
325
-      throw new Error('send data error' + e);
326
-    }
327
-  }
328
-
329
-  /**
330
-   * 异步向服务端发送请求
331
-   * @param operator 路由地址
332
-   * @param param 请求参数,比如{"hello":"world"}
333
-   * @param callback 请求状态回调处理
334
-   */
335
-  asyncSend(operator: string, param: object): Promise<WebSocketResp> {
336
-    return new Promise(
337
-      (resolve: (data: WebSocketResp) => void, reject: (err: WebsocketError) => void): void => {
338
-        if (this.socket.readyState !== this.socket.OPEN) {
339
-          if (this._enableLogger) {
340
-            console.log('[ping]: connection refuse');
341
-          }
342
-
343
-          reject(new WebsocketError(clientError, 'asyncSend: connection refuse'));
344
-        }
345
-
346
-        const sequence = new Date().getTime();
347
-        const listener = Utils.crc32(operator) + sequence;
348
-        this.listeners.set(
349
-          listener,
350
-          (data: WebSocketResp): void => {
351
-            const code = this.getResponseProperty('code');
352
-            if (code !== '') {
353
-              const message = this.getResponseProperty('message');
354
-              reject(new WebsocketError(Number(code), message));
355
-            } else {
356
-              resolve(data);
357
-            }
358
-
359
-            delete this.listeners[listener];
360
-          }
361
-        );
362
-
363
-        const p = new Packet();
364
-        this.send(
365
-          p.pack(Utils.crc32(operator), sequence, this.requestHeader, JSON.stringify(param))
366
-        );
367
-
368
-        if (this._enableLogger) {
369
-          console.info('[send data packet]', operator, sequence, this.requestHeader, param);
370
-        }
371
-      }
372
-    );
373
-  }
374
-}
375
-
376
-let client: Client;
377
-
378
-function getClient(url: string, callback: ReadyStateCallback) {
379
-  if (!client) {
380
-    client = new Client(url, callback);
381
-  }
382
-
383
-  return client;
384
-}
385
-
386
-export { Client, getClient };

+ 0
- 2
packages/cts-api/src/config.ts Wyświetl plik

@@ -1,2 +0,0 @@
1
-// PING_INTERVAL 心跳包时间间隔
2
-const PING_INTERVAL = 50 * 1000;

+ 0
- 26
packages/cts-api/src/error.ts Wyświetl plik

@@ -1,26 +0,0 @@
1
-export class WebsocketError {
2
-  private _code: number;
3
-  private _msg: string;
4
-
5
-  /**
6
-   * 构造函数
7
-   */
8
-  public constructor(code: number, msg: string) {
9
-    this._code = code;
10
-    this._msg = msg;
11
-  }
12
-
13
-  /**
14
-   * 返回错误码
15
-   */
16
-  public get code(): number {
17
-    return this._code;
18
-  }
19
-
20
-  /**
21
-   * 返回具体的错误信息
22
-   */
23
-  public get msg(): string {
24
-    return this._msg;
25
-  }
26
-}

+ 0
- 2
packages/cts-api/src/index.ts Wyświetl plik

@@ -1,3 +1 @@
1 1
 export { WebSocketClient } from './WebSocketClient';
2
-export { WebsocketError } from './error';
3
-export { Client } from './client';

+ 0
- 59
packages/cts-api/src/packet.ts Wyświetl plik

@@ -1,59 +0,0 @@
1
-import { Utils } from './utils';
2
-import * as Int64 from 'node-int64';
3
-
4
-export class Packet {
5
-  private key: string = 'b8ca9aa66def05ff3f24919274bb4a66';
6
-  public operator: number;
7
-  public sequence: number;
8
-  public headerLength: number;
9
-  public bodyLength: number;
10
-  public header: string;
11
-  public body: string;
12
-
13
-  public pack(operator: number, sequence: number, header: string, body: string): ArrayBuffer {
14
-    header = Utils.encrypt(header, this.key, this.key);
15
-    body = Utils.encrypt(body, this.key, this.key);
16
-
17
-    const headerLength = header.length;
18
-    const bodyLength = body.length;
19
-
20
-    const buf = new ArrayBuffer(20 + headerLength + bodyLength);
21
-    const dataView = new DataView(buf);
22
-    const nsBuf = new Int64(sequence).toBuffer();
23
-
24
-    dataView.setUint32(0, operator);
25
-    dataView.setUint32(12, headerLength);
26
-    dataView.setUint32(16, bodyLength);
27
-
28
-    let bufView = new Uint8Array(buf);
29
-    for (var i = 0; i < 8; i++) {
30
-      bufView[4 + i] = nsBuf[i];
31
-    }
32
-    for (let i = 0; i < headerLength; i++) {
33
-      bufView[20 + i] = header.charCodeAt(i);
34
-    }
35
-
36
-    for (let i = 0; i < bodyLength; i++) {
37
-      bufView[20 + headerLength + i] = body.charCodeAt(i);
38
-    }
39
-
40
-    return buf;
41
-  }
42
-
43
-  public unPack(data: ArrayBuffer | SharedArrayBuffer): Packet {
44
-    const dataView = new DataView(data);
45
-
46
-    this.operator = dataView.getUint32(0, false);
47
-    this.sequence = new Int64(new Uint8Array(dataView.buffer.slice(4, 12))).toNumber();
48
-    this.headerLength = dataView.getUint32(12, false);
49
-    this.bodyLength = dataView.getUint32(16, false);
50
-
51
-    const header = Utils.ab2str(dataView.buffer.slice(20, 20 + this.headerLength));
52
-    const body = Utils.ab2str(dataView.buffer.slice(20 + this.headerLength));
53
-
54
-    this.header = Utils.decrypt(header, this.key, this.key);
55
-    this.body = Utils.decrypt(body, this.key, this.key);
56
-
57
-    return this;
58
-  }
59
-}

+ 1
- 0
packages/cts-api/src/types.d.ts Wyświetl plik

@@ -0,0 +1 @@
1
+declare module 'ts-linker-sdk/dist/index.umd';

+ 0
- 14
packages/cts-api/src/types/callback.ts Wyświetl plik

@@ -1,14 +0,0 @@
1
-interface ReadyStateCallback {
2
-  onOpen(ev: Event): void;
3
-  onError(ev: Event): void;
4
-  onClose(ev: Event): void;
5
-}
6
-
7
-interface RequestCallback {
8
-  onStart(): void;
9
-  onSuccess(data: string): void;
10
-  onError(code: number, message: string): void;
11
-  onEnd(): void;
12
-}
13
-
14
-export { ReadyStateCallback, RequestCallback };

+ 0
- 1
packages/cts-api/src/types/node-int64.d.ts Wyświetl plik

@@ -1 +0,0 @@
1
-declare module 'node-int64';

+ 0
- 157
packages/cts-api/src/utils.ts Wyświetl plik

@@ -1,157 +0,0 @@
1
-import { AES, enc, mode, pad } from 'crypto-js';
2
-
3
-declare global {
4
-  interface Window {
5
-    crcTable: number[];
6
-  }
7
-}
8
-
9
-class Utils {
10
-  private static code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(
11
-    '',
12
-  );
13
-
14
-  public static crc32(str: string): number {
15
-    const crcTable =
16
-      window.crcTable || (window.crcTable = Utils.makeCRCTable());
17
-    let crc = 0 ^ -1;
18
-
19
-    for (let i = 0; i < str.length; i++) {
20
-      crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xff];
21
-    }
22
-
23
-    return (crc ^ -1) >>> 0;
24
-  }
25
-
26
-  // ArrayBuffer 转为字符串,参数为 ArrayBuffer 对象
27
-  public static ab2str(buf: ArrayBuffer): string {
28
-    // 注意,如果是大型二进制数组,为了避免溢出,必须一个一个字符地转
29
-    if (buf && buf.byteLength < 1024) {
30
-      return String.fromCharCode.apply(null, new Uint8Array(buf));
31
-    }
32
-
33
-    const bufView = new Uint8Array(buf);
34
-    const len = bufView.length;
35
-    const byteStr = new Array(len);
36
-
37
-    for (let i = 0; i < len; i++) {
38
-      byteStr[i] = String.fromCharCode.call(null, bufView[i]);
39
-    }
40
-
41
-    return byteStr.join('');
42
-  }
43
-
44
-  // 字符串转为 ArrayBuffer 对象,参数为字符串
45
-  public static str2ab(str: string): ArrayBuffer {
46
-    const buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
47
-    const bufView = new Uint8Array(buf);
48
-
49
-    for (let i = 0, strLen = str.length; i < strLen; i++) {
50
-      bufView[i] = str.charCodeAt(i);
51
-    }
52
-
53
-    return buf;
54
-  }
55
-
56
-  // 解密服务端传递过来的字符串
57
-  public static decrypt(data: string, key: string, iv: string): string {
58
-    const binData = Utils.stringToBin(data);
59
-    const base64Data = Utils.binToBase64(binData);
60
-
61
-    const bytes = AES.decrypt(base64Data, enc.Latin1.parse(key), {
62
-      iv: enc.Latin1.parse(iv),
63
-      mode: mode.CBC,
64
-      padding: pad.Pkcs7,
65
-    });
66
-
67
-    return bytes.toString(enc.Utf8);
68
-  }
69
-
70
-  // 加密字符串以后传递到服务端
71
-  public static encrypt(data: string, key: string, iv: string): string {
72
-    const result = AES.encrypt(data, enc.Latin1.parse(key), {
73
-      iv: enc.Latin1.parse(iv),
74
-      mode: mode.CBC,
75
-      padding: pad.Pkcs7,
76
-    });
77
-
78
-    return Utils.binToString(Utils.base64ToBin(result.toString()));
79
-  }
80
-
81
-  // 字节数组转换为base64编码
82
-  public static binToBase64(bitString: string): string {
83
-    const tail = bitString.length % 6;
84
-    const bitStringTemp1 = bitString.substr(0, bitString.length - tail);
85
-
86
-    let result = '';
87
-    let bitStringTemp2 = bitString.substr(bitString.length - tail, tail);
88
-
89
-    for (let i = 0; i < bitStringTemp1.length; i += 6) {
90
-      let index = parseInt(bitStringTemp1.substr(i, 6), 2);
91
-      result += Utils.code[index];
92
-    }
93
-
94
-    bitStringTemp2 += new Array(7 - tail).join('0');
95
-    if (tail) {
96
-      result += Utils.code[parseInt(bitStringTemp2, 2)];
97
-      result += new Array((6 - tail) / 2 + 1).join('=');
98
-    }
99
-
100
-    return result;
101
-  }
102
-
103
-  // base64编码转换为字节数组
104
-  public static base64ToBin(str: string): string {
105
-    let bitString = '';
106
-    let tail = 0;
107
-
108
-    for (let i = 0; i < str.length; i++) {
109
-      if (str[i] !== '=') {
110
-        let decode = this.code.indexOf(str[i]).toString(2);
111
-        bitString += new Array(7 - decode.length).join('0') + decode;
112
-      } else {
113
-        tail++;
114
-      }
115
-    }
116
-
117
-    return bitString.substr(0, bitString.length - tail * 2);
118
-  }
119
-
120
-  // 字符串转换为字节数组
121
-  public static stringToBin(str: string): string {
122
-    let result = '';
123
-    for (let i = 0; i < str.length; i++) {
124
-      let charCode = str.charCodeAt(i).toString(2);
125
-      result += new Array(9 - charCode.length).join('0') + charCode;
126
-    }
127
-
128
-    return result;
129
-  }
130
-
131
-  // 字节数组转化为字符串
132
-  public static binToString(bin: string): string {
133
-    let result = '';
134
-    for (let i = 0; i < bin.length; i += 8) {
135
-      result += String.fromCharCode(parseInt(bin.substr(i, 8), 2));
136
-    }
137
-
138
-    return result;
139
-  }
140
-
141
-  private static makeCRCTable(): number[] {
142
-    let c: number;
143
-    let crcTable: number[] = [];
144
-
145
-    for (let n = 0; n < 256; n++) {
146
-      c = n;
147
-      for (let k = 0; k < 8; k++) {
148
-        c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
149
-      }
150
-      crcTable[n] = c;
151
-    }
152
-
153
-    return crcTable;
154
-  }
155
-}
156
-
157
-export { Utils };

+ 8
- 0
packages/cts-api/yarn.lock Wyświetl plik

@@ -10361,6 +10361,14 @@ ts-jest@^24.0.2:
10361 10361
     semver "^5.5"
10362 10362
     yargs-parser "10.x"
10363 10363
 
10364
+ts-linker-sdk@^1.0.6:
10365
+  version "1.0.6"
10366
+  resolved "https://registry.npm.taobao.org/ts-linker-sdk/download/ts-linker-sdk-1.0.6.tgz#7db43684758ac7f91fc7ee38eafa35b5334d6026"
10367
+  integrity sha1-fbQ2hHWKx/kfx+446vo1tTNNYCY=
10368
+  dependencies:
10369
+    crypto-js "^3.1.9-1"
10370
+    node-int64 "^0.4.0"
10371
+
10364 10372
 ts-loader@5.4.5:
10365 10373
   version "5.4.5"
10366 10374
   resolved "https://registry.npm.taobao.org/ts-loader/download/ts-loader-5.4.5.tgz#a0c1f034b017a9344cef0961bfd97cc192492b8b"

+ 1328
- 920
yarn.lock
Plik diff jest za duży
Wyświetl plik