UNPKG

315 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var platformAdaptersNode = require('@leancloud/platform-adapters-node');
8var _defineProperty = _interopDefault(require('@babel/runtime/helpers/defineProperty'));
9var protobufLight = _interopDefault(require('protobufjs/dist/protobuf-light'));
10var EventEmitter = _interopDefault(require('eventemitter3'));
11var _regeneratorRuntime = _interopDefault(require('@babel/runtime/regenerator'));
12var _asyncToGenerator = _interopDefault(require('@babel/runtime/helpers/asyncToGenerator'));
13var _toConsumableArray = _interopDefault(require('@babel/runtime/helpers/toConsumableArray'));
14var _objectWithoutProperties = _interopDefault(require('@babel/runtime/helpers/objectWithoutProperties'));
15var _assertThisInitialized = _interopDefault(require('@babel/runtime/helpers/assertThisInitialized'));
16var _inheritsLoose = _interopDefault(require('@babel/runtime/helpers/inheritsLoose'));
17var d = _interopDefault(require('debug'));
18var shuffle = _interopDefault(require('lodash/shuffle'));
19var values = _interopDefault(require('lodash/values'));
20var _toArray = _interopDefault(require('@babel/runtime/helpers/toArray'));
21var _createClass = _interopDefault(require('@babel/runtime/helpers/createClass'));
22var _applyDecoratedDescriptor = _interopDefault(require('@babel/runtime/helpers/applyDecoratedDescriptor'));
23var StateMachine = _interopDefault(require('javascript-state-machine'));
24var _typeof = _interopDefault(require('@babel/runtime/helpers/typeof'));
25var isPlainObject = _interopDefault(require('lodash/isPlainObject'));
26var promiseTimeout = require('promise-timeout');
27var uuid = _interopDefault(require('uuid/v4'));
28var _slicedToArray = _interopDefault(require('@babel/runtime/helpers/slicedToArray'));
29var base64Arraybuffer = require('base64-arraybuffer');
30var remove = _interopDefault(require('lodash/remove'));
31var isEmpty = _interopDefault(require('lodash/isEmpty'));
32var cloneDeep = _interopDefault(require('lodash/cloneDeep'));
33var find = _interopDefault(require('lodash/find'));
34var _get = _interopDefault(require('lodash/get'));
35
36var messageCompiled = protobufLight.newBuilder({})['import']({
37 "package": 'push_server.messages2',
38 syntax: 'proto2',
39 options: {
40 objc_class_prefix: 'AVIM'
41 },
42 messages: [{
43 name: 'JsonObjectMessage',
44 syntax: 'proto2',
45 fields: [{
46 rule: 'required',
47 type: 'string',
48 name: 'data',
49 id: 1
50 }]
51 }, {
52 name: 'UnreadTuple',
53 syntax: 'proto2',
54 fields: [{
55 rule: 'required',
56 type: 'string',
57 name: 'cid',
58 id: 1
59 }, {
60 rule: 'required',
61 type: 'int32',
62 name: 'unread',
63 id: 2
64 }, {
65 rule: 'optional',
66 type: 'string',
67 name: 'mid',
68 id: 3
69 }, {
70 rule: 'optional',
71 type: 'int64',
72 name: 'timestamp',
73 id: 4
74 }, {
75 rule: 'optional',
76 type: 'string',
77 name: 'from',
78 id: 5
79 }, {
80 rule: 'optional',
81 type: 'string',
82 name: 'data',
83 id: 6
84 }, {
85 rule: 'optional',
86 type: 'int64',
87 name: 'patchTimestamp',
88 id: 7
89 }, {
90 rule: 'optional',
91 type: 'bool',
92 name: 'mentioned',
93 id: 8
94 }, {
95 rule: 'optional',
96 type: 'bytes',
97 name: 'binaryMsg',
98 id: 9
99 }, {
100 rule: 'optional',
101 type: 'int32',
102 name: 'convType',
103 id: 10
104 }]
105 }, {
106 name: 'LogItem',
107 syntax: 'proto2',
108 fields: [{
109 rule: 'optional',
110 type: 'string',
111 name: 'from',
112 id: 1
113 }, {
114 rule: 'optional',
115 type: 'string',
116 name: 'data',
117 id: 2
118 }, {
119 rule: 'optional',
120 type: 'int64',
121 name: 'timestamp',
122 id: 3
123 }, {
124 rule: 'optional',
125 type: 'string',
126 name: 'msgId',
127 id: 4
128 }, {
129 rule: 'optional',
130 type: 'int64',
131 name: 'ackAt',
132 id: 5
133 }, {
134 rule: 'optional',
135 type: 'int64',
136 name: 'readAt',
137 id: 6
138 }, {
139 rule: 'optional',
140 type: 'int64',
141 name: 'patchTimestamp',
142 id: 7
143 }, {
144 rule: 'optional',
145 type: 'bool',
146 name: 'mentionAll',
147 id: 8
148 }, {
149 rule: 'repeated',
150 type: 'string',
151 name: 'mentionPids',
152 id: 9
153 }, {
154 rule: 'optional',
155 type: 'bool',
156 name: 'bin',
157 id: 10
158 }, {
159 rule: 'optional',
160 type: 'int32',
161 name: 'convType',
162 id: 11
163 }]
164 }, {
165 name: 'ConvMemberInfo',
166 syntax: 'proto2',
167 fields: [{
168 rule: 'optional',
169 type: 'string',
170 name: 'pid',
171 id: 1
172 }, {
173 rule: 'optional',
174 type: 'string',
175 name: 'role',
176 id: 2
177 }, {
178 rule: 'optional',
179 type: 'string',
180 name: 'infoId',
181 id: 3
182 }]
183 }, {
184 name: 'DataCommand',
185 syntax: 'proto2',
186 fields: [{
187 rule: 'repeated',
188 type: 'string',
189 name: 'ids',
190 id: 1
191 }, {
192 rule: 'repeated',
193 type: 'JsonObjectMessage',
194 name: 'msg',
195 id: 2
196 }, {
197 rule: 'optional',
198 type: 'bool',
199 name: 'offline',
200 id: 3
201 }]
202 }, {
203 name: 'SessionCommand',
204 syntax: 'proto2',
205 fields: [{
206 rule: 'optional',
207 type: 'int64',
208 name: 't',
209 id: 1
210 }, {
211 rule: 'optional',
212 type: 'string',
213 name: 'n',
214 id: 2
215 }, {
216 rule: 'optional',
217 type: 'string',
218 name: 's',
219 id: 3
220 }, {
221 rule: 'optional',
222 type: 'string',
223 name: 'ua',
224 id: 4
225 }, {
226 rule: 'optional',
227 type: 'bool',
228 name: 'r',
229 id: 5
230 }, {
231 rule: 'optional',
232 type: 'string',
233 name: 'tag',
234 id: 6
235 }, {
236 rule: 'optional',
237 type: 'string',
238 name: 'deviceId',
239 id: 7
240 }, {
241 rule: 'repeated',
242 type: 'string',
243 name: 'sessionPeerIds',
244 id: 8
245 }, {
246 rule: 'repeated',
247 type: 'string',
248 name: 'onlineSessionPeerIds',
249 id: 9
250 }, {
251 rule: 'optional',
252 type: 'string',
253 name: 'st',
254 id: 10
255 }, {
256 rule: 'optional',
257 type: 'int32',
258 name: 'stTtl',
259 id: 11
260 }, {
261 rule: 'optional',
262 type: 'int32',
263 name: 'code',
264 id: 12
265 }, {
266 rule: 'optional',
267 type: 'string',
268 name: 'reason',
269 id: 13
270 }, {
271 rule: 'optional',
272 type: 'string',
273 name: 'deviceToken',
274 id: 14
275 }, {
276 rule: 'optional',
277 type: 'bool',
278 name: 'sp',
279 id: 15
280 }, {
281 rule: 'optional',
282 type: 'string',
283 name: 'detail',
284 id: 16
285 }, {
286 rule: 'optional',
287 type: 'int64',
288 name: 'lastUnreadNotifTime',
289 id: 17
290 }, {
291 rule: 'optional',
292 type: 'int64',
293 name: 'lastPatchTime',
294 id: 18
295 }, {
296 rule: 'optional',
297 type: 'int64',
298 name: 'configBitmap',
299 id: 19
300 }]
301 }, {
302 name: 'ErrorCommand',
303 syntax: 'proto2',
304 fields: [{
305 rule: 'required',
306 type: 'int32',
307 name: 'code',
308 id: 1
309 }, {
310 rule: 'required',
311 type: 'string',
312 name: 'reason',
313 id: 2
314 }, {
315 rule: 'optional',
316 type: 'int32',
317 name: 'appCode',
318 id: 3
319 }, {
320 rule: 'optional',
321 type: 'string',
322 name: 'detail',
323 id: 4
324 }, {
325 rule: 'repeated',
326 type: 'string',
327 name: 'pids',
328 id: 5
329 }, {
330 rule: 'optional',
331 type: 'string',
332 name: 'appMsg',
333 id: 6
334 }]
335 }, {
336 name: 'DirectCommand',
337 syntax: 'proto2',
338 fields: [{
339 rule: 'optional',
340 type: 'string',
341 name: 'msg',
342 id: 1
343 }, {
344 rule: 'optional',
345 type: 'string',
346 name: 'uid',
347 id: 2
348 }, {
349 rule: 'optional',
350 type: 'string',
351 name: 'fromPeerId',
352 id: 3
353 }, {
354 rule: 'optional',
355 type: 'int64',
356 name: 'timestamp',
357 id: 4
358 }, {
359 rule: 'optional',
360 type: 'bool',
361 name: 'offline',
362 id: 5
363 }, {
364 rule: 'optional',
365 type: 'bool',
366 name: 'hasMore',
367 id: 6
368 }, {
369 rule: 'repeated',
370 type: 'string',
371 name: 'toPeerIds',
372 id: 7
373 }, {
374 rule: 'optional',
375 type: 'bool',
376 name: 'r',
377 id: 10
378 }, {
379 rule: 'optional',
380 type: 'string',
381 name: 'cid',
382 id: 11
383 }, {
384 rule: 'optional',
385 type: 'string',
386 name: 'id',
387 id: 12
388 }, {
389 rule: 'optional',
390 type: 'bool',
391 name: 'transient',
392 id: 13
393 }, {
394 rule: 'optional',
395 type: 'string',
396 name: 'dt',
397 id: 14
398 }, {
399 rule: 'optional',
400 type: 'string',
401 name: 'roomId',
402 id: 15
403 }, {
404 rule: 'optional',
405 type: 'string',
406 name: 'pushData',
407 id: 16
408 }, {
409 rule: 'optional',
410 type: 'bool',
411 name: 'will',
412 id: 17
413 }, {
414 rule: 'optional',
415 type: 'int64',
416 name: 'patchTimestamp',
417 id: 18
418 }, {
419 rule: 'optional',
420 type: 'bytes',
421 name: 'binaryMsg',
422 id: 19
423 }, {
424 rule: 'repeated',
425 type: 'string',
426 name: 'mentionPids',
427 id: 20
428 }, {
429 rule: 'optional',
430 type: 'bool',
431 name: 'mentionAll',
432 id: 21
433 }, {
434 rule: 'optional',
435 type: 'int32',
436 name: 'convType',
437 id: 22
438 }]
439 }, {
440 name: 'AckCommand',
441 syntax: 'proto2',
442 fields: [{
443 rule: 'optional',
444 type: 'int32',
445 name: 'code',
446 id: 1
447 }, {
448 rule: 'optional',
449 type: 'string',
450 name: 'reason',
451 id: 2
452 }, {
453 rule: 'optional',
454 type: 'string',
455 name: 'mid',
456 id: 3
457 }, {
458 rule: 'optional',
459 type: 'string',
460 name: 'cid',
461 id: 4
462 }, {
463 rule: 'optional',
464 type: 'int64',
465 name: 't',
466 id: 5
467 }, {
468 rule: 'optional',
469 type: 'string',
470 name: 'uid',
471 id: 6
472 }, {
473 rule: 'optional',
474 type: 'int64',
475 name: 'fromts',
476 id: 7
477 }, {
478 rule: 'optional',
479 type: 'int64',
480 name: 'tots',
481 id: 8
482 }, {
483 rule: 'optional',
484 type: 'string',
485 name: 'type',
486 id: 9
487 }, {
488 rule: 'repeated',
489 type: 'string',
490 name: 'ids',
491 id: 10
492 }, {
493 rule: 'optional',
494 type: 'int32',
495 name: 'appCode',
496 id: 11
497 }, {
498 rule: 'optional',
499 type: 'string',
500 name: 'appMsg',
501 id: 12
502 }]
503 }, {
504 name: 'UnreadCommand',
505 syntax: 'proto2',
506 fields: [{
507 rule: 'repeated',
508 type: 'UnreadTuple',
509 name: 'convs',
510 id: 1
511 }, {
512 rule: 'optional',
513 type: 'int64',
514 name: 'notifTime',
515 id: 2
516 }]
517 }, {
518 name: 'ConvCommand',
519 syntax: 'proto2',
520 fields: [{
521 rule: 'repeated',
522 type: 'string',
523 name: 'm',
524 id: 1
525 }, {
526 rule: 'optional',
527 type: 'bool',
528 name: 'transient',
529 id: 2
530 }, {
531 rule: 'optional',
532 type: 'bool',
533 name: 'unique',
534 id: 3
535 }, {
536 rule: 'optional',
537 type: 'string',
538 name: 'cid',
539 id: 4
540 }, {
541 rule: 'optional',
542 type: 'string',
543 name: 'cdate',
544 id: 5
545 }, {
546 rule: 'optional',
547 type: 'string',
548 name: 'initBy',
549 id: 6
550 }, {
551 rule: 'optional',
552 type: 'string',
553 name: 'sort',
554 id: 7
555 }, {
556 rule: 'optional',
557 type: 'int32',
558 name: 'limit',
559 id: 8
560 }, {
561 rule: 'optional',
562 type: 'int32',
563 name: 'skip',
564 id: 9
565 }, {
566 rule: 'optional',
567 type: 'int32',
568 name: 'flag',
569 id: 10
570 }, {
571 rule: 'optional',
572 type: 'int32',
573 name: 'count',
574 id: 11
575 }, {
576 rule: 'optional',
577 type: 'string',
578 name: 'udate',
579 id: 12
580 }, {
581 rule: 'optional',
582 type: 'int64',
583 name: 't',
584 id: 13
585 }, {
586 rule: 'optional',
587 type: 'string',
588 name: 'n',
589 id: 14
590 }, {
591 rule: 'optional',
592 type: 'string',
593 name: 's',
594 id: 15
595 }, {
596 rule: 'optional',
597 type: 'bool',
598 name: 'statusSub',
599 id: 16
600 }, {
601 rule: 'optional',
602 type: 'bool',
603 name: 'statusPub',
604 id: 17
605 }, {
606 rule: 'optional',
607 type: 'int32',
608 name: 'statusTTL',
609 id: 18
610 }, {
611 rule: 'optional',
612 type: 'string',
613 name: 'uniqueId',
614 id: 19
615 }, {
616 rule: 'optional',
617 type: 'string',
618 name: 'targetClientId',
619 id: 20
620 }, {
621 rule: 'optional',
622 type: 'int64',
623 name: 'maxReadTimestamp',
624 id: 21
625 }, {
626 rule: 'optional',
627 type: 'int64',
628 name: 'maxAckTimestamp',
629 id: 22
630 }, {
631 rule: 'optional',
632 type: 'bool',
633 name: 'queryAllMembers',
634 id: 23
635 }, {
636 rule: 'repeated',
637 type: 'MaxReadTuple',
638 name: 'maxReadTuples',
639 id: 24
640 }, {
641 rule: 'repeated',
642 type: 'string',
643 name: 'cids',
644 id: 25
645 }, {
646 rule: 'optional',
647 type: 'ConvMemberInfo',
648 name: 'info',
649 id: 26
650 }, {
651 rule: 'optional',
652 type: 'bool',
653 name: 'tempConv',
654 id: 27
655 }, {
656 rule: 'optional',
657 type: 'int32',
658 name: 'tempConvTTL',
659 id: 28
660 }, {
661 rule: 'repeated',
662 type: 'string',
663 name: 'tempConvIds',
664 id: 29
665 }, {
666 rule: 'repeated',
667 type: 'string',
668 name: 'allowedPids',
669 id: 30
670 }, {
671 rule: 'repeated',
672 type: 'ErrorCommand',
673 name: 'failedPids',
674 id: 31
675 }, {
676 rule: 'optional',
677 type: 'string',
678 name: 'next',
679 id: 40
680 }, {
681 rule: 'optional',
682 type: 'JsonObjectMessage',
683 name: 'results',
684 id: 100
685 }, {
686 rule: 'optional',
687 type: 'JsonObjectMessage',
688 name: 'where',
689 id: 101
690 }, {
691 rule: 'optional',
692 type: 'JsonObjectMessage',
693 name: 'attr',
694 id: 103
695 }, {
696 rule: 'optional',
697 type: 'JsonObjectMessage',
698 name: 'attrModified',
699 id: 104
700 }]
701 }, {
702 name: 'RoomCommand',
703 syntax: 'proto2',
704 fields: [{
705 rule: 'optional',
706 type: 'string',
707 name: 'roomId',
708 id: 1
709 }, {
710 rule: 'optional',
711 type: 'string',
712 name: 's',
713 id: 2
714 }, {
715 rule: 'optional',
716 type: 'int64',
717 name: 't',
718 id: 3
719 }, {
720 rule: 'optional',
721 type: 'string',
722 name: 'n',
723 id: 4
724 }, {
725 rule: 'optional',
726 type: 'bool',
727 name: 'transient',
728 id: 5
729 }, {
730 rule: 'repeated',
731 type: 'string',
732 name: 'roomPeerIds',
733 id: 6
734 }, {
735 rule: 'optional',
736 type: 'string',
737 name: 'byPeerId',
738 id: 7
739 }]
740 }, {
741 name: 'LogsCommand',
742 syntax: 'proto2',
743 fields: [{
744 rule: 'optional',
745 type: 'string',
746 name: 'cid',
747 id: 1
748 }, {
749 rule: 'optional',
750 type: 'int32',
751 name: 'l',
752 id: 2
753 }, {
754 rule: 'optional',
755 type: 'int32',
756 name: 'limit',
757 id: 3
758 }, {
759 rule: 'optional',
760 type: 'int64',
761 name: 't',
762 id: 4
763 }, {
764 rule: 'optional',
765 type: 'int64',
766 name: 'tt',
767 id: 5
768 }, {
769 rule: 'optional',
770 type: 'string',
771 name: 'tmid',
772 id: 6
773 }, {
774 rule: 'optional',
775 type: 'string',
776 name: 'mid',
777 id: 7
778 }, {
779 rule: 'optional',
780 type: 'string',
781 name: 'checksum',
782 id: 8
783 }, {
784 rule: 'optional',
785 type: 'bool',
786 name: 'stored',
787 id: 9
788 }, {
789 rule: 'optional',
790 type: 'QueryDirection',
791 name: 'direction',
792 id: 10,
793 options: {
794 "default": 'OLD'
795 }
796 }, {
797 rule: 'optional',
798 type: 'bool',
799 name: 'tIncluded',
800 id: 11
801 }, {
802 rule: 'optional',
803 type: 'bool',
804 name: 'ttIncluded',
805 id: 12
806 }, {
807 rule: 'optional',
808 type: 'int32',
809 name: 'lctype',
810 id: 13
811 }, {
812 rule: 'repeated',
813 type: 'LogItem',
814 name: 'logs',
815 id: 105
816 }],
817 enums: [{
818 name: 'QueryDirection',
819 syntax: 'proto2',
820 values: [{
821 name: 'OLD',
822 id: 1
823 }, {
824 name: 'NEW',
825 id: 2
826 }]
827 }]
828 }, {
829 name: 'RcpCommand',
830 syntax: 'proto2',
831 fields: [{
832 rule: 'optional',
833 type: 'string',
834 name: 'id',
835 id: 1
836 }, {
837 rule: 'optional',
838 type: 'string',
839 name: 'cid',
840 id: 2
841 }, {
842 rule: 'optional',
843 type: 'int64',
844 name: 't',
845 id: 3
846 }, {
847 rule: 'optional',
848 type: 'bool',
849 name: 'read',
850 id: 4
851 }, {
852 rule: 'optional',
853 type: 'string',
854 name: 'from',
855 id: 5
856 }]
857 }, {
858 name: 'ReadTuple',
859 syntax: 'proto2',
860 fields: [{
861 rule: 'required',
862 type: 'string',
863 name: 'cid',
864 id: 1
865 }, {
866 rule: 'optional',
867 type: 'int64',
868 name: 'timestamp',
869 id: 2
870 }, {
871 rule: 'optional',
872 type: 'string',
873 name: 'mid',
874 id: 3
875 }]
876 }, {
877 name: 'MaxReadTuple',
878 syntax: 'proto2',
879 fields: [{
880 rule: 'optional',
881 type: 'string',
882 name: 'pid',
883 id: 1
884 }, {
885 rule: 'optional',
886 type: 'int64',
887 name: 'maxAckTimestamp',
888 id: 2
889 }, {
890 rule: 'optional',
891 type: 'int64',
892 name: 'maxReadTimestamp',
893 id: 3
894 }]
895 }, {
896 name: 'ReadCommand',
897 syntax: 'proto2',
898 fields: [{
899 rule: 'optional',
900 type: 'string',
901 name: 'cid',
902 id: 1
903 }, {
904 rule: 'repeated',
905 type: 'string',
906 name: 'cids',
907 id: 2
908 }, {
909 rule: 'repeated',
910 type: 'ReadTuple',
911 name: 'convs',
912 id: 3
913 }]
914 }, {
915 name: 'PresenceCommand',
916 syntax: 'proto2',
917 fields: [{
918 rule: 'optional',
919 type: 'StatusType',
920 name: 'status',
921 id: 1
922 }, {
923 rule: 'repeated',
924 type: 'string',
925 name: 'sessionPeerIds',
926 id: 2
927 }, {
928 rule: 'optional',
929 type: 'string',
930 name: 'cid',
931 id: 3
932 }]
933 }, {
934 name: 'ReportCommand',
935 syntax: 'proto2',
936 fields: [{
937 rule: 'optional',
938 type: 'bool',
939 name: 'initiative',
940 id: 1
941 }, {
942 rule: 'optional',
943 type: 'string',
944 name: 'type',
945 id: 2
946 }, {
947 rule: 'optional',
948 type: 'string',
949 name: 'data',
950 id: 3
951 }]
952 }, {
953 name: 'PatchItem',
954 syntax: 'proto2',
955 fields: [{
956 rule: 'optional',
957 type: 'string',
958 name: 'cid',
959 id: 1
960 }, {
961 rule: 'optional',
962 type: 'string',
963 name: 'mid',
964 id: 2
965 }, {
966 rule: 'optional',
967 type: 'int64',
968 name: 'timestamp',
969 id: 3
970 }, {
971 rule: 'optional',
972 type: 'bool',
973 name: 'recall',
974 id: 4
975 }, {
976 rule: 'optional',
977 type: 'string',
978 name: 'data',
979 id: 5
980 }, {
981 rule: 'optional',
982 type: 'int64',
983 name: 'patchTimestamp',
984 id: 6
985 }, {
986 rule: 'optional',
987 type: 'string',
988 name: 'from',
989 id: 7
990 }, {
991 rule: 'optional',
992 type: 'bytes',
993 name: 'binaryMsg',
994 id: 8
995 }, {
996 rule: 'optional',
997 type: 'bool',
998 name: 'mentionAll',
999 id: 9
1000 }, {
1001 rule: 'repeated',
1002 type: 'string',
1003 name: 'mentionPids',
1004 id: 10
1005 }, {
1006 rule: 'optional',
1007 type: 'int64',
1008 name: 'patchCode',
1009 id: 11
1010 }, {
1011 rule: 'optional',
1012 type: 'string',
1013 name: 'patchReason',
1014 id: 12
1015 }]
1016 }, {
1017 name: 'PatchCommand',
1018 syntax: 'proto2',
1019 fields: [{
1020 rule: 'repeated',
1021 type: 'PatchItem',
1022 name: 'patches',
1023 id: 1
1024 }, {
1025 rule: 'optional',
1026 type: 'int64',
1027 name: 'lastPatchTime',
1028 id: 2
1029 }]
1030 }, {
1031 name: 'PubsubCommand',
1032 syntax: 'proto2',
1033 fields: [{
1034 rule: 'optional',
1035 type: 'string',
1036 name: 'cid',
1037 id: 1
1038 }, {
1039 rule: 'repeated',
1040 type: 'string',
1041 name: 'cids',
1042 id: 2
1043 }, {
1044 rule: 'optional',
1045 type: 'string',
1046 name: 'topic',
1047 id: 3
1048 }, {
1049 rule: 'optional',
1050 type: 'string',
1051 name: 'subtopic',
1052 id: 4
1053 }, {
1054 rule: 'repeated',
1055 type: 'string',
1056 name: 'topics',
1057 id: 5
1058 }, {
1059 rule: 'repeated',
1060 type: 'string',
1061 name: 'subtopics',
1062 id: 6
1063 }, {
1064 rule: 'optional',
1065 type: 'JsonObjectMessage',
1066 name: 'results',
1067 id: 7
1068 }]
1069 }, {
1070 name: 'BlacklistCommand',
1071 syntax: 'proto2',
1072 fields: [{
1073 rule: 'optional',
1074 type: 'string',
1075 name: 'srcCid',
1076 id: 1
1077 }, {
1078 rule: 'repeated',
1079 type: 'string',
1080 name: 'toPids',
1081 id: 2
1082 }, {
1083 rule: 'optional',
1084 type: 'string',
1085 name: 'srcPid',
1086 id: 3
1087 }, {
1088 rule: 'repeated',
1089 type: 'string',
1090 name: 'toCids',
1091 id: 4
1092 }, {
1093 rule: 'optional',
1094 type: 'int32',
1095 name: 'limit',
1096 id: 5
1097 }, {
1098 rule: 'optional',
1099 type: 'string',
1100 name: 'next',
1101 id: 6
1102 }, {
1103 rule: 'repeated',
1104 type: 'string',
1105 name: 'blockedPids',
1106 id: 8
1107 }, {
1108 rule: 'repeated',
1109 type: 'string',
1110 name: 'blockedCids',
1111 id: 9
1112 }, {
1113 rule: 'repeated',
1114 type: 'string',
1115 name: 'allowedPids',
1116 id: 10
1117 }, {
1118 rule: 'repeated',
1119 type: 'ErrorCommand',
1120 name: 'failedPids',
1121 id: 11
1122 }, {
1123 rule: 'optional',
1124 type: 'int64',
1125 name: 't',
1126 id: 12
1127 }, {
1128 rule: 'optional',
1129 type: 'string',
1130 name: 'n',
1131 id: 13
1132 }, {
1133 rule: 'optional',
1134 type: 'string',
1135 name: 's',
1136 id: 14
1137 }]
1138 }, {
1139 name: 'GenericCommand',
1140 syntax: 'proto2',
1141 fields: [{
1142 rule: 'optional',
1143 type: 'CommandType',
1144 name: 'cmd',
1145 id: 1
1146 }, {
1147 rule: 'optional',
1148 type: 'OpType',
1149 name: 'op',
1150 id: 2
1151 }, {
1152 rule: 'optional',
1153 type: 'string',
1154 name: 'appId',
1155 id: 3
1156 }, {
1157 rule: 'optional',
1158 type: 'string',
1159 name: 'peerId',
1160 id: 4
1161 }, {
1162 rule: 'optional',
1163 type: 'int32',
1164 name: 'i',
1165 id: 5
1166 }, {
1167 rule: 'optional',
1168 type: 'string',
1169 name: 'installationId',
1170 id: 6
1171 }, {
1172 rule: 'optional',
1173 type: 'int32',
1174 name: 'priority',
1175 id: 7
1176 }, {
1177 rule: 'optional',
1178 type: 'int32',
1179 name: 'service',
1180 id: 8
1181 }, {
1182 rule: 'optional',
1183 type: 'int64',
1184 name: 'serverTs',
1185 id: 9
1186 }, {
1187 rule: 'optional',
1188 type: 'int64',
1189 name: 'clientTs',
1190 id: 10
1191 }, {
1192 rule: 'optional',
1193 type: 'int32',
1194 name: 'notificationType',
1195 id: 11
1196 }, {
1197 rule: 'optional',
1198 type: 'DataCommand',
1199 name: 'dataMessage',
1200 id: 101
1201 }, {
1202 rule: 'optional',
1203 type: 'SessionCommand',
1204 name: 'sessionMessage',
1205 id: 102
1206 }, {
1207 rule: 'optional',
1208 type: 'ErrorCommand',
1209 name: 'errorMessage',
1210 id: 103
1211 }, {
1212 rule: 'optional',
1213 type: 'DirectCommand',
1214 name: 'directMessage',
1215 id: 104
1216 }, {
1217 rule: 'optional',
1218 type: 'AckCommand',
1219 name: 'ackMessage',
1220 id: 105
1221 }, {
1222 rule: 'optional',
1223 type: 'UnreadCommand',
1224 name: 'unreadMessage',
1225 id: 106
1226 }, {
1227 rule: 'optional',
1228 type: 'ReadCommand',
1229 name: 'readMessage',
1230 id: 107
1231 }, {
1232 rule: 'optional',
1233 type: 'RcpCommand',
1234 name: 'rcpMessage',
1235 id: 108
1236 }, {
1237 rule: 'optional',
1238 type: 'LogsCommand',
1239 name: 'logsMessage',
1240 id: 109
1241 }, {
1242 rule: 'optional',
1243 type: 'ConvCommand',
1244 name: 'convMessage',
1245 id: 110
1246 }, {
1247 rule: 'optional',
1248 type: 'RoomCommand',
1249 name: 'roomMessage',
1250 id: 111
1251 }, {
1252 rule: 'optional',
1253 type: 'PresenceCommand',
1254 name: 'presenceMessage',
1255 id: 112
1256 }, {
1257 rule: 'optional',
1258 type: 'ReportCommand',
1259 name: 'reportMessage',
1260 id: 113
1261 }, {
1262 rule: 'optional',
1263 type: 'PatchCommand',
1264 name: 'patchMessage',
1265 id: 114
1266 }, {
1267 rule: 'optional',
1268 type: 'PubsubCommand',
1269 name: 'pubsubMessage',
1270 id: 115
1271 }, {
1272 rule: 'optional',
1273 type: 'BlacklistCommand',
1274 name: 'blacklistMessage',
1275 id: 116
1276 }]
1277 }],
1278 enums: [{
1279 name: 'CommandType',
1280 syntax: 'proto2',
1281 values: [{
1282 name: 'session',
1283 id: 0
1284 }, {
1285 name: 'conv',
1286 id: 1
1287 }, {
1288 name: 'direct',
1289 id: 2
1290 }, {
1291 name: 'ack',
1292 id: 3
1293 }, {
1294 name: 'rcp',
1295 id: 4
1296 }, {
1297 name: 'unread',
1298 id: 5
1299 }, {
1300 name: 'logs',
1301 id: 6
1302 }, {
1303 name: 'error',
1304 id: 7
1305 }, {
1306 name: 'login',
1307 id: 8
1308 }, {
1309 name: 'data',
1310 id: 9
1311 }, {
1312 name: 'room',
1313 id: 10
1314 }, {
1315 name: 'read',
1316 id: 11
1317 }, {
1318 name: 'presence',
1319 id: 12
1320 }, {
1321 name: 'report',
1322 id: 13
1323 }, {
1324 name: 'echo',
1325 id: 14
1326 }, {
1327 name: 'loggedin',
1328 id: 15
1329 }, {
1330 name: 'logout',
1331 id: 16
1332 }, {
1333 name: 'loggedout',
1334 id: 17
1335 }, {
1336 name: 'patch',
1337 id: 18
1338 }, {
1339 name: 'pubsub',
1340 id: 19
1341 }, {
1342 name: 'blacklist',
1343 id: 20
1344 }, {
1345 name: 'goaway',
1346 id: 21
1347 }]
1348 }, {
1349 name: 'OpType',
1350 syntax: 'proto2',
1351 values: [{
1352 name: 'open',
1353 id: 1
1354 }, {
1355 name: 'add',
1356 id: 2
1357 }, {
1358 name: 'remove',
1359 id: 3
1360 }, {
1361 name: 'close',
1362 id: 4
1363 }, {
1364 name: 'opened',
1365 id: 5
1366 }, {
1367 name: 'closed',
1368 id: 6
1369 }, {
1370 name: 'query',
1371 id: 7
1372 }, {
1373 name: 'query_result',
1374 id: 8
1375 }, {
1376 name: 'conflict',
1377 id: 9
1378 }, {
1379 name: 'added',
1380 id: 10
1381 }, {
1382 name: 'removed',
1383 id: 11
1384 }, {
1385 name: 'refresh',
1386 id: 12
1387 }, {
1388 name: 'refreshed',
1389 id: 13
1390 }, {
1391 name: 'start',
1392 id: 30
1393 }, {
1394 name: 'started',
1395 id: 31
1396 }, {
1397 name: 'joined',
1398 id: 32
1399 }, {
1400 name: 'members_joined',
1401 id: 33
1402 }, {
1403 name: 'left',
1404 id: 39
1405 }, {
1406 name: 'members_left',
1407 id: 40
1408 }, {
1409 name: 'results',
1410 id: 42
1411 }, {
1412 name: 'count',
1413 id: 43
1414 }, {
1415 name: 'result',
1416 id: 44
1417 }, {
1418 name: 'update',
1419 id: 45
1420 }, {
1421 name: 'updated',
1422 id: 46
1423 }, {
1424 name: 'mute',
1425 id: 47
1426 }, {
1427 name: 'unmute',
1428 id: 48
1429 }, {
1430 name: 'status',
1431 id: 49
1432 }, {
1433 name: 'members',
1434 id: 50
1435 }, {
1436 name: 'max_read',
1437 id: 51
1438 }, {
1439 name: 'is_member',
1440 id: 52
1441 }, {
1442 name: 'member_info_update',
1443 id: 53
1444 }, {
1445 name: 'member_info_updated',
1446 id: 54
1447 }, {
1448 name: 'member_info_changed',
1449 id: 55
1450 }, {
1451 name: 'join',
1452 id: 80
1453 }, {
1454 name: 'invite',
1455 id: 81
1456 }, {
1457 name: 'leave',
1458 id: 82
1459 }, {
1460 name: 'kick',
1461 id: 83
1462 }, {
1463 name: 'reject',
1464 id: 84
1465 }, {
1466 name: 'invited',
1467 id: 85
1468 }, {
1469 name: 'kicked',
1470 id: 86
1471 }, {
1472 name: 'upload',
1473 id: 100
1474 }, {
1475 name: 'uploaded',
1476 id: 101
1477 }, {
1478 name: 'subscribe',
1479 id: 120
1480 }, {
1481 name: 'subscribed',
1482 id: 121
1483 }, {
1484 name: 'unsubscribe',
1485 id: 122
1486 }, {
1487 name: 'unsubscribed',
1488 id: 123
1489 }, {
1490 name: 'is_subscribed',
1491 id: 124
1492 }, {
1493 name: 'modify',
1494 id: 150
1495 }, {
1496 name: 'modified',
1497 id: 151
1498 }, {
1499 name: 'block',
1500 id: 170
1501 }, {
1502 name: 'unblock',
1503 id: 171
1504 }, {
1505 name: 'blocked',
1506 id: 172
1507 }, {
1508 name: 'unblocked',
1509 id: 173
1510 }, {
1511 name: 'members_blocked',
1512 id: 174
1513 }, {
1514 name: 'members_unblocked',
1515 id: 175
1516 }, {
1517 name: 'check_block',
1518 id: 176
1519 }, {
1520 name: 'check_result',
1521 id: 177
1522 }, {
1523 name: 'add_shutup',
1524 id: 180
1525 }, {
1526 name: 'remove_shutup',
1527 id: 181
1528 }, {
1529 name: 'query_shutup',
1530 id: 182
1531 }, {
1532 name: 'shutup_added',
1533 id: 183
1534 }, {
1535 name: 'shutup_removed',
1536 id: 184
1537 }, {
1538 name: 'shutup_result',
1539 id: 185
1540 }, {
1541 name: 'shutuped',
1542 id: 186
1543 }, {
1544 name: 'unshutuped',
1545 id: 187
1546 }, {
1547 name: 'members_shutuped',
1548 id: 188
1549 }, {
1550 name: 'members_unshutuped',
1551 id: 189
1552 }, {
1553 name: 'check_shutup',
1554 id: 190
1555 }]
1556 }, {
1557 name: 'StatusType',
1558 syntax: 'proto2',
1559 values: [{
1560 name: 'on',
1561 id: 1
1562 }, {
1563 name: 'off',
1564 id: 2
1565 }]
1566 }],
1567 isNamespace: true
1568}).build();
1569
1570var _messages$push_server = messageCompiled.push_server.messages2,
1571 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
1572 UnreadTuple = _messages$push_server.UnreadTuple,
1573 LogItem = _messages$push_server.LogItem,
1574 DataCommand = _messages$push_server.DataCommand,
1575 SessionCommand = _messages$push_server.SessionCommand,
1576 ErrorCommand = _messages$push_server.ErrorCommand,
1577 DirectCommand = _messages$push_server.DirectCommand,
1578 AckCommand = _messages$push_server.AckCommand,
1579 UnreadCommand = _messages$push_server.UnreadCommand,
1580 ConvCommand = _messages$push_server.ConvCommand,
1581 RoomCommand = _messages$push_server.RoomCommand,
1582 LogsCommand = _messages$push_server.LogsCommand,
1583 RcpCommand = _messages$push_server.RcpCommand,
1584 ReadTuple = _messages$push_server.ReadTuple,
1585 MaxReadTuple = _messages$push_server.MaxReadTuple,
1586 ReadCommand = _messages$push_server.ReadCommand,
1587 PresenceCommand = _messages$push_server.PresenceCommand,
1588 ReportCommand = _messages$push_server.ReportCommand,
1589 GenericCommand = _messages$push_server.GenericCommand,
1590 BlacklistCommand = _messages$push_server.BlacklistCommand,
1591 PatchCommand = _messages$push_server.PatchCommand,
1592 PatchItem = _messages$push_server.PatchItem,
1593 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
1594 CommandType = _messages$push_server.CommandType,
1595 OpType = _messages$push_server.OpType,
1596 StatusType = _messages$push_server.StatusType;
1597
1598var message = /*#__PURE__*/Object.freeze({
1599 __proto__: null,
1600 JsonObjectMessage: JsonObjectMessage,
1601 UnreadTuple: UnreadTuple,
1602 LogItem: LogItem,
1603 DataCommand: DataCommand,
1604 SessionCommand: SessionCommand,
1605 ErrorCommand: ErrorCommand,
1606 DirectCommand: DirectCommand,
1607 AckCommand: AckCommand,
1608 UnreadCommand: UnreadCommand,
1609 ConvCommand: ConvCommand,
1610 RoomCommand: RoomCommand,
1611 LogsCommand: LogsCommand,
1612 RcpCommand: RcpCommand,
1613 ReadTuple: ReadTuple,
1614 MaxReadTuple: MaxReadTuple,
1615 ReadCommand: ReadCommand,
1616 PresenceCommand: PresenceCommand,
1617 ReportCommand: ReportCommand,
1618 GenericCommand: GenericCommand,
1619 BlacklistCommand: BlacklistCommand,
1620 PatchCommand: PatchCommand,
1621 PatchItem: PatchItem,
1622 ConvMemberInfo: ConvMemberInfo,
1623 CommandType: CommandType,
1624 OpType: OpType,
1625 StatusType: StatusType
1626});
1627
1628var adapters = {};
1629
1630var getAdapter = function getAdapter(name) {
1631 var adapter = adapters[name];
1632
1633 if (adapter === undefined) {
1634 throw new Error("".concat(name, " adapter is not configured"));
1635 }
1636
1637 return adapter;
1638};
1639/**
1640 * 指定 Adapters
1641 * @function
1642 * @memberof module:leancloud-realtime
1643 * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
1644 */
1645
1646
1647var setAdapters = function setAdapters(newAdapters) {
1648 Object.assign(adapters, newAdapters);
1649};
1650
1651/* eslint-disable */
1652var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
1653
1654var EXPIRED = Symbol('expired');
1655var debug = d('LC:Expirable');
1656
1657var Expirable = /*#__PURE__*/function () {
1658 function Expirable(value, ttl) {
1659 this.originalValue = value;
1660
1661 if (typeof ttl === 'number') {
1662 this.expiredAt = Date.now() + ttl;
1663 }
1664 }
1665
1666 _createClass(Expirable, [{
1667 key: "value",
1668 get: function get() {
1669 var expired = this.expiredAt && this.expiredAt <= Date.now();
1670 if (expired) debug("expired: ".concat(this.originalValue));
1671 return expired ? EXPIRED : this.originalValue;
1672 }
1673 }]);
1674
1675 return Expirable;
1676}();
1677Expirable.EXPIRED = EXPIRED;
1678
1679var debug$1 = d('LC:Cache');
1680
1681var Cache = /*#__PURE__*/function () {
1682 function Cache() {
1683 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
1684 this.name = name;
1685 this._map = {};
1686 }
1687
1688 var _proto = Cache.prototype;
1689
1690 _proto.get = function get(key) {
1691 var cache = this._map[key];
1692
1693 if (cache) {
1694 var value = cache.value;
1695
1696 if (value !== Expirable.EXPIRED) {
1697 debug$1('[%s] hit: %s', this.name, key);
1698 return value;
1699 }
1700
1701 delete this._map[key];
1702 }
1703
1704 debug$1("[".concat(this.name, "] missed: ").concat(key));
1705 return null;
1706 };
1707
1708 _proto.set = function set(key, value, ttl) {
1709 debug$1('[%s] set: %s %d', this.name, key, ttl);
1710 this._map[key] = new Expirable(value, ttl);
1711 };
1712
1713 return Cache;
1714}();
1715
1716function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
1717
1718function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
1719/**
1720 * 调试日志控制器
1721 * @const
1722 * @memberof module:leancloud-realtime
1723 * @example
1724 * debug.enable(); // 启用调试日志
1725 * debug.disable(); // 关闭调试日志
1726 */
1727
1728var debug$2 = {
1729 enable: function enable() {
1730 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
1731 return d.enable(namespaces);
1732 },
1733 disable: d.disable
1734};
1735var tryAll = function tryAll(promiseConstructors) {
1736 var promise = new Promise(promiseConstructors[0]);
1737
1738 if (promiseConstructors.length === 1) {
1739 return promise;
1740 }
1741
1742 return promise["catch"](function () {
1743 return tryAll(promiseConstructors.slice(1));
1744 });
1745}; // eslint-disable-next-line no-sequences
1746
1747var tap = function tap(interceptor) {
1748 return function (value) {
1749 return interceptor(value), value;
1750 };
1751};
1752var finalize = function finalize(callback) {
1753 return [// eslint-disable-next-line no-sequences
1754 function (value) {
1755 return callback(), value;
1756 }, function (error) {
1757 callback();
1758 throw error;
1759 }];
1760};
1761/**
1762 * 将对象转换为 Date,支持 string、number、ProtoBuf Long 以及 LeanCloud 的 Date 类型,
1763 * 其他情况下(包括对象为 falsy)返回原值。
1764 * @private
1765 */
1766
1767var decodeDate = function decodeDate(date) {
1768 if (!date) return date;
1769
1770 if (typeof date === 'string' || typeof date === 'number') {
1771 return new Date(date);
1772 }
1773
1774 if (date.__type === 'Date' && date.iso) {
1775 return new Date(date.iso);
1776 } // Long
1777
1778
1779 if (typeof date.toNumber === 'function') {
1780 return new Date(date.toNumber());
1781 }
1782
1783 return date;
1784};
1785/**
1786 * 获取 Date 的毫秒数,如果不是一个 Date 返回 undefined。
1787 * @private
1788 */
1789
1790var getTime = function getTime(date) {
1791 return date && date.getTime ? date.getTime() : undefined;
1792};
1793/**
1794 * 解码对象中的 LeanCloud 数据结构。
1795 * 目前仅会处理 Date 类型。
1796 * @private
1797 */
1798
1799var decode = function decode(value) {
1800 if (!value) return value;
1801
1802 if (value.__type === 'Date' && value.iso) {
1803 return new Date(value.iso);
1804 }
1805
1806 if (Array.isArray(value)) {
1807 return value.map(decode);
1808 }
1809
1810 if (isPlainObject(value)) {
1811 return Object.keys(value).reduce(function (result, key) {
1812 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, decode(value[key])));
1813 }, {});
1814 }
1815
1816 return value;
1817};
1818/**
1819 * 将对象中的特殊类型编码为 LeanCloud 数据结构。
1820 * 目前仅会处理 Date 类型。
1821 * @private
1822 */
1823
1824var encode = function encode(value) {
1825 if (value instanceof Date) return {
1826 __type: 'Date',
1827 iso: value.toJSON()
1828 };
1829
1830 if (Array.isArray(value)) {
1831 return value.map(encode);
1832 }
1833
1834 if (isPlainObject(value)) {
1835 return Object.keys(value).reduce(function (result, key) {
1836 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, encode(value[key])));
1837 }, {});
1838 }
1839
1840 return value;
1841};
1842var keyRemap = function keyRemap(keymap, obj) {
1843 return Object.keys(obj).reduce(function (newObj, key) {
1844 var newKey = keymap[key] || key;
1845 return Object.assign(newObj, _defineProperty({}, newKey, obj[key]));
1846 }, {});
1847};
1848var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
1849/* eslint-disable no-proto */
1850
1851var getStaticProperty = function getStaticProperty(klass, property) {
1852 return klass[property] || (klass.__proto__ ? getStaticProperty(klass.__proto__, property) : undefined);
1853};
1854/* eslint-enable no-proto */
1855
1856var union = function union(a, b) {
1857 return Array.from(new Set([].concat(_toConsumableArray(a), _toConsumableArray(b))));
1858};
1859var difference = function difference(a, b) {
1860 return Array.from(function (bSet) {
1861 return new Set(a.filter(function (x) {
1862 return !bSet.has(x);
1863 }));
1864 }(new Set(b)));
1865};
1866var map = new WeakMap(); // protected property helper
1867
1868var internal = function internal(object) {
1869 if (!map.has(object)) {
1870 map.set(object, {});
1871 }
1872
1873 return map.get(object);
1874};
1875var compact = function compact(obj, filter) {
1876 if (!isPlainObject(obj)) return obj;
1877
1878 var object = _objectSpread({}, obj);
1879
1880 Object.keys(object).forEach(function (prop) {
1881 var value = object[prop];
1882
1883 if (value === filter) {
1884 delete object[prop];
1885 } else {
1886 object[prop] = compact(value, filter);
1887 }
1888 });
1889 return object;
1890}; // debug utility
1891
1892var removeNull = function removeNull(obj) {
1893 return compact(obj, null);
1894};
1895
1896var trim = function trim(message) {
1897 return removeNull(JSON.parse(JSON.stringify(message)));
1898};
1899var ensureArray = function ensureArray(target) {
1900 if (Array.isArray(target)) {
1901 return target;
1902 }
1903
1904 if (target === undefined || target === null) {
1905 return [];
1906 }
1907
1908 return [target];
1909};
1910var setValue = function setValue(target, key, value) {
1911 // '.' is not allowed in Class keys, escaping is not in concern now.
1912 var segs = key.split('.');
1913 var lastSeg = segs.pop();
1914 var currentTarget = target;
1915 segs.forEach(function (seg) {
1916 if (currentTarget[seg] === undefined) currentTarget[seg] = {};
1917 currentTarget = currentTarget[seg];
1918 });
1919 currentTarget[lastSeg] = value;
1920 return target;
1921};
1922var isWeapp = // eslint-disable-next-line no-undef
1923(typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
1924
1925var throttle = function throttle(wait) {
1926 return function (target, property, descriptor) {
1927 var callback = descriptor.value; // very naive, internal use only
1928
1929 if (callback.length) {
1930 throw new Error('throttled function should not accept any arguments');
1931 }
1932
1933 return _objectSpread(_objectSpread({}, descriptor), {}, {
1934 value: function value() {
1935 var _this = this;
1936
1937 var _internal = internal(this),
1938 throttleMeta = _internal.throttleMeta;
1939
1940 if (!throttleMeta) {
1941 throttleMeta = {};
1942 internal(this).throttleMeta = throttleMeta;
1943 }
1944
1945 var _throttleMeta = throttleMeta,
1946 propertyMeta = _throttleMeta[property];
1947
1948 if (!propertyMeta) {
1949 propertyMeta = {};
1950 throttleMeta[property] = propertyMeta;
1951 }
1952
1953 var _propertyMeta = propertyMeta,
1954 _propertyMeta$previou = _propertyMeta.previouseTimestamp,
1955 previouseTimestamp = _propertyMeta$previou === void 0 ? 0 : _propertyMeta$previou,
1956 timeout = _propertyMeta.timeout;
1957 var now = Date.now();
1958 var remainingTime = wait - (now - previouseTimestamp);
1959
1960 if (remainingTime <= 0) {
1961 throttleMeta[property].previouseTimestamp = now;
1962 callback.apply(this);
1963 } else if (!timeout) {
1964 propertyMeta.timeout = setTimeout(function () {
1965 propertyMeta.previouseTimestamp = Date.now();
1966 delete propertyMeta.timeout;
1967 callback.apply(_this);
1968 }, remainingTime);
1969 }
1970 }
1971 });
1972 };
1973};
1974var isCNApp = function isCNApp(appId) {
1975 return appId.slice(-9) !== '-MdYXbMMI';
1976};
1977var equalBuffer = function equalBuffer(buffer1, buffer2) {
1978 if (!buffer1 || !buffer2) return false;
1979 if (buffer1.byteLength !== buffer2.byteLength) return false;
1980 var a = new Uint8Array(buffer1);
1981 var b = new Uint8Array(buffer2);
1982 return !a.some(function (value, index) {
1983 return value !== b[index];
1984 });
1985};
1986
1987var _class;
1988
1989function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
1990
1991function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
1992var debug$3 = d('LC:WebSocketPlus');
1993var OPEN = 'open';
1994var DISCONNECT = 'disconnect';
1995var RECONNECT = 'reconnect';
1996var RETRY = 'retry';
1997var SCHEDULE = 'schedule';
1998var OFFLINE = 'offline';
1999var ONLINE = 'online';
2000var ERROR = 'error';
2001var MESSAGE = 'message';
2002var HEARTBEAT_TIME = 180000;
2003var TIMEOUT_TIME = 380000;
2004
2005var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
2006 return Math.min(1000 * Math.pow(2, attempt), 300000);
2007};
2008
2009var requireConnected = function requireConnected(target, name, descriptor) {
2010 return _objectSpread$1(_objectSpread$1({}, descriptor), {}, {
2011 value: function requireConnectedWrapper() {
2012 var _descriptor$value;
2013
2014 this.checkConnectionAvailability(name);
2015
2016 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
2017 args[_key] = arguments[_key];
2018 }
2019
2020 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
2021 }
2022 });
2023};
2024
2025var WebSocketPlus = (_class = /*#__PURE__*/function (_EventEmitter) {
2026 _inheritsLoose(WebSocketPlus, _EventEmitter);
2027
2028 _createClass(WebSocketPlus, [{
2029 key: "urls",
2030 get: function get() {
2031 return this._urls;
2032 },
2033 set: function set(urls) {
2034 this._urls = ensureArray(urls);
2035 }
2036 }]);
2037
2038 function WebSocketPlus(getUrls, protocol) {
2039 var _this;
2040
2041 _this = _EventEmitter.call(this) || this;
2042
2043 _this.init();
2044
2045 _this._protocol = protocol;
2046 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
2047 _this._urls = urls;
2048 return _this._open();
2049 }).then(function () {
2050 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
2051
2052 if (global$1.addEventListener) {
2053 _this.__pause = function () {
2054 if (_this.can('pause')) _this.pause();
2055 };
2056
2057 _this.__resume = function () {
2058 if (_this.can('resume')) _this.resume();
2059 };
2060
2061 global$1.addEventListener('offline', _this.__pause);
2062 global$1.addEventListener('online', _this.__resume);
2063 }
2064
2065 _this.open();
2066 })["catch"](_this["throw"].bind(_assertThisInitialized(_this)));
2067 return _this;
2068 }
2069
2070 var _proto = WebSocketPlus.prototype;
2071
2072 _proto._open = function _open() {
2073 var _this2 = this;
2074
2075 return this._createWs(this._urls, this._protocol).then(function (ws) {
2076 var _this2$_urls = _toArray(_this2._urls),
2077 first = _this2$_urls[0],
2078 reset = _this2$_urls.slice(1);
2079
2080 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
2081 return ws;
2082 });
2083 };
2084
2085 _proto._createWs = function _createWs(urls, protocol) {
2086 var _this3 = this;
2087
2088 return tryAll(urls.map(function (url) {
2089 return function (resolve, reject) {
2090 debug$3("connect [".concat(url, "] ").concat(protocol));
2091 var WebSocket = getAdapter('WebSocket');
2092 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
2093 ws.binaryType = _this3.binaryType || 'arraybuffer';
2094
2095 ws.onopen = function () {
2096 return resolve(ws);
2097 };
2098
2099 ws.onclose = function (error) {
2100 if (error instanceof Error) {
2101 return reject(error);
2102 } // in browser, error event is useless
2103
2104
2105 return reject(new Error("Failed to connect [".concat(url, "]")));
2106 };
2107
2108 ws.onerror = ws.onclose;
2109 };
2110 })).then(function (ws) {
2111 _this3._ws = ws;
2112 _this3._ws.onclose = _this3._handleClose.bind(_this3);
2113 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
2114 return ws;
2115 });
2116 };
2117
2118 _proto._destroyWs = function _destroyWs() {
2119 var ws = this._ws;
2120 if (!ws) return;
2121 ws.onopen = null;
2122 ws.onclose = null;
2123 ws.onerror = null;
2124 ws.onmessage = null;
2125 this._ws = null;
2126 ws.close();
2127 } // eslint-disable-next-line class-methods-use-this
2128 ;
2129
2130 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
2131 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
2132 payload[_key2 - 3] = arguments[_key2];
2133 }
2134
2135 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
2136 };
2137
2138 _proto.onopen = function onopen() {
2139 this.emit(OPEN);
2140 };
2141
2142 _proto.onconnected = function onconnected() {
2143 this._startConnectionKeeper();
2144 };
2145
2146 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
2147 this._stopConnectionKeeper();
2148
2149 this._destroyWs();
2150
2151 if (to === 'offline' || to === 'disconnected') {
2152 this.emit(DISCONNECT);
2153 }
2154 };
2155
2156 _proto.onpause = function onpause() {
2157 this.emit(OFFLINE);
2158 };
2159
2160 _proto.onbeforeresume = function onbeforeresume() {
2161 this.emit(ONLINE);
2162 };
2163
2164 _proto.onreconnect = function onreconnect() {
2165 this.emit(RECONNECT);
2166 };
2167
2168 _proto.ondisconnected = function ondisconnected(event, from, to) {
2169 var _this4 = this;
2170
2171 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
2172 var delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
2173 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
2174 this.emit(SCHEDULE, attempt, delay);
2175
2176 if (this.__scheduledRetry) {
2177 clearTimeout(this.__scheduledRetry);
2178 }
2179
2180 this.__scheduledRetry = setTimeout(function () {
2181 if (_this4.is('disconnected')) {
2182 _this4.retry(attempt);
2183 }
2184 }, delay);
2185 };
2186
2187 _proto.onretry = function onretry(event, from, to) {
2188 var _this5 = this;
2189
2190 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
2191 this.emit(RETRY, attempt);
2192
2193 this._open().then(function () {
2194 return _this5.can('reconnect') && _this5.reconnect();
2195 }, function () {
2196 return _this5.can('fail') && _this5.fail(attempt + 1);
2197 });
2198 };
2199
2200 _proto.onerror = function onerror(event, from, to, error) {
2201 this.emit(ERROR, error);
2202 };
2203
2204 _proto.onclose = function onclose() {
2205 if (global$1.removeEventListener) {
2206 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
2207 if (this.__resume) global$1.removeEventListener('online', this.__resume);
2208 }
2209 };
2210
2211 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
2212 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
2213
2214 if (!this.is('connected')) {
2215 var currentState = this.current;
2216 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
2217
2218 if (this.is('disconnected') || this.is('reconnecting')) {
2219 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
2220 }
2221
2222 throw new Error('Connection unavailable');
2223 }
2224 } // jsdoc-ignore-start
2225 ;
2226
2227 _proto. // jsdoc-ignore-end
2228 _ping = function _ping() {
2229 debug$3('ping');
2230
2231 try {
2232 this.ping();
2233 } catch (error) {
2234 console.warn("websocket ping error: ".concat(error.message));
2235 }
2236 };
2237
2238 _proto.ping = function ping() {
2239 if (this._ws.ping) {
2240 this._ws.ping();
2241 } else {
2242 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
2243 }
2244 };
2245
2246 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
2247 var _this6 = this;
2248
2249 debug$3('_postponeTimeoutTimer');
2250
2251 this._clearTimeoutTimers();
2252
2253 this._timeoutTimer = setTimeout(function () {
2254 debug$3('timeout');
2255
2256 _this6.disconnect();
2257 }, TIMEOUT_TIME);
2258 };
2259
2260 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
2261 if (this._timeoutTimer) {
2262 clearTimeout(this._timeoutTimer);
2263 }
2264 };
2265
2266 _proto._startConnectionKeeper = function _startConnectionKeeper() {
2267 debug$3('start connection keeper');
2268 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
2269 var addListener = this._ws.addListener || this._ws.addEventListener;
2270
2271 if (!addListener) {
2272 debug$3('connection keeper disabled due to the lack of #addEventListener.');
2273 return;
2274 }
2275
2276 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
2277 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
2278
2279 this._postponeTimeoutTimer();
2280 };
2281
2282 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
2283 debug$3('stop connection keeper'); // websockets/ws#489
2284
2285 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
2286
2287 if (removeListener) {
2288 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
2289 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
2290
2291 this._clearTimeoutTimers();
2292 }
2293
2294 if (this._heartbeatTimer) {
2295 clearInterval(this._heartbeatTimer);
2296 }
2297 };
2298
2299 _proto._handleClose = function _handleClose(event) {
2300 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
2301
2302 if (this.isFinished()) return;
2303 this.handleClose(event);
2304 };
2305
2306 _proto.handleClose = function handleClose() {
2307 // reconnect
2308 this.disconnect();
2309 } // jsdoc-ignore-start
2310 ;
2311
2312 _proto. // jsdoc-ignore-end
2313 send = function send(data) {
2314 debug$3('send', data);
2315
2316 this._ws.send(data);
2317 };
2318
2319 _proto._handleMessage = function _handleMessage(event) {
2320 debug$3('message', event.data);
2321 this.handleMessage(event.data);
2322 };
2323
2324 _proto.handleMessage = function handleMessage(message) {
2325 this.emit(MESSAGE, message);
2326 };
2327
2328 return WebSocketPlus;
2329}(EventEmitter), (_applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "_ping"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "send"), _class.prototype)), _class);
2330StateMachine.create({
2331 target: WebSocketPlus.prototype,
2332 initial: {
2333 state: 'initialized',
2334 event: 'init',
2335 defer: true
2336 },
2337 terminal: 'closed',
2338 events: [{
2339 name: 'open',
2340 from: 'initialized',
2341 to: 'connected'
2342 }, {
2343 name: 'disconnect',
2344 from: 'connected',
2345 to: 'disconnected'
2346 }, {
2347 name: 'retry',
2348 from: 'disconnected',
2349 to: 'reconnecting'
2350 }, {
2351 name: 'fail',
2352 from: 'reconnecting',
2353 to: 'disconnected'
2354 }, {
2355 name: 'reconnect',
2356 from: 'reconnecting',
2357 to: 'connected'
2358 }, {
2359 name: 'pause',
2360 from: ['connected', 'disconnected', 'reconnecting'],
2361 to: 'offline'
2362 }, {}, {
2363 name: 'resume',
2364 from: 'offline',
2365 to: 'disconnected'
2366 }, {
2367 name: 'close',
2368 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
2369 to: 'closed'
2370 }, {
2371 name: 'throw',
2372 from: '*',
2373 to: 'error'
2374 }]
2375});
2376
2377var error = Object.freeze({
2378 1000: {
2379 name: 'CLOSE_NORMAL'
2380 },
2381 1006: {
2382 name: 'CLOSE_ABNORMAL'
2383 },
2384 4100: {
2385 name: 'APP_NOT_AVAILABLE',
2386 message: 'App not exists or realtime message service is disabled.'
2387 },
2388 4102: {
2389 name: 'SIGNATURE_FAILED',
2390 message: 'Login signature mismatch.'
2391 },
2392 4103: {
2393 name: 'INVALID_LOGIN',
2394 message: 'Malformed clientId.'
2395 },
2396 4105: {
2397 name: 'SESSION_REQUIRED',
2398 message: 'Message sent before session opened.'
2399 },
2400 4107: {
2401 name: 'READ_TIMEOUT'
2402 },
2403 4108: {
2404 name: 'LOGIN_TIMEOUT'
2405 },
2406 4109: {
2407 name: 'FRAME_TOO_LONG'
2408 },
2409 4110: {
2410 name: 'INVALID_ORIGIN',
2411 message: 'Access denied by domain whitelist.'
2412 },
2413 4111: {
2414 name: 'SESSION_CONFLICT'
2415 },
2416 4112: {
2417 name: 'SESSION_TOKEN_EXPIRED'
2418 },
2419 4113: {
2420 name: 'APP_QUOTA_EXCEEDED',
2421 message: 'The daily active users limit exceeded.'
2422 },
2423 4116: {
2424 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
2425 message: 'Command sent too fast.'
2426 },
2427 4200: {
2428 name: 'INTERNAL_ERROR',
2429 message: 'Internal error, please contact LeanCloud for support.'
2430 },
2431 4301: {
2432 name: 'CONVERSATION_API_FAILED',
2433 message: 'Upstream Conversatoin API failed, see error.detail for details.'
2434 },
2435 4302: {
2436 name: 'CONVERSATION_SIGNATURE_FAILED',
2437 message: 'Conversation action signature mismatch.'
2438 },
2439 4303: {
2440 name: 'CONVERSATION_NOT_FOUND'
2441 },
2442 4304: {
2443 name: 'CONVERSATION_FULL'
2444 },
2445 4305: {
2446 name: 'CONVERSATION_REJECTED_BY_APP',
2447 message: 'Conversation action rejected by hook.'
2448 },
2449 4306: {
2450 name: 'CONVERSATION_UPDATE_FAILED'
2451 },
2452 4307: {
2453 name: 'CONVERSATION_READ_ONLY'
2454 },
2455 4308: {
2456 name: 'CONVERSATION_NOT_ALLOWED'
2457 },
2458 4309: {
2459 name: 'CONVERSATION_UPDATE_REJECTED',
2460 message: 'Conversation update rejected because the client is not a member.'
2461 },
2462 4310: {
2463 name: 'CONVERSATION_QUERY_FAILED',
2464 message: 'Conversation query failed because it is too expansive.'
2465 },
2466 4311: {
2467 name: 'CONVERSATION_LOG_FAILED'
2468 },
2469 4312: {
2470 name: 'CONVERSATION_LOG_REJECTED',
2471 message: 'Message query rejected because the client is not a member of the conversation.'
2472 },
2473 4313: {
2474 name: 'SYSTEM_CONVERSATION_REQUIRED'
2475 },
2476 4314: {
2477 name: 'NORMAL_CONVERSATION_REQUIRED'
2478 },
2479 4315: {
2480 name: 'CONVERSATION_BLACKLISTED',
2481 message: 'Blacklisted in the conversation.'
2482 },
2483 4316: {
2484 name: 'TRANSIENT_CONVERSATION_REQUIRED'
2485 },
2486 4317: {
2487 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
2488 },
2489 4318: {
2490 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
2491 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
2492 },
2493 4323: {
2494 name: 'TEMPORARY_CONVERSATION_EXPIRED',
2495 message: 'Temporary conversation expired or does not exist.'
2496 },
2497 4401: {
2498 name: 'INVALID_MESSAGING_TARGET',
2499 message: 'Conversation does not exist or client is not a member.'
2500 },
2501 4402: {
2502 name: 'MESSAGE_REJECTED_BY_APP',
2503 message: 'Message rejected by hook.'
2504 },
2505 4403: {
2506 name: 'MESSAGE_OWNERSHIP_REQUIRED'
2507 },
2508 4404: {
2509 name: 'MESSAGE_NOT_FOUND'
2510 },
2511 4405: {
2512 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
2513 message: 'Message update rejected by hook.'
2514 },
2515 4406: {
2516 name: 'MESSAGE_EDIT_DISABLED'
2517 },
2518 4407: {
2519 name: 'MESSAGE_RECALL_DISABLED'
2520 },
2521 5130: {
2522 name: 'OWNER_PROMOTION_NOT_ALLOWED',
2523 message: "Updating a member's role to owner is not allowed."
2524 }
2525});
2526var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
2527 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
2528}, {}));
2529var createError = function createError(_ref) {
2530 var code = _ref.code,
2531 reason = _ref.reason,
2532 appCode = _ref.appCode,
2533 detail = _ref.detail,
2534 errorMessage = _ref.error;
2535 var message = reason || detail || errorMessage;
2536 var name = reason;
2537
2538 if (!message && error[code]) {
2539 name = error[code].name;
2540 message = error[code].message || name;
2541 }
2542
2543 if (!message) {
2544 message = "Unknow Error: ".concat(code);
2545 }
2546
2547 var err = new Error(message);
2548 return Object.assign(err, {
2549 code: code,
2550 appCode: appCode,
2551 detail: detail,
2552 name: name
2553 });
2554};
2555
2556var debug$4 = d('LC:Connection');
2557var COMMAND_TIMEOUT = 20000;
2558var EXPIRE = Symbol('expire');
2559
2560var isIdempotentCommand = function isIdempotentCommand(command) {
2561 return !(command.cmd === CommandType.direct || command.cmd === CommandType.session && command.op === OpType.open || command.cmd === CommandType.conv && (command.op === OpType.start || command.op === OpType.update || command.op === OpType.members));
2562};
2563
2564var Connection = /*#__PURE__*/function (_WebSocketPlus) {
2565 _inheritsLoose(Connection, _WebSocketPlus);
2566
2567 function Connection(getUrl, _ref) {
2568 var _this;
2569
2570 var format = _ref.format,
2571 version = _ref.version;
2572 debug$4('initializing Connection');
2573 var protocolString = "lc.".concat(format, ".").concat(version);
2574 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
2575 _this._protocolFormat = format;
2576 _this._commands = {};
2577 _this._serialId = 0;
2578 return _this;
2579 }
2580
2581 var _proto = Connection.prototype;
2582
2583 _proto.send = /*#__PURE__*/function () {
2584 var _send = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(command) {
2585 var _this2 = this;
2586
2587 var waitingForRespond,
2588 buffer,
2589 serialId,
2590 duplicatedCommand,
2591 message,
2592 promise,
2593 _args = arguments;
2594 return _regeneratorRuntime.wrap(function _callee$(_context) {
2595 while (1) {
2596 switch (_context.prev = _context.next) {
2597 case 0:
2598 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
2599
2600 if (!waitingForRespond) {
2601 _context.next = 11;
2602 break;
2603 }
2604
2605 if (!isIdempotentCommand(command)) {
2606 _context.next = 8;
2607 break;
2608 }
2609
2610 buffer = command.toArrayBuffer();
2611 duplicatedCommand = values(this._commands).find(function (_ref2) {
2612 var targetBuffer = _ref2.buffer,
2613 targetCommand = _ref2.command;
2614 return targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer);
2615 });
2616
2617 if (!duplicatedCommand) {
2618 _context.next = 8;
2619 break;
2620 }
2621
2622 console.warn("Duplicated command [cmd:".concat(command.cmd, " op:").concat(command.op, "] is throttled."));
2623 return _context.abrupt("return", duplicatedCommand.promise);
2624
2625 case 8:
2626 this._serialId += 1;
2627 serialId = this._serialId;
2628 command.i = serialId; // eslint-disable-line no-param-reassign
2629
2630 case 11:
2631 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
2632
2633 if (this._protocolFormat === 'proto2base64') {
2634 message = command.toBase64();
2635 } else if (command.toArrayBuffer) {
2636 message = command.toArrayBuffer();
2637 }
2638
2639 if (message) {
2640 _context.next = 15;
2641 break;
2642 }
2643
2644 throw new TypeError("".concat(command, " is not a GenericCommand"));
2645
2646 case 15:
2647 _WebSocketPlus.prototype.send.call(this, message);
2648
2649 if (waitingForRespond) {
2650 _context.next = 18;
2651 break;
2652 }
2653
2654 return _context.abrupt("return", undefined);
2655
2656 case 18:
2657 promise = new Promise(function (resolve, reject) {
2658 _this2._commands[serialId] = {
2659 command: command,
2660 buffer: buffer,
2661 resolve: resolve,
2662 reject: reject,
2663 timeout: setTimeout(function () {
2664 if (_this2._commands[serialId]) {
2665 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
2666 reject(createError({
2667 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
2668 name: 'COMMAND_TIMEOUT'
2669 }));
2670 delete _this2._commands[serialId];
2671 }
2672 }, COMMAND_TIMEOUT)
2673 };
2674 });
2675 this._commands[serialId].promise = promise;
2676 return _context.abrupt("return", promise);
2677
2678 case 21:
2679 case "end":
2680 return _context.stop();
2681 }
2682 }
2683 }, _callee, this);
2684 }));
2685
2686 function send(_x) {
2687 return _send.apply(this, arguments);
2688 }
2689
2690 return send;
2691 }();
2692
2693 _proto.handleMessage = function handleMessage(msg) {
2694 var message;
2695
2696 try {
2697 message = GenericCommand.decode(msg);
2698 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
2699 } catch (e) {
2700 console.warn('Decode message failed:', e.message, msg);
2701 return;
2702 }
2703
2704 var serialId = message.i;
2705
2706 if (serialId) {
2707 if (this._commands[serialId]) {
2708 clearTimeout(this._commands[serialId].timeout);
2709
2710 if (message.cmd === CommandType.error) {
2711 this._commands[serialId].reject(createError(message.errorMessage));
2712 } else {
2713 this._commands[serialId].resolve(message);
2714 }
2715
2716 delete this._commands[serialId];
2717 } else {
2718 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
2719 }
2720 } else {
2721 switch (message.cmd) {
2722 case CommandType.error:
2723 {
2724 this.emit(ERROR, createError(message.errorMessage));
2725 return;
2726 }
2727
2728 case CommandType.goaway:
2729 {
2730 this.emit(EXPIRE);
2731 return;
2732 }
2733
2734 default:
2735 {
2736 this.emit(MESSAGE, message);
2737 }
2738 }
2739 }
2740 };
2741
2742 _proto.ping = function ping() {
2743 return this.send(new GenericCommand({
2744 cmd: CommandType.echo
2745 }))["catch"](function (error) {
2746 return debug$4('ping failed:', error);
2747 });
2748 };
2749
2750 return Connection;
2751}(WebSocketPlus);
2752
2753var debug$5 = d('LC:request');
2754var request = (function (_ref) {
2755 var _ref$method = _ref.method,
2756 method = _ref$method === void 0 ? 'GET' : _ref$method,
2757 _url = _ref.url,
2758 query = _ref.query,
2759 headers = _ref.headers,
2760 data = _ref.data,
2761 time = _ref.timeout;
2762 var url = _url;
2763
2764 if (query) {
2765 var queryString = Object.keys(query).map(function (key) {
2766 var value = query[key];
2767 if (value === undefined) return undefined;
2768 var v = isPlainObject(value) ? JSON.stringify(value) : value;
2769 return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(v));
2770 }).filter(function (qs) {
2771 return qs;
2772 }).join('&');
2773 url = "".concat(url, "?").concat(queryString);
2774 }
2775
2776 debug$5('Req: %O %O %O', method, url, {
2777 headers: headers,
2778 data: data
2779 });
2780 var request = getAdapter('request');
2781 var promise = request(url, {
2782 method: method,
2783 headers: headers,
2784 data: data
2785 }).then(function (response) {
2786 if (response.ok === false) {
2787 var error = createError(response.data);
2788 error.response = response;
2789 throw error;
2790 }
2791
2792 debug$5('Res: %O %O %O', url, response.status, response.data);
2793 return response.data;
2794 })["catch"](function (error) {
2795 if (error.response) {
2796 debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
2797 }
2798
2799 throw error;
2800 });
2801 return time ? promiseTimeout.timeout(promise, time) : promise;
2802});
2803
2804var checkType = function checkType(middleware) {
2805 return function (param) {
2806 var constructor = param.constructor;
2807 return Promise.resolve(param).then(middleware).then(tap(function (result) {
2808 if (result === undefined || result === null) {
2809 // eslint-disable-next-line max-len
2810 return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns ").concat(result, " while a ").concat(param.constructor.name, " expected."));
2811 }
2812
2813 if (!(result instanceof constructor)) {
2814 // eslint-disable-next-line max-len
2815 return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns a ").concat(result.constructor.name, " while a ").concat(param.constructor.name, " expected."));
2816 }
2817
2818 return 0;
2819 }));
2820 };
2821};
2822
2823var applyDecorators = function applyDecorators(decorators, target) {
2824 if (decorators) {
2825 decorators.forEach(function (decorator) {
2826 try {
2827 decorator(target);
2828 } catch (error) {
2829 if (decorator._pluginName) {
2830 error.message += "[".concat(decorator._pluginName, "]");
2831 }
2832
2833 throw error;
2834 }
2835 });
2836 }
2837};
2838var applyMiddlewares = function applyMiddlewares(middlewares) {
2839 return function (target) {
2840 return ensureArray(middlewares).reduce(function (previousPromise, middleware) {
2841 return previousPromise.then(checkType(middleware))["catch"](function (error) {
2842 if (middleware._pluginName) {
2843 // eslint-disable-next-line no-param-reassign
2844 error.message += "[".concat(middleware._pluginName, "]");
2845 }
2846
2847 throw error;
2848 });
2849 }, Promise.resolve(target));
2850 };
2851};
2852var applyDispatcher = function applyDispatcher(dispatchers, payload) {
2853 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
2854 return resultPromise.then(function (shouldDispatch) {
2855 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
2856 })["catch"](function (error) {
2857 if (dispatcher._pluginName) {
2858 // eslint-disable-next-line no-param-reassign
2859 error.message += "[".concat(dispatcher._pluginName, "]");
2860 }
2861
2862 throw error;
2863 });
2864 }, Promise.resolve(true));
2865};
2866
2867var version = "5.0.0-rc.7";
2868
2869function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
2870
2871function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
2872var debug$6 = d('LC:Realtime');
2873var routerCache = new Cache('push-router');
2874var initializedApp = {};
2875
2876var Realtime = /*#__PURE__*/function (_EventEmitter) {
2877 _inheritsLoose(Realtime, _EventEmitter);
2878
2879 /**
2880 * @extends EventEmitter
2881 * @param {Object} options
2882 * @param {String} options.appId
2883 * @param {String} options.appKey (since 4.0.0)
2884 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
2885 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
2886 * 适用于 WebSocket 实现不支持二进制数据格式的情况
2887 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
2888 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
2889 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
2890 */
2891 function Realtime(_ref) {
2892 var _this2;
2893
2894 var plugins = _ref.plugins,
2895 options = _objectWithoutProperties(_ref, ["plugins"]);
2896
2897 debug$6('initializing Realtime %s %O', version, options);
2898 _this2 = _EventEmitter.call(this) || this;
2899 var appId = options.appId;
2900
2901 if (typeof appId !== 'string') {
2902 throw new TypeError("appId [".concat(appId, "] is not a string"));
2903 }
2904
2905 if (initializedApp[appId]) {
2906 throw new Error("App [".concat(appId, "] is already initialized."));
2907 }
2908
2909 initializedApp[appId] = true;
2910
2911 if (typeof options.appKey !== 'string') {
2912 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
2913 }
2914
2915 if (isCNApp(appId)) {
2916 if (!options.server) {
2917 throw new TypeError("server option is required for apps from CN region");
2918 }
2919 }
2920
2921 _this2._options = _objectSpread$2({
2922 appId: undefined,
2923 appKey: undefined,
2924 noBinary: false,
2925 ssl: true,
2926 RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined
2927 }, options);
2928 _this2._cache = new Cache('endpoints');
2929
2930 var _this = internal(_assertThisInitialized(_this2));
2931
2932 _this.clients = new Set();
2933 _this.pendingClients = new Set();
2934 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
2935 debug$6('Using plugins %o', mergedPlugins.map(function (plugin) {
2936 return plugin.name;
2937 }));
2938 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
2939 Object.keys(plugin).forEach(function (hook) {
2940 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
2941 if (plugin.name) {
2942 ensureArray(plugin[hook]).forEach(function (value) {
2943 // eslint-disable-next-line no-param-reassign
2944 value._pluginName = plugin.name;
2945 });
2946 } // eslint-disable-next-line no-param-reassign
2947
2948
2949 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
2950 }
2951 });
2952 return result;
2953 }, {}); // onRealtimeCreate hook
2954
2955 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
2956 return _this2;
2957 }
2958
2959 var _proto = Realtime.prototype;
2960
2961 _proto._request = /*#__PURE__*/function () {
2962 var _request2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2) {
2963 var method, _url, _ref2$version, version, path, query, headers, data, url, _this$_options, appId, server, _yield$this$construct, api;
2964
2965 return _regeneratorRuntime.wrap(function _callee$(_context) {
2966 while (1) {
2967 switch (_context.prev = _context.next) {
2968 case 0:
2969 method = _ref2.method, _url = _ref2.url, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, data = _ref2.data;
2970 url = _url;
2971
2972 if (url) {
2973 _context.next = 9;
2974 break;
2975 }
2976
2977 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
2978 _context.next = 6;
2979 return this.constructor._getServerUrls({
2980 appId: appId,
2981 server: server
2982 });
2983
2984 case 6:
2985 _yield$this$construct = _context.sent;
2986 api = _yield$this$construct.api;
2987 url = "".concat(api, "/").concat(version).concat(path);
2988
2989 case 9:
2990 return _context.abrupt("return", request({
2991 url: url,
2992 method: method,
2993 query: query,
2994 headers: _objectSpread$2({
2995 'X-LC-Id': this._options.appId,
2996 'X-LC-Key': this._options.appKey
2997 }, headers),
2998 data: data
2999 }));
3000
3001 case 10:
3002 case "end":
3003 return _context.stop();
3004 }
3005 }
3006 }, _callee, this);
3007 }));
3008
3009 function _request(_x) {
3010 return _request2.apply(this, arguments);
3011 }
3012
3013 return _request;
3014 }();
3015
3016 _proto._open = function _open() {
3017 var _this3 = this;
3018
3019 if (this._openPromise) return this._openPromise;
3020 var format = 'protobuf2';
3021
3022 if (this._options.noBinary) {
3023 // 不发送 binary data,fallback to base64 string
3024 format = 'proto2base64';
3025 }
3026
3027 var version = 3;
3028 var protocol = {
3029 format: format,
3030 version: version
3031 };
3032 this._openPromise = new Promise(function (resolve, reject) {
3033 debug$6('No connection established, create a new one.');
3034 var connection = new Connection(function () {
3035 return _this3._getRTMServers(_this3._options);
3036 }, protocol);
3037 connection.on(OPEN, function () {
3038 return resolve(connection);
3039 }).on(ERROR, function (error) {
3040 delete _this3._openPromise;
3041 reject(error);
3042 }).on(EXPIRE, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
3043 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
3044 while (1) {
3045 switch (_context2.prev = _context2.next) {
3046 case 0:
3047 debug$6('Connection expired. Refresh endpoints.');
3048
3049 _this3._cache.set('endpoints', null, 0);
3050
3051 _context2.next = 4;
3052 return _this3._getRTMServers(_this3._options);
3053
3054 case 4:
3055 connection.urls = _context2.sent;
3056 connection.disconnect();
3057
3058 case 6:
3059 case "end":
3060 return _context2.stop();
3061 }
3062 }
3063 }, _callee2);
3064 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
3065 /**
3066 * 连接断开。
3067 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
3068 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
3069 * @event Realtime#DISCONNECT
3070 */
3071
3072 /**
3073 * 计划在一段时间后尝试重新连接
3074 * @event Realtime#SCHEDULE
3075 * @param {Number} attempt 尝试重连的次数
3076 * @param {Number} delay 延迟的毫秒数
3077 */
3078
3079 /**
3080 * 正在尝试重新连接
3081 * @event Realtime#RETRY
3082 * @param {Number} attempt 尝试重连的次数
3083 */
3084
3085 /**
3086 * 连接恢复正常。
3087 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
3088 * @event Realtime#RECONNECT
3089 */
3090
3091 /**
3092 * 客户端连接断开
3093 * @event IMClient#DISCONNECT
3094 * @see Realtime#event:DISCONNECT
3095 * @since 3.2.0
3096 */
3097
3098 /**
3099 * 计划在一段时间后尝试重新连接
3100 * @event IMClient#SCHEDULE
3101 * @param {Number} attempt 尝试重连的次数
3102 * @param {Number} delay 延迟的毫秒数
3103 * @since 3.2.0
3104 */
3105
3106 /**
3107 * 正在尝试重新连接
3108 * @event IMClient#RETRY
3109 * @param {Number} attempt 尝试重连的次数
3110 * @since 3.2.0
3111 */
3112
3113 /**
3114 * 客户端进入离线状态。
3115 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
3116 * @event Realtime#OFFLINE
3117 * @since 3.4.0
3118 */
3119
3120 /**
3121 * 客户端恢复在线状态
3122 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
3123 * @event Realtime#ONLINE
3124 * @since 3.4.0
3125 */
3126
3127 /**
3128 * 进入离线状态。
3129 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
3130 * @event IMClient#OFFLINE
3131 * @since 3.4.0
3132 */
3133
3134 /**
3135 * 恢复在线状态
3136 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
3137 * @event IMClient#ONLINE
3138 * @since 3.4.0
3139 */
3140 // event proxy
3141
3142 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
3143 return connection.on(event, function () {
3144 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
3145 payload[_key] = arguments[_key];
3146 }
3147
3148 debug$6("".concat(event, " event emitted. %o"), payload);
3149
3150 _this3.emit.apply(_this3, [event].concat(payload));
3151
3152 if (event !== RECONNECT) {
3153 internal(_this3).clients.forEach(function (client) {
3154 client.emit.apply(client, [event].concat(payload));
3155 });
3156 }
3157 });
3158 }); // override handleClose
3159
3160 connection.handleClose = function handleClose(event) {
3161 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
3162 return errorCode === event.code;
3163 });
3164
3165 if (isFatal) {
3166 // in these cases, SDK should throw.
3167 this["throw"](createError(event));
3168 } else {
3169 // reconnect
3170 this.disconnect();
3171 }
3172 };
3173
3174 internal(_this3).connection = connection;
3175 });
3176 return this._openPromise;
3177 };
3178
3179 _proto._getRTMServers = /*#__PURE__*/function () {
3180 var _getRTMServers2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(options) {
3181 var info, cachedEndPoints, _info, server, secondary, ttl;
3182
3183 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
3184 while (1) {
3185 switch (_context3.prev = _context3.next) {
3186 case 0:
3187 if (!options.RTMServers) {
3188 _context3.next = 2;
3189 break;
3190 }
3191
3192 return _context3.abrupt("return", shuffle(ensureArray(options.RTMServers)));
3193
3194 case 2:
3195 cachedEndPoints = this._cache.get('endpoints');
3196
3197 if (!cachedEndPoints) {
3198 _context3.next = 7;
3199 break;
3200 }
3201
3202 info = cachedEndPoints;
3203 _context3.next = 14;
3204 break;
3205
3206 case 7:
3207 _context3.next = 9;
3208 return this.constructor._fetchRTMServers(options);
3209
3210 case 9:
3211 info = _context3.sent;
3212 _info = info, server = _info.server, secondary = _info.secondary, ttl = _info.ttl;
3213
3214 if (!(typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number')) {
3215 _context3.next = 13;
3216 break;
3217 }
3218
3219 throw new Error("malformed RTM route response: ".concat(JSON.stringify(info)));
3220
3221 case 13:
3222 this._cache.set('endpoints', info, info.ttl * 1000);
3223
3224 case 14:
3225 debug$6('endpoint info: %O', info);
3226 return _context3.abrupt("return", [info.server, info.secondary]);
3227
3228 case 16:
3229 case "end":
3230 return _context3.stop();
3231 }
3232 }
3233 }, _callee3, this);
3234 }));
3235
3236 function _getRTMServers(_x2) {
3237 return _getRTMServers2.apply(this, arguments);
3238 }
3239
3240 return _getRTMServers;
3241 }();
3242
3243 Realtime._getServerUrls = /*#__PURE__*/function () {
3244 var _getServerUrls2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(_ref4) {
3245 var appId, server, cachedRouter, defaultProtocol;
3246 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
3247 while (1) {
3248 switch (_context4.prev = _context4.next) {
3249 case 0:
3250 appId = _ref4.appId, server = _ref4.server;
3251 debug$6('fetch server urls');
3252
3253 if (!server) {
3254 _context4.next = 6;
3255 break;
3256 }
3257
3258 if (!(typeof server !== 'string')) {
3259 _context4.next = 5;
3260 break;
3261 }
3262
3263 return _context4.abrupt("return", server);
3264
3265 case 5:
3266 return _context4.abrupt("return", {
3267 RTMRouter: server,
3268 api: server
3269 });
3270
3271 case 6:
3272 cachedRouter = routerCache.get(appId);
3273
3274 if (!cachedRouter) {
3275 _context4.next = 9;
3276 break;
3277 }
3278
3279 return _context4.abrupt("return", cachedRouter);
3280
3281 case 9:
3282 defaultProtocol = 'https://';
3283 return _context4.abrupt("return", request({
3284 url: 'https://app-router.com/2/route',
3285 query: {
3286 appId: appId
3287 },
3288 timeout: 20000
3289 }).then(tap(debug$6)).then(function (_ref5) {
3290 var RTMRouterServer = _ref5.rtm_router_server,
3291 APIServer = _ref5.api_server,
3292 _ref5$ttl = _ref5.ttl,
3293 ttl = _ref5$ttl === void 0 ? 3600 : _ref5$ttl;
3294
3295 if (!RTMRouterServer) {
3296 throw new Error('rtm router not exists');
3297 }
3298
3299 var serverUrls = {
3300 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
3301 api: "".concat(defaultProtocol).concat(APIServer)
3302 };
3303 routerCache.set(appId, serverUrls, ttl * 1000);
3304 return serverUrls;
3305 })["catch"](function () {
3306 var id = appId.slice(0, 8).toLowerCase();
3307 var domain = 'lncldglobal.com';
3308 return {
3309 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
3310 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
3311 };
3312 }));
3313
3314 case 11:
3315 case "end":
3316 return _context4.stop();
3317 }
3318 }
3319 }, _callee4);
3320 }));
3321
3322 function _getServerUrls(_x3) {
3323 return _getServerUrls2.apply(this, arguments);
3324 }
3325
3326 return _getServerUrls;
3327 }();
3328
3329 Realtime._fetchRTMServers = function _fetchRTMServers(_ref6) {
3330 var appId = _ref6.appId,
3331 ssl = _ref6.ssl,
3332 server = _ref6.server,
3333 RTMServerName = _ref6.RTMServerName;
3334 debug$6('fetch endpoint info');
3335 return this._getServerUrls({
3336 appId: appId,
3337 server: server
3338 }).then(tap(debug$6)).then(function (_ref7) {
3339 var RTMRouter = _ref7.RTMRouter;
3340 return request({
3341 url: "".concat(RTMRouter, "/v1/route"),
3342 query: {
3343 appId: appId,
3344 secure: ssl,
3345 features: isWeapp ? 'wechat' : undefined,
3346 server: RTMServerName,
3347 _t: Date.now()
3348 },
3349 timeout: 20000
3350 }).then(tap(debug$6));
3351 });
3352 };
3353
3354 _proto._close = function _close() {
3355 if (this._openPromise) {
3356 this._openPromise.then(function (connection) {
3357 return connection.close();
3358 });
3359 }
3360
3361 delete this._openPromise;
3362 }
3363 /**
3364 * 手动进行重连。
3365 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
3366 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
3367 */
3368 ;
3369
3370 _proto.retry = function retry() {
3371 var _internal = internal(this),
3372 connection = _internal.connection;
3373
3374 if (!connection) {
3375 throw new Error('no connection established');
3376 }
3377
3378 if (connection.cannot('retry')) {
3379 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
3380 }
3381
3382 return connection.retry();
3383 }
3384 /**
3385 * 暂停,使 SDK 进入离线状态。
3386 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
3387 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
3388 *
3389 * @since 3.4.0
3390 * @see Realtime#event:OFFLINE
3391 */
3392 ;
3393
3394 _proto.pause = function pause() {
3395 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
3396 // 因此不像 retry,这个方法应该尽可能 loose
3397 var _internal2 = internal(this),
3398 connection = _internal2.connection;
3399
3400 if (!connection) return;
3401 if (connection.can('pause')) connection.pause();
3402 }
3403 /**
3404 * 恢复在线状态。
3405 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
3406 *
3407 * @since 3.4.0
3408 * @see Realtime#event:ONLINE
3409 */
3410 ;
3411
3412 _proto.resume = function resume() {
3413 // 与 pause 一样,这个方法应该尽可能 loose
3414 var _internal3 = internal(this),
3415 connection = _internal3.connection;
3416
3417 if (!connection) return;
3418 if (connection.can('resume')) connection.resume();
3419 };
3420
3421 _proto._registerPending = function _registerPending(value) {
3422 internal(this).pendingClients.add(value);
3423 };
3424
3425 _proto._deregisterPending = function _deregisterPending(client) {
3426 internal(this).pendingClients["delete"](client);
3427 };
3428
3429 _proto._register = function _register(client) {
3430 internal(this).clients.add(client);
3431 };
3432
3433 _proto._deregister = function _deregister(client) {
3434 var _this = internal(this);
3435
3436 _this.clients["delete"](client);
3437
3438 if (_this.clients.size + _this.pendingClients.size === 0) {
3439 this._close();
3440 }
3441 };
3442
3443 _proto._dispatchCommand = function _dispatchCommand(command) {
3444 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
3445 // no plugin handled this command
3446 if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
3447 return false;
3448 });
3449 };
3450
3451 return Realtime;
3452}(EventEmitter); // For test purpose only
3453
3454var polyfilledPromise = Promise;
3455
3456// IMClient
3457var UNREAD_MESSAGES_COUNT_UPDATE = 'unreadmessagescountupdate';
3458var CLOSE = 'close';
3459var CONFLICT = 'conflict';
3460var CONVERSATION_INFO_UPDATED = 'conversationinfoupdated';
3461var UNHANDLED_MESSAGE = 'unhandledmessage'; // shared
3462
3463var INVITED = 'invited';
3464var KICKED = 'kicked';
3465var MEMBERS_JOINED = 'membersjoined';
3466var MEMBERS_LEFT = 'membersleft';
3467var MEMBER_INFO_UPDATED = 'memberinfoupdated';
3468var BLOCKED = 'blocked';
3469var UNBLOCKED = 'unblocked';
3470var MEMBERS_BLOCKED = 'membersblocked';
3471var MEMBERS_UNBLOCKED = 'membersunblocked';
3472var MUTED = 'muted';
3473var UNMUTED = 'unmuted';
3474var MEMBERS_MUTED = 'membersmuted';
3475var MEMBERS_UNMUTED = 'membersunmuted';
3476var MESSAGE$1 = 'message';
3477var MESSAGE_RECALL = 'messagerecall';
3478var MESSAGE_UPDATE = 'messageupdate'; // Conversation
3479
3480var LAST_DELIVERED_AT_UPDATE = 'lastdeliveredatupdate';
3481var LAST_READ_AT_UPDATE = 'lastreadatupdate';
3482var INFO_UPDATED = 'infoupdated';
3483
3484var IMEvent = /*#__PURE__*/Object.freeze({
3485 __proto__: null,
3486 UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE,
3487 CLOSE: CLOSE,
3488 CONFLICT: CONFLICT,
3489 CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED,
3490 UNHANDLED_MESSAGE: UNHANDLED_MESSAGE,
3491 INVITED: INVITED,
3492 KICKED: KICKED,
3493 MEMBERS_JOINED: MEMBERS_JOINED,
3494 MEMBERS_LEFT: MEMBERS_LEFT,
3495 MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED,
3496 BLOCKED: BLOCKED,
3497 UNBLOCKED: UNBLOCKED,
3498 MEMBERS_BLOCKED: MEMBERS_BLOCKED,
3499 MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED,
3500 MUTED: MUTED,
3501 UNMUTED: UNMUTED,
3502 MEMBERS_MUTED: MEMBERS_MUTED,
3503 MEMBERS_UNMUTED: MEMBERS_UNMUTED,
3504 MESSAGE: MESSAGE$1,
3505 MESSAGE_RECALL: MESSAGE_RECALL,
3506 MESSAGE_UPDATE: MESSAGE_UPDATE,
3507 LAST_DELIVERED_AT_UPDATE: LAST_DELIVERED_AT_UPDATE,
3508 LAST_READ_AT_UPDATE: LAST_READ_AT_UPDATE,
3509 INFO_UPDATED: INFO_UPDATED
3510});
3511
3512var _rMessageStatus;
3513
3514function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
3515
3516function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3517/**
3518 * 消息状态枚举
3519 * @enum {Symbol}
3520 * @since 3.2.0
3521 * @memberof module:leancloud-realtime
3522 */
3523
3524var MessageStatus = {
3525 /** 初始状态、未知状态 */
3526 NONE: Symbol('none'),
3527
3528 /** 正在发送 */
3529 SENDING: Symbol('sending'),
3530
3531 /** 已发送 */
3532 SENT: Symbol('sent'),
3533
3534 /** 已送达 */
3535 DELIVERED: Symbol('delivered'),
3536
3537 /** 发送失败 */
3538 FAILED: Symbol('failed')
3539};
3540Object.freeze(MessageStatus);
3541var rMessageStatus = (_rMessageStatus = {}, _defineProperty(_rMessageStatus, MessageStatus.NONE, true), _defineProperty(_rMessageStatus, MessageStatus.SENDING, true), _defineProperty(_rMessageStatus, MessageStatus.SENT, true), _defineProperty(_rMessageStatus, MessageStatus.DELIVERED, true), _defineProperty(_rMessageStatus, MessageStatus.READ, true), _defineProperty(_rMessageStatus, MessageStatus.FAILED, true), _rMessageStatus);
3542
3543var Message = /*#__PURE__*/function () {
3544 /**
3545 * @implements AVMessage
3546 * @param {Object|String|ArrayBuffer} content 消息内容
3547 */
3548 function Message(content) {
3549 Object.assign(this, {
3550 content: content
3551 }, {
3552 /**
3553 * @type {String}
3554 * @memberof Message#
3555 */
3556 id: uuid(),
3557
3558 /**
3559 * 消息所在的 conversation id
3560 * @memberof Message#
3561 * @type {String?}
3562 */
3563 cid: null,
3564
3565 /**
3566 * 消息发送时间
3567 * @memberof Message#
3568 * @type {Date}
3569 */
3570 timestamp: new Date(),
3571
3572 /**
3573 * 消息发送者
3574 * @memberof Message#
3575 * @type {String}
3576 */
3577 from: undefined,
3578
3579 /**
3580 * 消息提及的用户
3581 * @since 4.0.0
3582 * @memberof Message#
3583 * @type {String[]}
3584 */
3585 mentionList: [],
3586
3587 /**
3588 * 消息是否提及了所有人
3589 * @since 4.0.0
3590 * @memberof Message#
3591 * @type {Boolean}
3592 */
3593 mentionedAll: false,
3594 _mentioned: false
3595 });
3596
3597 this._setStatus(MessageStatus.NONE);
3598 }
3599 /**
3600 * 将当前消息的内容序列化为 JSON 对象
3601 * @private
3602 * @return {Object}
3603 */
3604
3605
3606 var _proto = Message.prototype;
3607
3608 _proto.getPayload = function getPayload() {
3609 return this.content;
3610 };
3611
3612 _proto._toJSON = function _toJSON() {
3613 var id = this.id,
3614 cid = this.cid,
3615 from = this.from,
3616 timestamp = this.timestamp,
3617 deliveredAt = this.deliveredAt,
3618 updatedAt = this.updatedAt,
3619 mentionList = this.mentionList,
3620 mentionedAll = this.mentionedAll,
3621 mentioned = this.mentioned;
3622 return {
3623 id: id,
3624 cid: cid,
3625 from: from,
3626 timestamp: timestamp,
3627 deliveredAt: deliveredAt,
3628 updatedAt: updatedAt,
3629 mentionList: mentionList,
3630 mentionedAll: mentionedAll,
3631 mentioned: mentioned
3632 };
3633 }
3634 /**
3635 * 返回 JSON 格式的消息
3636 * @return {Object} 返回值是一个 plain Object
3637 */
3638 ;
3639
3640 _proto.toJSON = function toJSON() {
3641 return _objectSpread$3(_objectSpread$3({}, this._toJSON()), {}, {
3642 data: this.content
3643 });
3644 }
3645 /**
3646 * 返回 JSON 格式的消息,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseMessage} 反序列化。
3647 * @return {Object} 返回值是一个 plain Object
3648 * @since 4.0.0
3649 */
3650 ;
3651
3652 _proto.toFullJSON = function toFullJSON() {
3653 var content = this.content,
3654 id = this.id,
3655 cid = this.cid,
3656 from = this.from,
3657 timestamp = this.timestamp,
3658 deliveredAt = this.deliveredAt,
3659 _updatedAt = this._updatedAt,
3660 mentionList = this.mentionList,
3661 mentionedAll = this.mentionedAll;
3662 return {
3663 data: content,
3664 id: id,
3665 cid: cid,
3666 from: from,
3667 timestamp: getTime(timestamp),
3668 deliveredAt: getTime(deliveredAt),
3669 updatedAt: getTime(_updatedAt),
3670 mentionList: mentionList,
3671 mentionedAll: mentionedAll
3672 };
3673 }
3674 /**
3675 * 消息状态,值为 {@link module:leancloud-realtime.MessageStatus} 之一
3676 * @type {Symbol}
3677 * @readonly
3678 * @since 3.2.0
3679 */
3680 ;
3681
3682 _proto._setStatus = function _setStatus(status) {
3683 if (!rMessageStatus[status]) {
3684 throw new Error('Invalid message status');
3685 }
3686
3687 this._status = status;
3688 };
3689
3690 _proto._updateMentioned = function _updateMentioned(client) {
3691 this._mentioned = this.from !== client && (this.mentionedAll || this.mentionList.indexOf(client) > -1);
3692 }
3693 /**
3694 * 获取提及用户列表
3695 * @since 4.0.0
3696 * @return {String[]} 提及用户的 id 列表
3697 */
3698 ;
3699
3700 _proto.getMentionList = function getMentionList() {
3701 return this.mentionList;
3702 }
3703 /**
3704 * 设置提及用户列表
3705 * @since 4.0.0
3706 * @param {String[]} clients 提及用户的 id 列表
3707 * @return {this} self
3708 */
3709 ;
3710
3711 _proto.setMentionList = function setMentionList(clients) {
3712 this.mentionList = ensureArray(clients);
3713 return this;
3714 }
3715 /**
3716 * 设置是否提及所有人
3717 * @since 4.0.0
3718 * @param {Boolean} [value=true]
3719 * @return {this} self
3720 */
3721 ;
3722
3723 _proto.mentionAll = function mentionAll() {
3724 var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
3725 this.mentionedAll = Boolean(value);
3726 return this;
3727 }
3728 /**
3729 * 判断给定的内容是否是有效的 Message,
3730 * 该方法始终返回 true
3731 * @private
3732 * @returns {Boolean}
3733 * @implements AVMessage.validate
3734 */
3735 ;
3736
3737 Message.validate = function validate() {
3738 return true;
3739 }
3740 /**
3741 * 解析处理消息内容
3742 * <pre>
3743 * 如果子类提供了 message,返回该 message
3744 * 如果没有提供,将 json 作为 content 实例化一个 Message
3745 * @private
3746 * @param {Object} json json 格式的消息内容
3747 * @param {Message} message 子类提供的 message
3748 * @return {Message}
3749 * @implements AVMessage.parse
3750 */
3751 ;
3752
3753 Message.parse = function parse(json, message) {
3754 return message || new this(json);
3755 };
3756
3757 _createClass(Message, [{
3758 key: "status",
3759 get: function get() {
3760 return this._status;
3761 }
3762 }, {
3763 key: "timestamp",
3764 get: function get() {
3765 return this._timestamp;
3766 },
3767 set: function set(value) {
3768 this._timestamp = decodeDate(value);
3769 }
3770 /**
3771 * 消息送达时间
3772 * @type {?Date}
3773 */
3774
3775 }, {
3776 key: "deliveredAt",
3777 get: function get() {
3778 return this._deliveredAt;
3779 },
3780 set: function set(value) {
3781 this._deliveredAt = decodeDate(value);
3782 }
3783 /**
3784 * 消息修改或撤回时间,可以通过比较其与消息的 timestamp 是否相等判断消息是否被修改过或撤回过。
3785 * @type {Date}
3786 * @since 3.5.0
3787 */
3788
3789 }, {
3790 key: "updatedAt",
3791 get: function get() {
3792 return this._updatedAt || this.timestamp;
3793 },
3794 set: function set(value) {
3795 this._updatedAt = decodeDate(value);
3796 }
3797 /**
3798 * 当前用户是否在该消息中被提及
3799 * @type {Boolean}
3800 * @readonly
3801 * @since 4.0.0
3802 */
3803
3804 }, {
3805 key: "mentioned",
3806 get: function get() {
3807 return this._mentioned;
3808 }
3809 }]);
3810
3811 return Message;
3812}();
3813
3814/* eslint-disable no-param-reassign */
3815
3816var messageType = function messageType(type) {
3817 if (typeof type !== 'number') {
3818 throw new TypeError("".concat(type, " is not a Number"));
3819 }
3820
3821 return function (target) {
3822 target.TYPE = type;
3823
3824 target.validate = function (json) {
3825 return json._lctype === type;
3826 };
3827
3828 target.prototype._getType = function () {
3829 return {
3830 _lctype: type
3831 };
3832 };
3833 };
3834}; // documented in ../plugin-im.js
3835
3836var messageField = function messageField(fields) {
3837 if (typeof fields !== 'string') {
3838 if (!Array.isArray(fields)) {
3839 throw new TypeError("".concat(fields, " is not an Array"));
3840 } else if (fields.some(function (value) {
3841 return typeof value !== 'string';
3842 })) {
3843 throw new TypeError('fields contains non-string typed member');
3844 }
3845 }
3846
3847 return function (target) {
3848 // IE10 Hack:
3849 // static properties in IE10 will not be inherited from super
3850 // search for parse method and assign it manually
3851 var originalCustomFields = isIE10 ? getStaticProperty(target, '_customFields') : target._customFields;
3852 originalCustomFields = Array.isArray(originalCustomFields) ? originalCustomFields : [];
3853 target._customFields = originalCustomFields.concat(fields);
3854 };
3855}; // IE10 Hack:
3856// static properties in IE10 will not be inherited from super
3857// search for parse method and assign it manually
3858
3859var IE10Compatible = function IE10Compatible(target) {
3860 if (isIE10) {
3861 target.parse = getStaticProperty(target, 'parse');
3862 }
3863};
3864
3865var _dec, _class$1;
3866
3867function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
3868
3869function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3870
3871var // jsdoc-ignore-end
3872
3873/**
3874 * 所有内置的富媒体消息均继承自本类
3875 * @extends Message
3876 */
3877TypedMessage = (_dec = messageField(['_lctext', '_lcattrs']), _dec(_class$1 = /*#__PURE__*/function (_Message) {
3878 _inheritsLoose(TypedMessage, _Message);
3879
3880 function TypedMessage() {
3881 return _Message.apply(this, arguments) || this;
3882 }
3883
3884 var _proto = TypedMessage.prototype;
3885
3886 /**
3887 * @param {String} text
3888 * @return {this} self
3889 */
3890 _proto.setText = function setText(text) {
3891 this._lctext = text;
3892 return this;
3893 }
3894 /**
3895 * @return {String}
3896 */
3897 ;
3898
3899 _proto.getText = function getText() {
3900 return this._lctext;
3901 }
3902 /**
3903 * @param {Object} attributes
3904 * @return {this} self
3905 */
3906 ;
3907
3908 _proto.setAttributes = function setAttributes(attributes) {
3909 this._lcattrs = attributes;
3910 return this;
3911 }
3912 /**
3913 * @return {Object}
3914 */
3915 ;
3916
3917 _proto.getAttributes = function getAttributes() {
3918 return this._lcattrs;
3919 };
3920
3921 _proto._getCustomFields = function _getCustomFields() {
3922 var _this = this;
3923
3924 var fields = Array.isArray(this.constructor._customFields) ? this.constructor._customFields : [];
3925 return fields.reduce(function (result, field) {
3926 if (typeof field !== 'string') return result;
3927 result[field] = _this[field]; // eslint-disable-line no-param-reassign
3928
3929 return result;
3930 }, {});
3931 }
3932 /* eslint-disable class-methods-use-this */
3933 ;
3934
3935 _proto._getType = function _getType() {
3936 throw new Error('not implemented');
3937 }
3938 /* eslint-enable class-methods-use-this */
3939 ;
3940
3941 _proto.getPayload = function getPayload() {
3942 return compact(_objectSpread$4(_objectSpread$4({
3943 _lctext: this.getText(),
3944 _lcattrs: this.getAttributes()
3945 }, this._getCustomFields()), this._getType()));
3946 };
3947
3948 _proto.toJSON = function toJSON() {
3949 var type = this.type,
3950 text = this.text,
3951 attributes = this.attributes,
3952 summary = this.summary;
3953 return _objectSpread$4(_objectSpread$4({}, _Message.prototype._toJSON.call(this)), {}, {
3954 type: type,
3955 text: text,
3956 attributes: attributes,
3957 summary: summary
3958 });
3959 };
3960
3961 _proto.toFullJSON = function toFullJSON() {
3962 return _objectSpread$4(_objectSpread$4({}, _Message.prototype.toFullJSON.call(this)), {}, {
3963 data: this.getPayload()
3964 });
3965 }
3966 /**
3967 * 解析处理消息内容
3968 * <pre>
3969 * 为给定的 message 设置 text 与 attributes 属性,返回该 message
3970 * 如果子类没有提供 message,new this()
3971 * @protected
3972 * @param {Object} json json 格式的消息内容
3973 * @param {TypedMessage} message 子类提供的 message
3974 * @return {TypedMessage}
3975 * @implements AVMessage.parse
3976 */
3977 ;
3978
3979 TypedMessage.parse = function parse(json) {
3980 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new this();
3981 message.content = json; // eslint-disable-line no-param-reassign
3982
3983 var customFields = isIE10 ? getStaticProperty(message.constructor, '_customFields') : message.constructor._customFields;
3984 var fields = Array.isArray(customFields) ? customFields : [];
3985 fields = fields.reduce(function (result, field) {
3986 if (typeof field !== 'string') return result;
3987 result[field] = json[field]; // eslint-disable-line no-param-reassign
3988
3989 return result;
3990 }, {});
3991 Object.assign(message, fields);
3992 return _Message.parse.call(this, json, message);
3993 };
3994
3995 _createClass(TypedMessage, [{
3996 key: "type",
3997
3998 /**
3999 * @type {Number}
4000 * @readonly
4001 */
4002 get: function get() {
4003 return this.constructor.TYPE;
4004 }
4005 /** @type {String} */
4006
4007 }, {
4008 key: "text",
4009 set: function set(text) {
4010 return this.setText(text);
4011 },
4012 get: function get() {
4013 return this.getText();
4014 }
4015 /** @type {Object} */
4016
4017 }, {
4018 key: "attributes",
4019 set: function set(attributes) {
4020 return this.setAttributes(attributes);
4021 },
4022 get: function get() {
4023 return this.getAttributes();
4024 }
4025 /**
4026 * 在客户端需要以文本形式展示该消息时显示的文案,
4027 * 如 <code>[红包] 新春快乐</code>。
4028 * 默认值为消息的 text。
4029 * @type {String}
4030 * @readonly
4031 */
4032
4033 }, {
4034 key: "summary",
4035 get: function get() {
4036 return this.text;
4037 }
4038 }]);
4039
4040 return TypedMessage;
4041}(Message)) || _class$1);
4042
4043var _dec$1, _class$2;
4044
4045var // jsdoc-ignore-end
4046
4047/**
4048 * 已撤回类型消息,当消息被撤回时,SDK 会使用该类型的消息替代原始消息
4049 * @extends TypedMessage
4050 */
4051RecalledMessage = (_dec$1 = messageType(-127), _dec$1(_class$2 = IE10Compatible(_class$2 = /*#__PURE__*/function (_TypedMessage) {
4052 _inheritsLoose(RecalledMessage, _TypedMessage);
4053
4054 function RecalledMessage() {
4055 return _TypedMessage.apply(this, arguments) || this;
4056 }
4057
4058 _createClass(RecalledMessage, [{
4059 key: "summary",
4060
4061 /**
4062 * 在客户端需要以文本形式展示该消息时显示的文案,值为 <code>[该消息已撤回]</code>
4063 * @type {String}
4064 * @readonly
4065 */
4066 // eslint-disable-next-line class-methods-use-this
4067 get: function get() {
4068 return '[该消息已撤回]';
4069 }
4070 }]);
4071
4072 return RecalledMessage;
4073}(TypedMessage)) || _class$2) || _class$2);
4074
4075function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
4076
4077function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
4078var debug$7 = d('LC:Conversation');
4079
4080var serializeMessage = function serializeMessage(message) {
4081 var content = message.getPayload();
4082 var msg;
4083 var binaryMsg;
4084
4085 if (content instanceof ArrayBuffer) {
4086 binaryMsg = content;
4087 } else if (typeof content !== 'string') {
4088 msg = JSON.stringify(content);
4089 } else {
4090 msg = content;
4091 }
4092
4093 return {
4094 msg: msg,
4095 binaryMsg: binaryMsg
4096 };
4097};
4098
4099var _LogsCommand$QueryDir = LogsCommand.QueryDirection,
4100 NEW = _LogsCommand$QueryDir.NEW,
4101 OLD = _LogsCommand$QueryDir.OLD;
4102/**
4103 * 历史消息查询方向枚举
4104 * @enum {Number}
4105 * @since 4.0.0
4106 * @memberof module:leancloud-realtime
4107 */
4108
4109var MessageQueryDirection = {
4110 /** 从后向前 */
4111 NEW_TO_OLD: OLD,
4112
4113 /** 从前向后 */
4114 OLD_TO_NEW: NEW
4115};
4116Object.freeze(MessageQueryDirection);
4117
4118var ConversationBase = /*#__PURE__*/function (_EventEmitter) {
4119 _inheritsLoose(ConversationBase, _EventEmitter);
4120
4121 /**
4122 * @extends EventEmitter
4123 * @private
4124 * @abstract
4125 */
4126 function ConversationBase(_ref, client) {
4127 var _this;
4128
4129 var id = _ref.id,
4130 lastMessageAt = _ref.lastMessageAt,
4131 lastMessage = _ref.lastMessage,
4132 lastDeliveredAt = _ref.lastDeliveredAt,
4133 lastReadAt = _ref.lastReadAt,
4134 _ref$unreadMessagesCo = _ref.unreadMessagesCount,
4135 unreadMessagesCount = _ref$unreadMessagesCo === void 0 ? 0 : _ref$unreadMessagesCo,
4136 _ref$members = _ref.members,
4137 members = _ref$members === void 0 ? [] : _ref$members,
4138 _ref$mentioned = _ref.mentioned,
4139 mentioned = _ref$mentioned === void 0 ? false : _ref$mentioned,
4140 properties = _objectWithoutProperties(_ref, ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"]);
4141
4142 _this = _EventEmitter.call(this) || this;
4143 Object.assign(_assertThisInitialized(_this), _objectSpread$5({
4144 /**
4145 * 对话 id,对应 _Conversation 表中的 objectId
4146 * @memberof ConversationBase#
4147 * @type {String}
4148 */
4149 id: id,
4150
4151 /**
4152 * 最后一条消息时间
4153 * @memberof ConversationBase#
4154 * @type {?Date}
4155 */
4156 lastMessageAt: lastMessageAt,
4157
4158 /**
4159 * 最后一条消息
4160 * @memberof ConversationBase#
4161 * @type {?Message}
4162 */
4163 lastMessage: lastMessage,
4164
4165 /**
4166 * 参与该对话的用户列表
4167 * @memberof ConversationBase#
4168 * @type {String[]}
4169 */
4170 members: members
4171 }, properties));
4172 _this.members = Array.from(new Set(_this.members));
4173 Object.assign(internal(_assertThisInitialized(_this)), {
4174 messagesWaitingForReceipt: {},
4175 lastDeliveredAt: lastDeliveredAt,
4176 lastReadAt: lastReadAt,
4177 unreadMessagesCount: unreadMessagesCount,
4178 mentioned: mentioned
4179 });
4180 _this._client = client;
4181
4182 if (debug$7.enabled) {
4183 values(IMEvent).forEach(function (event) {
4184 return _this.on(event, function () {
4185 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
4186 payload[_key] = arguments[_key];
4187 }
4188
4189 return _this._debug("".concat(event, " event emitted. %o"), payload);
4190 });
4191 });
4192 } // onConversationCreate hook
4193
4194
4195 applyDecorators(_this._client._plugins.onConversationCreate, _assertThisInitialized(_this));
4196 return _this;
4197 }
4198 /**
4199 * 当前用户是否在该对话的未读消息中被提及
4200 * @type {Boolean}
4201 * @since 4.0.0
4202 */
4203
4204
4205 var _proto = ConversationBase.prototype;
4206
4207 _proto._setUnreadMessagesMentioned = function _setUnreadMessagesMentioned(value) {
4208 internal(this).unreadMessagesMentioned = Boolean(value);
4209 };
4210
4211 _proto._setLastDeliveredAt = function _setLastDeliveredAt(value) {
4212 var date = decodeDate(value);
4213
4214 if (!(date < internal(this).lastDeliveredAt)) {
4215 internal(this).lastDeliveredAt = date;
4216 /**
4217 * 最后消息送达时间更新
4218 * @event ConversationBase#LAST_DELIVERED_AT_UPDATE
4219 * @since 3.4.0
4220 */
4221
4222 this.emit(LAST_DELIVERED_AT_UPDATE);
4223 }
4224 }
4225 /**
4226 * 最后消息被阅读时间,常用来实现发送消息的「已读」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
4227 * @type {?Date}
4228 * @since 3.4.0
4229 */
4230 ;
4231
4232 _proto._setLastReadAt = function _setLastReadAt(value) {
4233 var date = decodeDate(value);
4234
4235 if (!(date < internal(this).lastReadAt)) {
4236 internal(this).lastReadAt = date;
4237 /**
4238 * 最后消息被阅读时间更新
4239 * @event ConversationBase#LAST_READ_AT_UPDATE
4240 * @since 3.4.0
4241 */
4242
4243 this.emit(LAST_READ_AT_UPDATE);
4244 }
4245 }
4246 /**
4247 * 返回 JSON 格式的对话,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseConversation} 反序列化。
4248 * @return {Object} 返回值是一个 plain Object
4249 * @since 4.0.0
4250 */
4251 ;
4252
4253 _proto.toFullJSON = function toFullJSON() {
4254 var id = this.id,
4255 members = this.members,
4256 lastMessageAt = this.lastMessageAt,
4257 lastDeliveredAt = this.lastDeliveredAt,
4258 lastReadAt = this.lastReadAt,
4259 lastMessage = this.lastMessage,
4260 unreadMessagesCount = this.unreadMessagesCount;
4261 return {
4262 id: id,
4263 members: members,
4264 lastMessageAt: getTime(lastMessageAt),
4265 lastDeliveredAt: getTime(lastDeliveredAt),
4266 lastReadAt: getTime(lastReadAt),
4267 lastMessage: lastMessage ? lastMessage.toFullJSON() : undefined,
4268 unreadMessagesCount: unreadMessagesCount
4269 };
4270 }
4271 /**
4272 * 返回 JSON 格式的对话
4273 * @return {Object} 返回值是一个 plain Object
4274 * @since 4.0.0
4275 */
4276 ;
4277
4278 _proto.toJSON = function toJSON() {
4279 var id = this.id,
4280 members = this.members,
4281 lastMessageAt = this.lastMessageAt,
4282 lastDeliveredAt = this.lastDeliveredAt,
4283 lastReadAt = this.lastReadAt,
4284 lastMessage = this.lastMessage,
4285 unreadMessagesCount = this.unreadMessagesCount,
4286 unreadMessagesMentioned = this.unreadMessagesMentioned;
4287 return {
4288 id: id,
4289 members: members,
4290 lastMessageAt: lastMessageAt,
4291 lastDeliveredAt: lastDeliveredAt,
4292 lastReadAt: lastReadAt,
4293 lastMessage: lastMessage ? lastMessage.toJSON() : undefined,
4294 unreadMessagesCount: unreadMessagesCount,
4295 unreadMessagesMentioned: unreadMessagesMentioned
4296 };
4297 };
4298
4299 _proto._debug = function _debug() {
4300 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
4301 params[_key2] = arguments[_key2];
4302 }
4303
4304 debug$7.apply(void 0, params.concat(["[".concat(this.id, "]")]));
4305 };
4306
4307 _proto._send = function _send(command) {
4308 var _this$_client;
4309
4310 /* eslint-disable no-param-reassign */
4311 if (command.cmd === null) {
4312 command.cmd = 'conv';
4313 }
4314
4315 if (command.cmd === 'conv' && command.convMessage === null) {
4316 command.convMessage = new ConvCommand();
4317 }
4318
4319 if (command.convMessage && command.convMessage.cid === null) {
4320 command.convMessage.cid = this.id;
4321 }
4322 /* eslint-enable no-param-reassign */
4323
4324
4325 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
4326 args[_key3 - 1] = arguments[_key3];
4327 }
4328
4329 return (_this$_client = this._client)._send.apply(_this$_client, [command].concat(args));
4330 }
4331 /**
4332 * 发送消息
4333 * @param {Message} message 消息,Message 及其子类的实例
4334 * @param {Object} [options] since v3.3.0,发送选项
4335 * @param {Boolean} [options.transient] since v3.3.1,是否作为暂态消息发送
4336 * @param {Boolean} [options.receipt] 是否需要回执,仅在普通对话中有效
4337 * @param {Boolean} [options.will] since v3.4.0,是否指定该消息作为「掉线消息」发送,
4338 * 「掉线消息」会延迟到当前用户掉线后发送,常用来实现「下线通知」功能
4339 * @param {MessagePriority} [options.priority] 消息优先级,仅在暂态对话中有效,
4340 * see: {@link module:leancloud-realtime.MessagePriority MessagePriority}
4341 * @param {Object} [options.pushData] 消息对应的离线推送内容,如果消息接收方不在线,会推送指定的内容。其结构说明参见: {@link https://url.leanapp.cn/pushData 推送消息内容}
4342 * @return {Promise.<Message>} 发送的消息
4343 */
4344 ;
4345
4346 _proto.send =
4347 /*#__PURE__*/
4348 function () {
4349 var _send2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(message, options) {
4350 var _message$constructor$, _transient, receipt, priority, pushData, will, _serializeMessage, msg, binaryMsg, command, resCommand, _resCommand$ackMessag, uid, t, code, reason, appCode;
4351
4352 return _regeneratorRuntime.wrap(function _callee$(_context) {
4353 while (1) {
4354 switch (_context.prev = _context.next) {
4355 case 0:
4356 this._debug(message, 'send');
4357
4358 if (message instanceof Message) {
4359 _context.next = 3;
4360 break;
4361 }
4362
4363 throw new TypeError("".concat(message, " is not a Message"));
4364
4365 case 3:
4366 _message$constructor$ = _objectSpread$5(_objectSpread$5(_objectSpread$5({}, message.constructor.sendOptions), typeof message.constructor.getSendOptions === 'function' ? message.constructor.getSendOptions(message) : {}), options), _transient = _message$constructor$["transient"], receipt = _message$constructor$.receipt, priority = _message$constructor$.priority, pushData = _message$constructor$.pushData, will = _message$constructor$.will;
4367
4368 if (receipt) {
4369 if (this["transient"]) {
4370 console.warn('receipt option is ignored as the conversation is transient.');
4371 } else if (_transient) {
4372 console.warn('receipt option is ignored as the message is sent transiently.');
4373 } else if (this.members.length > 2) {
4374 console.warn('receipt option is recommended to be used in one-on-one conversation.'); // eslint-disable-line max-len
4375 }
4376 }
4377
4378 if (priority && !this["transient"]) {
4379 console.warn('priority option is ignored as the conversation is not transient.');
4380 }
4381
4382 Object.assign(message, {
4383 cid: this.id,
4384 from: this._client.id
4385 });
4386
4387 message._setStatus(MessageStatus.SENDING);
4388
4389 _serializeMessage = serializeMessage(message), msg = _serializeMessage.msg, binaryMsg = _serializeMessage.binaryMsg;
4390 command = new GenericCommand({
4391 cmd: 'direct',
4392 directMessage: new DirectCommand({
4393 msg: msg,
4394 binaryMsg: binaryMsg,
4395 cid: this.id,
4396 r: receipt,
4397 "transient": _transient,
4398 dt: message.id,
4399 pushData: JSON.stringify(pushData),
4400 will: will,
4401 mentionPids: message.mentionList,
4402 mentionAll: message.mentionedAll
4403 }),
4404 priority: priority
4405 });
4406 _context.prev = 10;
4407 _context.next = 13;
4408 return this._send(command);
4409
4410 case 13:
4411 resCommand = _context.sent;
4412 _resCommand$ackMessag = resCommand.ackMessage, uid = _resCommand$ackMessag.uid, t = _resCommand$ackMessag.t, code = _resCommand$ackMessag.code, reason = _resCommand$ackMessag.reason, appCode = _resCommand$ackMessag.appCode;
4413
4414 if (!(code !== null)) {
4415 _context.next = 17;
4416 break;
4417 }
4418
4419 throw createError({
4420 code: code,
4421 reason: reason,
4422 appCode: appCode
4423 });
4424
4425 case 17:
4426 Object.assign(message, {
4427 id: uid,
4428 timestamp: t
4429 });
4430
4431 if (!_transient) {
4432 this.lastMessage = message;
4433 this.lastMessageAt = message.timestamp;
4434 }
4435
4436 message._setStatus(MessageStatus.SENT);
4437
4438 if (receipt) {
4439 internal(this).messagesWaitingForReceipt[message.id] = message;
4440 }
4441
4442 return _context.abrupt("return", message);
4443
4444 case 24:
4445 _context.prev = 24;
4446 _context.t0 = _context["catch"](10);
4447
4448 message._setStatus(MessageStatus.FAILED);
4449
4450 throw _context.t0;
4451
4452 case 28:
4453 case "end":
4454 return _context.stop();
4455 }
4456 }
4457 }, _callee, this, [[10, 24]]);
4458 }));
4459
4460 function send(_x, _x2) {
4461 return _send2.apply(this, arguments);
4462 }
4463
4464 return send;
4465 }();
4466
4467 _proto._update = /*#__PURE__*/function () {
4468 var _update2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(message, newMessage, recall) {
4469 var msg, binaryMsg, content, id, cid, timestamp, from, _status;
4470
4471 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
4472 while (1) {
4473 switch (_context2.prev = _context2.next) {
4474 case 0:
4475 this._debug('patch %O %O %O', message, newMessage, recall);
4476
4477 if (!(message instanceof Message)) {
4478 _context2.next = 8;
4479 break;
4480 }
4481
4482 if (!(message.from !== this._client.id)) {
4483 _context2.next = 4;
4484 break;
4485 }
4486
4487 throw new Error('Updating message from others is not allowed');
4488
4489 case 4:
4490 if (!(message.status !== MessageStatus.SENT && message.status !== MessageStatus.DELIVERED)) {
4491 _context2.next = 6;
4492 break;
4493 }
4494
4495 throw new Error('Message is not sent');
4496
4497 case 6:
4498 _context2.next = 10;
4499 break;
4500
4501 case 8:
4502 if (message.id && message.timestamp) {
4503 _context2.next = 10;
4504 break;
4505 }
4506
4507 throw new TypeError("".concat(message, " is not a Message"));
4508
4509 case 10:
4510 if (!recall) {
4511 content = serializeMessage(newMessage);
4512 msg = content.msg;
4513 binaryMsg = content.binaryMsg;
4514 }
4515
4516 _context2.next = 13;
4517 return this._send(new GenericCommand({
4518 cmd: CommandType.patch,
4519 op: OpType.modify,
4520 patchMessage: new PatchCommand({
4521 patches: [new PatchItem({
4522 cid: this.id,
4523 mid: message.id,
4524 timestamp: Number(message.timestamp),
4525 recall: recall,
4526 data: msg,
4527 binaryMsg: binaryMsg,
4528 mentionPids: newMessage.mentionList,
4529 mentionAll: newMessage.mentionedAll
4530 })],
4531 lastPatchTime: this._client._lastPatchTime
4532 })
4533 }));
4534
4535 case 13:
4536 id = message.id, cid = message.cid, timestamp = message.timestamp, from = message.from, _status = message._status;
4537 Object.assign(newMessage, {
4538 id: id,
4539 cid: cid,
4540 timestamp: timestamp,
4541 from: from,
4542 _status: _status
4543 });
4544
4545 if (this.lastMessage && this.lastMessage.id === newMessage.id) {
4546 this.lastMessage = newMessage;
4547 }
4548
4549 return _context2.abrupt("return", newMessage);
4550
4551 case 17:
4552 case "end":
4553 return _context2.stop();
4554 }
4555 }
4556 }, _callee2, this);
4557 }));
4558
4559 function _update(_x3, _x4, _x5) {
4560 return _update2.apply(this, arguments);
4561 }
4562
4563 return _update;
4564 }()
4565 /**
4566 * 获取对话人数,或暂态对话的在线人数
4567 * @return {Promise.<Number>}
4568 */
4569 ;
4570
4571 _proto.count =
4572 /*#__PURE__*/
4573 function () {
4574 var _count = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
4575 var resCommand;
4576 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
4577 while (1) {
4578 switch (_context3.prev = _context3.next) {
4579 case 0:
4580 this._debug('count');
4581
4582 _context3.next = 3;
4583 return this._send(new GenericCommand({
4584 op: 'count'
4585 }));
4586
4587 case 3:
4588 resCommand = _context3.sent;
4589 return _context3.abrupt("return", resCommand.convMessage.count);
4590
4591 case 5:
4592 case "end":
4593 return _context3.stop();
4594 }
4595 }
4596 }, _callee3, this);
4597 }));
4598
4599 function count() {
4600 return _count.apply(this, arguments);
4601 }
4602
4603 return count;
4604 }()
4605 /**
4606 * 应用增加成员的操作,产生副作用
4607 * @param {string[]} members
4608 * @abstract
4609 * @private
4610 */
4611 ;
4612
4613 _proto._addMembers = function _addMembers() {}
4614 /**
4615 * 应用减少成员的操作,产生副作用
4616 * @param {string[]} members
4617 * @abstract
4618 * @private
4619 */
4620 ;
4621
4622 _proto._removeMembers = function _removeMembers() {}
4623 /**
4624 * 修改已发送的消息
4625 * @param {AVMessage} message 要修改的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
4626 * @param {AVMessage} newMessage 新的消息
4627 * @return {Promise.<AVMessage>} 更新后的消息
4628 */
4629 ;
4630
4631 _proto.update =
4632 /*#__PURE__*/
4633 function () {
4634 var _update3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(message, newMessage) {
4635 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
4636 while (1) {
4637 switch (_context4.prev = _context4.next) {
4638 case 0:
4639 if (newMessage instanceof Message) {
4640 _context4.next = 2;
4641 break;
4642 }
4643
4644 throw new TypeError("".concat(newMessage, " is not a Message"));
4645
4646 case 2:
4647 return _context4.abrupt("return", this._update(message, newMessage, false));
4648
4649 case 3:
4650 case "end":
4651 return _context4.stop();
4652 }
4653 }
4654 }, _callee4, this);
4655 }));
4656
4657 function update(_x6, _x7) {
4658 return _update3.apply(this, arguments);
4659 }
4660
4661 return update;
4662 }()
4663 /**
4664 * 撤回已发送的消息
4665 * @param {AVMessage} message 要撤回的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
4666 * @return {Promise.<RecalledMessage>} 一条已撤回的消息
4667 */
4668 ;
4669
4670 _proto.recall =
4671 /*#__PURE__*/
4672 function () {
4673 var _recall = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(message) {
4674 return _regeneratorRuntime.wrap(function _callee5$(_context5) {
4675 while (1) {
4676 switch (_context5.prev = _context5.next) {
4677 case 0:
4678 return _context5.abrupt("return", this._update(message, new RecalledMessage(), true));
4679
4680 case 1:
4681 case "end":
4682 return _context5.stop();
4683 }
4684 }
4685 }, _callee5, this);
4686 }));
4687
4688 function recall(_x8) {
4689 return _recall.apply(this, arguments);
4690 }
4691
4692 return recall;
4693 }()
4694 /**
4695 * 查询消息记录
4696 * 如果仅需实现消息向前记录翻页查询需求,建议使用 {@link Conversation#createMessagesIterator}。
4697 * 不论何种方向,获得的消息都是按照时间升序排列的。
4698 * startClosed 与 endClosed 用于指定查询区间的开闭。
4699 *
4700 * @param {Object} [options]
4701 * @param {Number} [options.limit] 限制查询结果的数量,目前服务端默认为 20
4702 * @param {Number} [options.type] 指定查询的富媒体消息类型,不指定则查询所有消息。
4703 * @param {MessageQueryDirection} [options.direction] 查询的方向。
4704 * 在不指定的情况下如果 startTime 大于 endTime,则为从新到旧查询,可以实现加载聊天记录等场景。
4705 * 如果 startTime 小于 endTime,则为从旧到新查询,可以实现弹幕等场景。
4706 * @param {Date} [options.startTime] 从该时间开始查询,不传则从当前时间开始查询
4707 * @param {String} [options.startMessageId] 从该消息之前开始查询,需要与 startTime 同时使用,为防止某时刻有重复消息
4708 * @param {Boolean}[options.startClosed] 指定查询范围是否包括开始的时间点,默认不包括
4709 * @param {Date} [options.endTime] 查询到该时间为止,不传则查询最早消息为止
4710 * @param {String} [options.endMessageId] 查询到该消息为止,需要与 endTime 同时使用,为防止某时刻有重复消息
4711 * @param {Boolean}[options.endClosed] 指定查询范围是否包括结束的时间点,默认不包括
4712 *
4713 * @param {Date} [options.beforeTime] DEPRECATED: 使用 startTime 代替。限制查询结果为小于该时间之前的消息,不传则为当前时间
4714 * @param {String} [options.beforeMessageId] DEPRECATED: 使用 startMessageId 代替。
4715 * 限制查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
4716 * @param {Date} [options.afterTime] DEPRECATED: 使用 endTime 代替。限制查询结果为大于该时间之前的消息
4717 * @param {String} [options.afterMessageId] DEPRECATED: 使用 endMessageId 代替。
4718 * 限制查询结果为该消息之后的消息,需要与 afterTime 同时使用,为防止某时刻有重复消息
4719 * @return {Promise.<Message[]>} 消息列表
4720 */
4721 ;
4722
4723 _proto.queryMessages =
4724 /*#__PURE__*/
4725 function () {
4726 var _queryMessages = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() {
4727 var _this2 = this;
4728
4729 var options,
4730 beforeTime,
4731 beforeMessageId,
4732 afterTime,
4733 afterMessageId,
4734 limit,
4735 direction,
4736 type,
4737 startTime,
4738 startMessageId,
4739 startClosed,
4740 endTime,
4741 endMessageId,
4742 endClosed,
4743 conditions,
4744 resCommand,
4745 _args7 = arguments;
4746 return _regeneratorRuntime.wrap(function _callee7$(_context7) {
4747 while (1) {
4748 switch (_context7.prev = _context7.next) {
4749 case 0:
4750 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
4751
4752 this._debug('query messages %O', options);
4753
4754 beforeTime = options.beforeTime, beforeMessageId = options.beforeMessageId, afterTime = options.afterTime, afterMessageId = options.afterMessageId, limit = options.limit, direction = options.direction, type = options.type, startTime = options.startTime, startMessageId = options.startMessageId, startClosed = options.startClosed, endTime = options.endTime, endMessageId = options.endMessageId, endClosed = options.endClosed;
4755
4756 if (!(beforeMessageId || beforeTime || afterMessageId || afterTime)) {
4757 _context7.next = 6;
4758 break;
4759 }
4760
4761 console.warn('DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId.');
4762 return _context7.abrupt("return", this.queryMessages({
4763 startTime: beforeTime,
4764 startMessageId: beforeMessageId,
4765 endTime: afterTime,
4766 endMessageId: afterMessageId,
4767 limit: limit
4768 }));
4769
4770 case 6:
4771 if (!(startMessageId && !startTime)) {
4772 _context7.next = 8;
4773 break;
4774 }
4775
4776 throw new Error('query option startMessageId must be used with option startTime');
4777
4778 case 8:
4779 if (!(endMessageId && !endTime)) {
4780 _context7.next = 10;
4781 break;
4782 }
4783
4784 throw new Error('query option endMessageId must be used with option endTime');
4785
4786 case 10:
4787 conditions = {
4788 t: startTime,
4789 mid: startMessageId,
4790 tIncluded: startClosed,
4791 tt: endTime,
4792 tmid: endMessageId,
4793 ttIncluded: endClosed,
4794 l: limit,
4795 lctype: type
4796 };
4797
4798 if (conditions.t instanceof Date) {
4799 conditions.t = conditions.t.getTime();
4800 }
4801
4802 if (conditions.tt instanceof Date) {
4803 conditions.tt = conditions.tt.getTime();
4804 }
4805
4806 if (direction !== undefined) {
4807 conditions.direction = direction;
4808 } else if (conditions.tt > conditions.t) {
4809 conditions.direction = MessageQueryDirection.OLD_TO_NEW;
4810 }
4811
4812 _context7.next = 16;
4813 return this._send(new GenericCommand({
4814 cmd: 'logs',
4815 logsMessage: new LogsCommand(Object.assign(conditions, {
4816 cid: this.id
4817 }))
4818 }));
4819
4820 case 16:
4821 resCommand = _context7.sent;
4822 return _context7.abrupt("return", Promise.all(resCommand.logsMessage.logs.map( /*#__PURE__*/function () {
4823 var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(_ref2) {
4824 var msgId, timestamp, patchTimestamp, from, ackAt, readAt, data, mentionAll, mentionPids, bin, messageData, message, status;
4825 return _regeneratorRuntime.wrap(function _callee6$(_context6) {
4826 while (1) {
4827 switch (_context6.prev = _context6.next) {
4828 case 0:
4829 msgId = _ref2.msgId, timestamp = _ref2.timestamp, patchTimestamp = _ref2.patchTimestamp, from = _ref2.from, ackAt = _ref2.ackAt, readAt = _ref2.readAt, data = _ref2.data, mentionAll = _ref2.mentionAll, mentionPids = _ref2.mentionPids, bin = _ref2.bin;
4830 messageData = {
4831 data: data,
4832 bin: bin,
4833 id: msgId,
4834 cid: _this2.id,
4835 timestamp: timestamp,
4836 from: from,
4837 deliveredAt: ackAt,
4838 updatedAt: patchTimestamp,
4839 mentionList: mentionPids,
4840 mentionedAll: mentionAll
4841 };
4842 _context6.next = 4;
4843 return _this2._client.parseMessage(messageData);
4844
4845 case 4:
4846 message = _context6.sent;
4847 status = MessageStatus.SENT;
4848
4849 if (_this2.members.length === 2) {
4850 if (ackAt) status = MessageStatus.DELIVERED;
4851 if (ackAt) _this2._setLastDeliveredAt(ackAt);
4852 if (readAt) _this2._setLastReadAt(readAt);
4853 }
4854
4855 message._setStatus(status);
4856
4857 return _context6.abrupt("return", message);
4858
4859 case 9:
4860 case "end":
4861 return _context6.stop();
4862 }
4863 }
4864 }, _callee6);
4865 }));
4866
4867 return function (_x9) {
4868 return _ref3.apply(this, arguments);
4869 };
4870 }())));
4871
4872 case 18:
4873 case "end":
4874 return _context7.stop();
4875 }
4876 }
4877 }, _callee7, this);
4878 }));
4879
4880 function queryMessages() {
4881 return _queryMessages.apply(this, arguments);
4882 }
4883
4884 return queryMessages;
4885 }()
4886 /**
4887 * 获取消息翻页迭代器
4888 * @param {Object} [options]
4889 * @param {Date} [options.beforeTime] 限制起始查询结果为小于该时间之前的消息,不传则为当前时间
4890 * @param {String} [options.beforeMessageId] 限制起始查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
4891 * @param {Number} [options.limit] 限制每页查询结果的数量,目前服务端默认为 20
4892 * @return {AsyncIterater.<Promise.<IteratorResult<Message[]>>>} [AsyncIterator]{@link https://github.com/tc39/proposal-async-iteration},调用其 next 方法返回获取下一页消息的 Promise
4893 * @example
4894 * var messageIterator = conversation.createMessagesIterator({ limit: 10 });
4895 * messageIterator.next().then(function(result) {
4896 * // result: {
4897 * // value: [message1, ..., message10],
4898 * // done: false,
4899 * // }
4900 * });
4901 * messageIterator.next().then(function(result) {
4902 * // result: {
4903 * // value: [message11, ..., message20],
4904 * // done: false,
4905 * // }
4906 * });
4907 * messageIterator.next().then(function(result) {
4908 * // No more messages
4909 * // result: { value: [], done: true }
4910 * });
4911 */
4912 ;
4913
4914 _proto.createMessagesIterator = function createMessagesIterator() {
4915 var _this3 = this;
4916
4917 var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
4918 beforeTime = _ref4.beforeTime,
4919 beforeMessageId = _ref4.beforeMessageId,
4920 limit = _ref4.limit;
4921
4922 var promise;
4923 return {
4924 next: function next() {
4925 if (promise === undefined) {
4926 // first call
4927 promise = _this3.queryMessages({
4928 limit: limit,
4929 startTime: beforeTime,
4930 startMessageId: beforeMessageId
4931 });
4932 } else {
4933 promise = promise.then(function (prevMessages) {
4934 if (prevMessages.length === 0 || prevMessages.length < limit) {
4935 // no more messages
4936 return [];
4937 }
4938
4939 return _this3.queryMessages({
4940 startTime: prevMessages[0].timestamp,
4941 startMessageId: prevMessages[0].id,
4942 limit: limit
4943 });
4944 });
4945 }
4946
4947 return promise.then(function (value) {
4948 return {
4949 value: Array.from(value),
4950 done: value.length === 0 || value.length < limit
4951 };
4952 });
4953 }
4954 };
4955 }
4956 /**
4957 * 将该会话标记为已读
4958 * @return {Promise.<this>} self
4959 */
4960 ;
4961
4962 _proto.read =
4963 /*#__PURE__*/
4964 function () {
4965 var _read = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
4966 var client;
4967 return _regeneratorRuntime.wrap(function _callee8$(_context8) {
4968 while (1) {
4969 switch (_context8.prev = _context8.next) {
4970 case 0:
4971 this.unreadMessagesCount = 0;
4972
4973 this._setUnreadMessagesMentioned(false); // 跳过暂态会话
4974
4975
4976 if (!this["transient"]) {
4977 _context8.next = 4;
4978 break;
4979 }
4980
4981 return _context8.abrupt("return", this);
4982
4983 case 4:
4984 client = this._client;
4985
4986 if (!internal(client).readConversationsBuffer) {
4987 internal(client).readConversationsBuffer = new Set();
4988 }
4989
4990 internal(client).readConversationsBuffer.add(this);
4991
4992 client._doSendRead();
4993
4994 return _context8.abrupt("return", this);
4995
4996 case 9:
4997 case "end":
4998 return _context8.stop();
4999 }
5000 }
5001 }, _callee8, this);
5002 }));
5003
5004 function read() {
5005 return _read.apply(this, arguments);
5006 }
5007
5008 return read;
5009 }();
5010
5011 _proto._handleReceipt = function _handleReceipt(_ref5) {
5012 var messageId = _ref5.messageId,
5013 timestamp = _ref5.timestamp,
5014 read = _ref5.read;
5015
5016 if (read) {
5017 this._setLastReadAt(timestamp);
5018 } else {
5019 this._setLastDeliveredAt(timestamp);
5020 }
5021
5022 var _internal = internal(this),
5023 messagesWaitingForReceipt = _internal.messagesWaitingForReceipt;
5024
5025 var message = messagesWaitingForReceipt[messageId];
5026 if (!message) return;
5027
5028 message._setStatus(MessageStatus.DELIVERED);
5029
5030 message.deliveredAt = timestamp;
5031 delete messagesWaitingForReceipt[messageId];
5032 }
5033 /**
5034 * 更新对话的最新回执时间戳(lastDeliveredAt、lastReadAt)
5035 * @since 3.4.0
5036 * @return {Promise.<this>} this
5037 */
5038 ;
5039
5040 _proto.fetchReceiptTimestamps =
5041 /*#__PURE__*/
5042 function () {
5043 var _fetchReceiptTimestamps = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() {
5044 var _yield$this$_send, _yield$this$_send$con, maxReadTimestamp, maxAckTimestamp;
5045
5046 return _regeneratorRuntime.wrap(function _callee9$(_context9) {
5047 while (1) {
5048 switch (_context9.prev = _context9.next) {
5049 case 0:
5050 if (!(this["transient"] || this.system)) {
5051 _context9.next = 2;
5052 break;
5053 }
5054
5055 return _context9.abrupt("return", this);
5056
5057 case 2:
5058 _context9.next = 4;
5059 return this._send(new GenericCommand({
5060 op: 'max_read'
5061 }));
5062
5063 case 4:
5064 _yield$this$_send = _context9.sent;
5065 _yield$this$_send$con = _yield$this$_send.convMessage;
5066 maxReadTimestamp = _yield$this$_send$con.maxReadTimestamp;
5067 maxAckTimestamp = _yield$this$_send$con.maxAckTimestamp;
5068
5069 this._setLastDeliveredAt(maxAckTimestamp);
5070
5071 this._setLastReadAt(maxReadTimestamp);
5072
5073 return _context9.abrupt("return", this);
5074
5075 case 11:
5076 case "end":
5077 return _context9.stop();
5078 }
5079 }
5080 }, _callee9, this);
5081 }));
5082
5083 function fetchReceiptTimestamps() {
5084 return _fetchReceiptTimestamps.apply(this, arguments);
5085 }
5086
5087 return fetchReceiptTimestamps;
5088 }();
5089
5090 _proto._fetchAllReceiptTimestamps = function _fetchAllReceiptTimestamps() {
5091 // 暂态/系统会话不支持回执
5092 if (this["transient"] || this.system) return this;
5093 var convMessage = new ConvCommand({
5094 queryAllMembers: true
5095 });
5096 return this._send(new GenericCommand({
5097 op: 'max_read',
5098 convMessage: convMessage
5099 })).then(function (_ref6) {
5100 var maxReadTuples = _ref6.convMessage.maxReadTuples;
5101 return maxReadTuples.filter(function (maxReadTuple) {
5102 return maxReadTuple.maxAckTimestamp || maxReadTuple.maxReadTimestamp;
5103 }).map(function (_ref7) {
5104 var pid = _ref7.pid,
5105 maxAckTimestamp = _ref7.maxAckTimestamp,
5106 maxReadTimestamp = _ref7.maxReadTimestamp;
5107 return {
5108 pid: pid,
5109 lastDeliveredAt: decodeDate(maxAckTimestamp),
5110 lastReadAt: decodeDate(maxReadTimestamp)
5111 };
5112 });
5113 });
5114 };
5115
5116 _createClass(ConversationBase, [{
5117 key: "unreadMessagesMentioned",
5118 get: function get() {
5119 return internal(this).unreadMessagesMentioned;
5120 }
5121 }, {
5122 key: "unreadMessagesCount",
5123 set: function set(value) {
5124 if (value !== this.unreadMessagesCount) {
5125 internal(this).unreadMessagesCount = value;
5126
5127 this._client.emit(UNREAD_MESSAGES_COUNT_UPDATE, [this]);
5128 }
5129 }
5130 /**
5131 * 当前用户在该对话的未读消息数
5132 * @type {Number}
5133 */
5134 ,
5135 get: function get() {
5136 return internal(this).unreadMessagesCount;
5137 }
5138 }, {
5139 key: "lastMessageAt",
5140 set: function set(value) {
5141 var time = decodeDate(value);
5142 if (time <= this._lastMessageAt) return;
5143 this._lastMessageAt = time;
5144 },
5145 get: function get() {
5146 return this._lastMessageAt;
5147 }
5148 /**
5149 * 最后消息送达时间,常用来实现消息的「已送达」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
5150 * @type {?Date}
5151 * @since 3.4.0
5152 */
5153
5154 }, {
5155 key: "lastDeliveredAt",
5156 get: function get() {
5157 if (this.members.length !== 2) return null;
5158 return internal(this).lastDeliveredAt;
5159 }
5160 }, {
5161 key: "lastReadAt",
5162 get: function get() {
5163 if (this.members.length !== 2) return null;
5164 return internal(this).lastReadAt;
5165 }
5166 }]);
5167
5168 return ConversationBase;
5169}(EventEmitter);
5170
5171var debug$8 = d('LC:SignatureFactoryRunner');
5172
5173function _validateSignature() {
5174 var signatureResult = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
5175 var signature = signatureResult.signature,
5176 timestamp = signatureResult.timestamp,
5177 nonce = signatureResult.nonce;
5178
5179 if (typeof signature !== 'string' || typeof timestamp !== 'number' || typeof nonce !== 'string') {
5180 throw new Error('malformed signature');
5181 }
5182
5183 return {
5184 signature: signature,
5185 timestamp: timestamp,
5186 nonce: nonce
5187 };
5188}
5189
5190var runSignatureFactory = (function (signatureFactory, params) {
5191 return Promise.resolve().then(function () {
5192 debug$8('call signatureFactory with %O', params);
5193 return signatureFactory.apply(void 0, _toConsumableArray(params));
5194 }).then(tap(function (signatureResult) {
5195 return debug$8('sign result %O', signatureResult);
5196 }), function (error) {
5197 // eslint-disable-next-line no-param-reassign
5198 error.message = "sign error: ".concat(error.message);
5199 debug$8(error);
5200 throw error;
5201 }).then(_validateSignature);
5202});
5203
5204function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
5205
5206function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
5207/**
5208 * 部分失败异常
5209 * @typedef OperationFailureError
5210 * @type {Error}
5211 * @property {string} message 异常信息
5212 * @property {string[]} clientIds 因为该原因失败的 client id 列表
5213 * @property {number} [code] 错误码
5214 * @property {string} [detail] 详细信息
5215 */
5216
5217/**
5218 * 部分成功的结果
5219 * @typedef PartiallySuccess
5220 * @type {Object}
5221 * @property {string[]} successfulClientIds 成功的 client id 列表
5222 * @property {OperationFailureError[]} failures 失败的异常列表
5223 */
5224
5225/**
5226 * 分页查询结果
5227 * @typedef PagedResults
5228 * @type {Object}
5229 * @property {T[]} results 查询结果
5230 * @property {string} [next] 存在表示还有更多结果,在下次查询中带上可实现翻页。
5231 */
5232
5233var createPartiallySuccess = function createPartiallySuccess(_ref) {
5234 var allowedPids = _ref.allowedPids,
5235 failedPids = _ref.failedPids;
5236 return {
5237 successfulClientIds: allowedPids,
5238 failures: failedPids.map(function (_ref2) {
5239 var pids = _ref2.pids,
5240 error = _objectWithoutProperties(_ref2, ["pids"]);
5241
5242 return Object.assign(createError(error), {
5243 clientIds: pids
5244 });
5245 })
5246 };
5247};
5248/**
5249 * @extends ConversationBase
5250 * @private
5251 * @abstract
5252 */
5253
5254
5255var PersistentConversation = /*#__PURE__*/function (_ConversationBase) {
5256 _inheritsLoose(PersistentConversation, _ConversationBase);
5257
5258 function PersistentConversation(data, _ref3, client) {
5259 var _this;
5260
5261 var creator = _ref3.creator,
5262 createdAt = _ref3.createdAt,
5263 updatedAt = _ref3.updatedAt,
5264 _ref3$transient = _ref3["transient"],
5265 _transient = _ref3$transient === void 0 ? false : _ref3$transient,
5266 _ref3$system = _ref3.system,
5267 system = _ref3$system === void 0 ? false : _ref3$system,
5268 _ref3$muted = _ref3.muted,
5269 muted = _ref3$muted === void 0 ? false : _ref3$muted,
5270 _ref3$mutedMembers = _ref3.mutedMembers,
5271 mutedMembers = _ref3$mutedMembers === void 0 ? [] : _ref3$mutedMembers,
5272 attributes = _objectWithoutProperties(_ref3, ["creator", "createdAt", "updatedAt", "transient", "system", "muted", "mutedMembers"]);
5273
5274 _this = _ConversationBase.call(this, _objectSpread$6(_objectSpread$6({}, data), {}, {
5275 /**
5276 * 对话创建者
5277 * @memberof PersistentConversation#
5278 * @type {String}
5279 */
5280 creator: creator,
5281
5282 /**
5283 * 对话创建时间
5284 * @memberof PersistentConversation#
5285 * @type {Date}
5286 */
5287 createdAt: createdAt,
5288
5289 /**
5290 * 对话更新时间
5291 * @memberof PersistentConversation#
5292 * @type {Date}
5293 */
5294 updatedAt: updatedAt,
5295
5296 /**
5297 * 对该对话设置了静音的用户列表
5298 * @memberof PersistentConversation#
5299 * @type {?String[]}
5300 */
5301 mutedMembers: mutedMembers,
5302
5303 /**
5304 * 暂态对话标记
5305 * @memberof PersistentConversation#
5306 * @type {Boolean}
5307 */
5308 "transient": _transient,
5309
5310 /**
5311 * 系统对话标记
5312 * @memberof PersistentConversation#
5313 * @type {Boolean}
5314 * @since 3.3.0
5315 */
5316 system: system,
5317
5318 /**
5319 * 当前用户静音该对话标记
5320 * @memberof PersistentConversation#
5321 * @type {Boolean}
5322 */
5323 muted: muted,
5324 _attributes: attributes
5325 }), client) || this;
5326
5327 _this._reset();
5328
5329 return _this;
5330 }
5331
5332 var _proto = PersistentConversation.prototype;
5333
5334 /**
5335 * 获取对话的自定义属性
5336 * @since 3.2.0
5337 * @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
5338 * @return {Any} 属性的值
5339 */
5340 _proto.get = function get(key) {
5341 return _get(internal(this).currentAttributes, key);
5342 }
5343 /**
5344 * 设置对话的自定义属性
5345 * @since 3.2.0
5346 * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
5347 * @param {Any} value 属性的值
5348 * @return {this} self
5349 * @example
5350 *
5351 * // 设置对话的 color 属性
5352 * conversation.set('color', {
5353 * text: '#000',
5354 * background: '#DDD',
5355 * });
5356 * // 设置对话的 color.text 属性
5357 * conversation.set('color.text', '#333');
5358 */
5359 ;
5360
5361 _proto.set = function set(key, value) {
5362 this._debug("set [".concat(key, "]: ").concat(value));
5363
5364 var _internal = internal(this),
5365 pendingAttributes = _internal.pendingAttributes;
5366
5367 var pendingKeys = Object.keys(pendingAttributes); // suppose pendingAttributes = { 'a.b': {} }
5368 // set 'a' or 'a.b': delete 'a.b'
5369
5370 var re = new RegExp("^".concat(key));
5371 var childKeys = pendingKeys.filter(re.test.bind(re));
5372 childKeys.forEach(function (k) {
5373 delete pendingAttributes[k];
5374 });
5375
5376 if (childKeys.length) {
5377 pendingAttributes[key] = value;
5378 } else {
5379 // set 'a.c': nothing to do
5380 // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
5381 var parentKey = find(pendingKeys, function (k) {
5382 return key.indexOf(k) === 0;
5383 }); // 'a.b'
5384
5385 if (parentKey) {
5386 setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
5387 } else {
5388 pendingAttributes[key] = value;
5389 }
5390 }
5391
5392 this._buildCurrentAttributes();
5393
5394 return this;
5395 };
5396
5397 _proto._buildCurrentAttributes = function _buildCurrentAttributes() {
5398 var _internal2 = internal(this),
5399 pendingAttributes = _internal2.pendingAttributes;
5400
5401 internal(this).currentAttributes = Object.keys(pendingAttributes).reduce(function (target, k) {
5402 return setValue(target, k, pendingAttributes[k]);
5403 }, cloneDeep(this._attributes));
5404 };
5405
5406 _proto._updateServerAttributes = function _updateServerAttributes(attributes) {
5407 var _this2 = this;
5408
5409 Object.keys(attributes).forEach(function (key) {
5410 return setValue(_this2._attributes, key, attributes[key]);
5411 });
5412
5413 this._buildCurrentAttributes();
5414 };
5415
5416 _proto._reset = function _reset() {
5417 Object.assign(internal(this), {
5418 pendingAttributes: {},
5419 currentAttributes: this._attributes
5420 });
5421 }
5422 /**
5423 * 保存当前对话的属性至服务器
5424 * @return {Promise.<this>} self
5425 */
5426 ;
5427
5428 _proto.save =
5429 /*#__PURE__*/
5430 function () {
5431 var _save = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
5432 var attr, convMessage, resCommand;
5433 return _regeneratorRuntime.wrap(function _callee$(_context) {
5434 while (1) {
5435 switch (_context.prev = _context.next) {
5436 case 0:
5437 this._debug('save');
5438
5439 attr = internal(this).pendingAttributes;
5440
5441 if (!isEmpty(attr)) {
5442 _context.next = 5;
5443 break;
5444 }
5445
5446 this._debug('nothing touched, resolve with self');
5447
5448 return _context.abrupt("return", this);
5449
5450 case 5:
5451 this._debug('attr: %O', attr);
5452
5453 convMessage = new ConvCommand({
5454 attr: new JsonObjectMessage({
5455 data: JSON.stringify(encode(attr))
5456 })
5457 });
5458 _context.next = 9;
5459 return this._send(new GenericCommand({
5460 op: 'update',
5461 convMessage: convMessage
5462 }));
5463
5464 case 9:
5465 resCommand = _context.sent;
5466 this.updatedAt = resCommand.convMessage.udate;
5467 this._attributes = internal(this).currentAttributes;
5468 internal(this).pendingAttributes = {};
5469 return _context.abrupt("return", this);
5470
5471 case 14:
5472 case "end":
5473 return _context.stop();
5474 }
5475 }
5476 }, _callee, this);
5477 }));
5478
5479 function save() {
5480 return _save.apply(this, arguments);
5481 }
5482
5483 return save;
5484 }()
5485 /**
5486 * 从服务器更新对话的属性
5487 * @return {Promise.<this>} self
5488 */
5489 ;
5490
5491 _proto.fetch =
5492 /*#__PURE__*/
5493 function () {
5494 var _fetch = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
5495 var query;
5496 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
5497 while (1) {
5498 switch (_context2.prev = _context2.next) {
5499 case 0:
5500 query = this._client.getQuery().equalTo('objectId', this.id);
5501 _context2.next = 3;
5502 return query.find();
5503
5504 case 3:
5505 return _context2.abrupt("return", this);
5506
5507 case 4:
5508 case "end":
5509 return _context2.stop();
5510 }
5511 }
5512 }, _callee2, this);
5513 }));
5514
5515 function fetch() {
5516 return _fetch.apply(this, arguments);
5517 }
5518
5519 return fetch;
5520 }()
5521 /**
5522 * 静音,客户端拒绝收到服务器端的离线推送通知
5523 * @return {Promise.<this>} self
5524 */
5525 ;
5526
5527 _proto.mute =
5528 /*#__PURE__*/
5529 function () {
5530 var _mute = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
5531 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
5532 while (1) {
5533 switch (_context3.prev = _context3.next) {
5534 case 0:
5535 this._debug('mute');
5536
5537 _context3.next = 3;
5538 return this._send(new GenericCommand({
5539 op: 'mute'
5540 }));
5541
5542 case 3:
5543 if (!this["transient"]) {
5544 this.muted = true;
5545 this.mutedMembers = union(this.mutedMembers, [this._client.id]);
5546 }
5547
5548 return _context3.abrupt("return", this);
5549
5550 case 5:
5551 case "end":
5552 return _context3.stop();
5553 }
5554 }
5555 }, _callee3, this);
5556 }));
5557
5558 function mute() {
5559 return _mute.apply(this, arguments);
5560 }
5561
5562 return mute;
5563 }()
5564 /**
5565 * 取消静音
5566 * @return {Promise.<this>} self
5567 */
5568 ;
5569
5570 _proto.unmute =
5571 /*#__PURE__*/
5572 function () {
5573 var _unmute = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
5574 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
5575 while (1) {
5576 switch (_context4.prev = _context4.next) {
5577 case 0:
5578 this._debug('unmute');
5579
5580 _context4.next = 3;
5581 return this._send(new GenericCommand({
5582 op: 'unmute'
5583 }));
5584
5585 case 3:
5586 if (!this["transient"]) {
5587 this.muted = false;
5588 this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
5589 }
5590
5591 return _context4.abrupt("return", this);
5592
5593 case 5:
5594 case "end":
5595 return _context4.stop();
5596 }
5597 }
5598 }, _callee4, this);
5599 }));
5600
5601 function unmute() {
5602 return _unmute.apply(this, arguments);
5603 }
5604
5605 return unmute;
5606 }();
5607
5608 _proto._appendConversationSignature = /*#__PURE__*/function () {
5609 var _appendConversationSignature2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(command, action, clientIds) {
5610 var params, signatureResult;
5611 return _regeneratorRuntime.wrap(function _callee5$(_context5) {
5612 while (1) {
5613 switch (_context5.prev = _context5.next) {
5614 case 0:
5615 if (!this._client.options.conversationSignatureFactory) {
5616 _context5.next = 6;
5617 break;
5618 }
5619
5620 params = [this.id, this._client.id, clientIds.sort(), action];
5621 _context5.next = 4;
5622 return runSignatureFactory(this._client.options.conversationSignatureFactory, params);
5623
5624 case 4:
5625 signatureResult = _context5.sent;
5626 Object.assign(command.convMessage, keyRemap({
5627 signature: 's',
5628 timestamp: 't',
5629 nonce: 'n'
5630 }, signatureResult));
5631
5632 case 6:
5633 case "end":
5634 return _context5.stop();
5635 }
5636 }
5637 }, _callee5, this);
5638 }));
5639
5640 function _appendConversationSignature(_x, _x2, _x3) {
5641 return _appendConversationSignature2.apply(this, arguments);
5642 }
5643
5644 return _appendConversationSignature;
5645 }();
5646
5647 _proto._appendBlacklistSignature = /*#__PURE__*/function () {
5648 var _appendBlacklistSignature2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(command, action, clientIds) {
5649 var params, signatureResult;
5650 return _regeneratorRuntime.wrap(function _callee6$(_context6) {
5651 while (1) {
5652 switch (_context6.prev = _context6.next) {
5653 case 0:
5654 if (!this._client.options.blacklistSignatureFactory) {
5655 _context6.next = 6;
5656 break;
5657 }
5658
5659 params = [this.id, this._client.id, clientIds.sort(), action];
5660 _context6.next = 4;
5661 return runSignatureFactory(this._client.options.blacklistSignatureFactory, params);
5662
5663 case 4:
5664 signatureResult = _context6.sent;
5665 Object.assign(command.blacklistMessage, keyRemap({
5666 signature: 's',
5667 timestamp: 't',
5668 nonce: 'n'
5669 }, signatureResult));
5670
5671 case 6:
5672 case "end":
5673 return _context6.stop();
5674 }
5675 }
5676 }, _callee6, this);
5677 }));
5678
5679 function _appendBlacklistSignature(_x4, _x5, _x6) {
5680 return _appendBlacklistSignature2.apply(this, arguments);
5681 }
5682
5683 return _appendBlacklistSignature;
5684 }()
5685 /**
5686 * 增加成员
5687 * @param {String|String[]} clientIds 新增成员 client id
5688 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
5689 */
5690 ;
5691
5692 _proto.add =
5693 /*#__PURE__*/
5694 function () {
5695 var _add = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(clientIds) {
5696 var command, _yield$this$_send, convMessage, allowedPids;
5697
5698 return _regeneratorRuntime.wrap(function _callee7$(_context7) {
5699 while (1) {
5700 switch (_context7.prev = _context7.next) {
5701 case 0:
5702 this._debug('add', clientIds);
5703
5704 if (typeof clientIds === 'string') {
5705 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
5706 }
5707
5708 command = new GenericCommand({
5709 op: 'add',
5710 convMessage: new ConvCommand({
5711 m: clientIds
5712 })
5713 });
5714 _context7.next = 5;
5715 return this._appendConversationSignature(command, 'invite', clientIds);
5716
5717 case 5:
5718 _context7.next = 7;
5719 return this._send(command);
5720
5721 case 7:
5722 _yield$this$_send = _context7.sent;
5723 convMessage = _yield$this$_send.convMessage;
5724 allowedPids = _yield$this$_send.convMessage.allowedPids;
5725
5726 this._addMembers(allowedPids);
5727
5728 return _context7.abrupt("return", createPartiallySuccess(convMessage));
5729
5730 case 12:
5731 case "end":
5732 return _context7.stop();
5733 }
5734 }
5735 }, _callee7, this);
5736 }));
5737
5738 function add(_x7) {
5739 return _add.apply(this, arguments);
5740 }
5741
5742 return add;
5743 }()
5744 /**
5745 * 剔除成员
5746 * @param {String|String[]} clientIds 成员 client id
5747 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
5748 */
5749 ;
5750
5751 _proto.remove =
5752 /*#__PURE__*/
5753 function () {
5754 var _remove = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(clientIds) {
5755 var command, _yield$this$_send2, convMessage, allowedPids;
5756
5757 return _regeneratorRuntime.wrap(function _callee8$(_context8) {
5758 while (1) {
5759 switch (_context8.prev = _context8.next) {
5760 case 0:
5761 this._debug('remove', clientIds);
5762
5763 if (typeof clientIds === 'string') {
5764 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
5765 }
5766
5767 command = new GenericCommand({
5768 op: 'remove',
5769 convMessage: new ConvCommand({
5770 m: clientIds
5771 })
5772 });
5773 _context8.next = 5;
5774 return this._appendConversationSignature(command, 'kick', clientIds);
5775
5776 case 5:
5777 _context8.next = 7;
5778 return this._send(command);
5779
5780 case 7:
5781 _yield$this$_send2 = _context8.sent;
5782 convMessage = _yield$this$_send2.convMessage;
5783 allowedPids = _yield$this$_send2.convMessage.allowedPids;
5784
5785 this._removeMembers(allowedPids);
5786
5787 return _context8.abrupt("return", createPartiallySuccess(convMessage));
5788
5789 case 12:
5790 case "end":
5791 return _context8.stop();
5792 }
5793 }
5794 }, _callee8, this);
5795 }));
5796
5797 function remove(_x8) {
5798 return _remove.apply(this, arguments);
5799 }
5800
5801 return remove;
5802 }()
5803 /**
5804 * (当前用户)加入该对话
5805 * @return {Promise.<this>} self
5806 */
5807 ;
5808
5809 _proto.join =
5810 /*#__PURE__*/
5811 function () {
5812 var _join = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9() {
5813 var _this3 = this;
5814
5815 return _regeneratorRuntime.wrap(function _callee9$(_context9) {
5816 while (1) {
5817 switch (_context9.prev = _context9.next) {
5818 case 0:
5819 this._debug('join');
5820
5821 return _context9.abrupt("return", this.add(this._client.id).then(function (_ref4) {
5822 var failures = _ref4.failures;
5823 if (failures[0]) throw failures[0];
5824 return _this3;
5825 }));
5826
5827 case 2:
5828 case "end":
5829 return _context9.stop();
5830 }
5831 }
5832 }, _callee9, this);
5833 }));
5834
5835 function join() {
5836 return _join.apply(this, arguments);
5837 }
5838
5839 return join;
5840 }()
5841 /**
5842 * (当前用户)退出该对话
5843 * @return {Promise.<this>} self
5844 */
5845 ;
5846
5847 _proto.quit =
5848 /*#__PURE__*/
5849 function () {
5850 var _quit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
5851 var _this4 = this;
5852
5853 return _regeneratorRuntime.wrap(function _callee10$(_context10) {
5854 while (1) {
5855 switch (_context10.prev = _context10.next) {
5856 case 0:
5857 this._debug('quit');
5858
5859 return _context10.abrupt("return", this.remove(this._client.id).then(function (_ref5) {
5860 var failures = _ref5.failures;
5861 if (failures[0]) throw failures[0];
5862 return _this4;
5863 }));
5864
5865 case 2:
5866 case "end":
5867 return _context10.stop();
5868 }
5869 }
5870 }, _callee10, this);
5871 }));
5872
5873 function quit() {
5874 return _quit.apply(this, arguments);
5875 }
5876
5877 return quit;
5878 }()
5879 /**
5880 * 在该对话中禁言成员
5881 * @param {String|String[]} clientIds 成员 client id
5882 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
5883 */
5884 ;
5885
5886 _proto.muteMembers =
5887 /*#__PURE__*/
5888 function () {
5889 var _muteMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(clientIds) {
5890 var command, _yield$this$_send3, convMessage;
5891
5892 return _regeneratorRuntime.wrap(function _callee11$(_context11) {
5893 while (1) {
5894 switch (_context11.prev = _context11.next) {
5895 case 0:
5896 this._debug('mute', clientIds);
5897
5898 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
5899
5900 command = new GenericCommand({
5901 op: OpType.add_shutup,
5902 convMessage: new ConvCommand({
5903 m: clientIds
5904 })
5905 });
5906 _context11.next = 5;
5907 return this._send(command);
5908
5909 case 5:
5910 _yield$this$_send3 = _context11.sent;
5911 convMessage = _yield$this$_send3.convMessage;
5912 return _context11.abrupt("return", createPartiallySuccess(convMessage));
5913
5914 case 8:
5915 case "end":
5916 return _context11.stop();
5917 }
5918 }
5919 }, _callee11, this);
5920 }));
5921
5922 function muteMembers(_x9) {
5923 return _muteMembers.apply(this, arguments);
5924 }
5925
5926 return muteMembers;
5927 }()
5928 /**
5929 * 在该对话中解除成员禁言
5930 * @param {String|String[]} clientIds 成员 client id
5931 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
5932 */
5933 ;
5934
5935 _proto.unmuteMembers =
5936 /*#__PURE__*/
5937 function () {
5938 var _unmuteMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(clientIds) {
5939 var command, _yield$this$_send4, convMessage;
5940
5941 return _regeneratorRuntime.wrap(function _callee12$(_context12) {
5942 while (1) {
5943 switch (_context12.prev = _context12.next) {
5944 case 0:
5945 this._debug('unmute', clientIds);
5946
5947 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
5948
5949 command = new GenericCommand({
5950 op: OpType.remove_shutup,
5951 convMessage: new ConvCommand({
5952 m: clientIds
5953 })
5954 });
5955 _context12.next = 5;
5956 return this._send(command);
5957
5958 case 5:
5959 _yield$this$_send4 = _context12.sent;
5960 convMessage = _yield$this$_send4.convMessage;
5961 return _context12.abrupt("return", createPartiallySuccess(convMessage));
5962
5963 case 8:
5964 case "end":
5965 return _context12.stop();
5966 }
5967 }
5968 }, _callee12, this);
5969 }));
5970
5971 function unmuteMembers(_x10) {
5972 return _unmuteMembers.apply(this, arguments);
5973 }
5974
5975 return unmuteMembers;
5976 }()
5977 /**
5978 * 查询该对话禁言成员列表
5979 * @param {Object} [options]
5980 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
5981 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
5982 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
5983 */
5984 ;
5985
5986 _proto.queryMutedMembers =
5987 /*#__PURE__*/
5988 function () {
5989 var _queryMutedMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13() {
5990 var _ref6,
5991 limit,
5992 next,
5993 command,
5994 _yield$this$_send5,
5995 _yield$this$_send5$co,
5996 m,
5997 newNext,
5998 _args13 = arguments;
5999
6000 return _regeneratorRuntime.wrap(function _callee13$(_context13) {
6001 while (1) {
6002 switch (_context13.prev = _context13.next) {
6003 case 0:
6004 _ref6 = _args13.length > 0 && _args13[0] !== undefined ? _args13[0] : {}, limit = _ref6.limit, next = _ref6.next;
6005
6006 this._debug('query muted: limit %O, next: %O', limit, next);
6007
6008 command = new GenericCommand({
6009 op: OpType.query_shutup,
6010 convMessage: new ConvCommand({
6011 limit: limit,
6012 next: next
6013 })
6014 });
6015 _context13.next = 5;
6016 return this._send(command);
6017
6018 case 5:
6019 _yield$this$_send5 = _context13.sent;
6020 _yield$this$_send5$co = _yield$this$_send5.convMessage;
6021 m = _yield$this$_send5$co.m;
6022 newNext = _yield$this$_send5$co.next;
6023 return _context13.abrupt("return", {
6024 results: m,
6025 next: newNext
6026 });
6027
6028 case 10:
6029 case "end":
6030 return _context13.stop();
6031 }
6032 }
6033 }, _callee13, this);
6034 }));
6035
6036 function queryMutedMembers() {
6037 return _queryMutedMembers.apply(this, arguments);
6038 }
6039
6040 return queryMutedMembers;
6041 }()
6042 /**
6043 * 将用户加入该对话黑名单
6044 * @param {String|String[]} clientIds 成员 client id
6045 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
6046 */
6047 ;
6048
6049 _proto.blockMembers =
6050 /*#__PURE__*/
6051 function () {
6052 var _blockMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(clientIds) {
6053 var command, _yield$this$_send6, blacklistMessage;
6054
6055 return _regeneratorRuntime.wrap(function _callee14$(_context14) {
6056 while (1) {
6057 switch (_context14.prev = _context14.next) {
6058 case 0:
6059 this._debug('block', clientIds);
6060
6061 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
6062
6063 command = new GenericCommand({
6064 cmd: 'blacklist',
6065 op: OpType.block,
6066 blacklistMessage: new BlacklistCommand({
6067 srcCid: this.id,
6068 toPids: clientIds
6069 })
6070 });
6071 _context14.next = 5;
6072 return this._appendBlacklistSignature(command, 'conversation-block-clients', clientIds);
6073
6074 case 5:
6075 _context14.next = 7;
6076 return this._send(command);
6077
6078 case 7:
6079 _yield$this$_send6 = _context14.sent;
6080 blacklistMessage = _yield$this$_send6.blacklistMessage;
6081 return _context14.abrupt("return", createPartiallySuccess(blacklistMessage));
6082
6083 case 10:
6084 case "end":
6085 return _context14.stop();
6086 }
6087 }
6088 }, _callee14, this);
6089 }));
6090
6091 function blockMembers(_x11) {
6092 return _blockMembers.apply(this, arguments);
6093 }
6094
6095 return blockMembers;
6096 }()
6097 /**
6098 * 将用户移出该对话黑名单
6099 * @param {String|String[]} clientIds 成员 client id
6100 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
6101 */
6102 ;
6103
6104 _proto.unblockMembers =
6105 /*#__PURE__*/
6106 function () {
6107 var _unblockMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(clientIds) {
6108 var command, _yield$this$_send7, blacklistMessage;
6109
6110 return _regeneratorRuntime.wrap(function _callee15$(_context15) {
6111 while (1) {
6112 switch (_context15.prev = _context15.next) {
6113 case 0:
6114 this._debug('unblock', clientIds);
6115
6116 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
6117
6118 command = new GenericCommand({
6119 cmd: 'blacklist',
6120 op: OpType.unblock,
6121 blacklistMessage: new BlacklistCommand({
6122 srcCid: this.id,
6123 toPids: clientIds
6124 })
6125 });
6126 _context15.next = 5;
6127 return this._appendBlacklistSignature(command, 'conversation-unblock-clients', clientIds);
6128
6129 case 5:
6130 _context15.next = 7;
6131 return this._send(command);
6132
6133 case 7:
6134 _yield$this$_send7 = _context15.sent;
6135 blacklistMessage = _yield$this$_send7.blacklistMessage;
6136 return _context15.abrupt("return", createPartiallySuccess(blacklistMessage));
6137
6138 case 10:
6139 case "end":
6140 return _context15.stop();
6141 }
6142 }
6143 }, _callee15, this);
6144 }));
6145
6146 function unblockMembers(_x12) {
6147 return _unblockMembers.apply(this, arguments);
6148 }
6149
6150 return unblockMembers;
6151 }()
6152 /**
6153 * 查询该对话黑名单
6154 * @param {Object} [options]
6155 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
6156 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
6157 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
6158 */
6159 ;
6160
6161 _proto.queryBlockedMembers =
6162 /*#__PURE__*/
6163 function () {
6164 var _queryBlockedMembers = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() {
6165 var _ref7,
6166 limit,
6167 next,
6168 command,
6169 _yield$this$_send8,
6170 _yield$this$_send8$bl,
6171 blockedPids,
6172 newNext,
6173 _args16 = arguments;
6174
6175 return _regeneratorRuntime.wrap(function _callee16$(_context16) {
6176 while (1) {
6177 switch (_context16.prev = _context16.next) {
6178 case 0:
6179 _ref7 = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : {}, limit = _ref7.limit, next = _ref7.next;
6180
6181 this._debug('query blocked: limit %O, next: %O', limit, next);
6182
6183 command = new GenericCommand({
6184 cmd: 'blacklist',
6185 op: OpType.query,
6186 blacklistMessage: new BlacklistCommand({
6187 srcCid: this.id,
6188 limit: limit,
6189 next: next
6190 })
6191 });
6192 _context16.next = 5;
6193 return this._send(command);
6194
6195 case 5:
6196 _yield$this$_send8 = _context16.sent;
6197 _yield$this$_send8$bl = _yield$this$_send8.blacklistMessage;
6198 blockedPids = _yield$this$_send8$bl.blockedPids;
6199 newNext = _yield$this$_send8$bl.next;
6200 return _context16.abrupt("return", {
6201 results: blockedPids,
6202 next: newNext
6203 });
6204
6205 case 10:
6206 case "end":
6207 return _context16.stop();
6208 }
6209 }
6210 }, _callee16, this);
6211 }));
6212
6213 function queryBlockedMembers() {
6214 return _queryBlockedMembers.apply(this, arguments);
6215 }
6216
6217 return queryBlockedMembers;
6218 }();
6219
6220 _proto.toFullJSON = function toFullJSON() {
6221 var creator = this.creator,
6222 system = this.system,
6223 _transient2 = this["transient"],
6224 createdAt = this.createdAt,
6225 updatedAt = this.updatedAt,
6226 _attributes = this._attributes;
6227 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
6228 creator: creator,
6229 system: system,
6230 "transient": _transient2,
6231 createdAt: getTime(createdAt),
6232 updatedAt: getTime(updatedAt)
6233 }, _attributes);
6234 };
6235
6236 _proto.toJSON = function toJSON() {
6237 var creator = this.creator,
6238 system = this.system,
6239 _transient3 = this["transient"],
6240 muted = this.muted,
6241 mutedMembers = this.mutedMembers,
6242 createdAt = this.createdAt,
6243 updatedAt = this.updatedAt,
6244 _attributes = this._attributes;
6245 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
6246 creator: creator,
6247 system: system,
6248 "transient": _transient3,
6249 muted: muted,
6250 mutedMembers: mutedMembers,
6251 createdAt: createdAt,
6252 updatedAt: updatedAt
6253 }, _attributes);
6254 };
6255
6256 _createClass(PersistentConversation, [{
6257 key: "createdAt",
6258 set: function set(value) {
6259 this._createdAt = decodeDate(value);
6260 },
6261 get: function get() {
6262 return this._createdAt;
6263 }
6264 }, {
6265 key: "updatedAt",
6266 set: function set(value) {
6267 this._updatedAt = decodeDate(value);
6268 },
6269 get: function get() {
6270 return this._updatedAt;
6271 }
6272 /**
6273 * 对话名字,对应 _Conversation 表中的 name
6274 * @type {String}
6275 */
6276
6277 }, {
6278 key: "name",
6279 get: function get() {
6280 return this.get('name');
6281 },
6282 set: function set(value) {
6283 this.set('name', value);
6284 }
6285 }]);
6286
6287 return PersistentConversation;
6288}(ConversationBase);
6289
6290/**
6291 * 对话成员角色枚举
6292 * @enum {String}
6293 * @since 4.0.0
6294 * @memberof module:leancloud-realtime
6295 */
6296
6297var ConversationMemberRole = {
6298 /** 所有者 */
6299 OWNER: 'Owner',
6300
6301 /** 管理员 */
6302 MANAGER: 'Manager',
6303
6304 /** 成员 */
6305 MEMBER: 'Member'
6306};
6307Object.freeze(ConversationMemberRole);
6308
6309var ConversationMemberInfo = /*#__PURE__*/function () {
6310 /**
6311 * 对话成员属性,保存了成员与某个对话相关的属性,对应 _ConversationMemberInfo 表
6312 * @since 4.0.0
6313 */
6314 function ConversationMemberInfo(_ref) {
6315 var conversation = _ref.conversation,
6316 memberId = _ref.memberId,
6317 role = _ref.role;
6318 if (!conversation) throw new Error('conversation requried');
6319 if (!memberId) throw new Error('memberId requried');
6320 Object.assign(internal(this), {
6321 conversation: conversation,
6322 memberId: memberId,
6323 role: role
6324 });
6325 }
6326 /**
6327 * 对话 Id
6328 * @type {String}
6329 * @readonly
6330 */
6331
6332
6333 var _proto = ConversationMemberInfo.prototype;
6334
6335 _proto.toJSON = function toJSON() {
6336 var conversationId = this.conversationId,
6337 memberId = this.memberId,
6338 role = this.role,
6339 isOwner = this.isOwner;
6340 return {
6341 conversationId: conversationId,
6342 memberId: memberId,
6343 role: role,
6344 isOwner: isOwner
6345 };
6346 };
6347
6348 _createClass(ConversationMemberInfo, [{
6349 key: "conversationId",
6350 get: function get() {
6351 return internal(this).conversation.id;
6352 }
6353 /**
6354 * 成员 Id
6355 * @type {String}
6356 * @readonly
6357 */
6358
6359 }, {
6360 key: "memberId",
6361 get: function get() {
6362 return internal(this).memberId;
6363 }
6364 /**
6365 * 角色
6366 * @type {module:leancloud-realtime.ConversationMemberRole | String}
6367 * @readonly
6368 */
6369
6370 }, {
6371 key: "role",
6372 get: function get() {
6373 if (this.isOwner) return ConversationMemberRole.OWNER;
6374 return internal(this).role;
6375 }
6376 /**
6377 * 是否是管理员
6378 * @type {Boolean}
6379 * @readonly
6380 */
6381
6382 }, {
6383 key: "isOwner",
6384 get: function get() {
6385 return this.memberId === internal(this).conversation.creator;
6386 }
6387 }]);
6388
6389 return ConversationMemberInfo;
6390}();
6391
6392/**
6393 * 普通对话
6394 *
6395 * 无法直接实例化,请使用 {@link IMClient#createConversation} 创建新的普通对话。
6396 * @extends PersistentConversation
6397 * @public
6398 */
6399
6400var Conversation = /*#__PURE__*/function (_PersistentConversati) {
6401 _inheritsLoose(Conversation, _PersistentConversati);
6402
6403 function Conversation() {
6404 return _PersistentConversati.apply(this, arguments) || this;
6405 }
6406
6407 var _proto = Conversation.prototype;
6408
6409 _proto._addMembers = function _addMembers(members) {
6410 var _this = this;
6411
6412 _PersistentConversati.prototype._addMembers.call(this, members);
6413
6414 this.members = union(this.members, members);
6415
6416 var _internal = internal(this),
6417 memberInfoMap = _internal.memberInfoMap;
6418
6419 if (!memberInfoMap) return;
6420 members.forEach(function (memberId) {
6421 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
6422 conversation: _this,
6423 memberId: memberId,
6424 role: ConversationMemberRole.MEMBER
6425 });
6426 });
6427 };
6428
6429 _proto._removeMembers = function _removeMembers(members) {
6430 _PersistentConversati.prototype._removeMembers.call(this, members);
6431
6432 this.members = difference(this.members, members);
6433
6434 var _internal2 = internal(this),
6435 memberInfoMap = _internal2.memberInfoMap;
6436
6437 if (!memberInfoMap) return;
6438 members.forEach(function (memberId) {
6439 delete memberInfoMap[memberId];
6440 });
6441 };
6442
6443 _proto._fetchAllMemberInfo = /*#__PURE__*/function () {
6444 var _fetchAllMemberInfo2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
6445 var _this2 = this;
6446
6447 var response, memberInfos, memberInfoMap;
6448 return _regeneratorRuntime.wrap(function _callee$(_context) {
6449 while (1) {
6450 switch (_context.prev = _context.next) {
6451 case 0:
6452 _context.next = 2;
6453 return this._client._requestWithSessionToken({
6454 method: 'GET',
6455 path: '/classes/_ConversationMemberInfo',
6456 query: {
6457 where: {
6458 cid: this.id
6459 }
6460 }
6461 });
6462
6463 case 2:
6464 response = _context.sent;
6465 memberInfos = response.results.map(function (info) {
6466 return new ConversationMemberInfo({
6467 conversation: _this2,
6468 memberId: info.clientId,
6469 role: info.role
6470 });
6471 });
6472 memberInfoMap = {};
6473 memberInfos.forEach(function (memberInfo) {
6474 memberInfoMap[memberInfo.memberId] = memberInfo;
6475 });
6476 this.members.forEach(function (memberId) {
6477 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
6478 conversation: _this2,
6479 memberId: memberId,
6480 role: ConversationMemberRole.MEMBER
6481 });
6482 });
6483 internal(this).memberInfoMap = memberInfoMap;
6484 return _context.abrupt("return", memberInfoMap);
6485
6486 case 9:
6487 case "end":
6488 return _context.stop();
6489 }
6490 }
6491 }, _callee, this);
6492 }));
6493
6494 function _fetchAllMemberInfo() {
6495 return _fetchAllMemberInfo2.apply(this, arguments);
6496 }
6497
6498 return _fetchAllMemberInfo;
6499 }()
6500 /**
6501 * 获取所有成员的对话属性
6502 * @since 4.0.0
6503 * @return {Promise.<ConversationMemberInfo[]>} 所有成员的对话属性列表
6504 */
6505 ;
6506
6507 _proto.getAllMemberInfo =
6508 /*#__PURE__*/
6509 function () {
6510 var _getAllMemberInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
6511 var _ref,
6512 _ref$noCache,
6513 noCache,
6514 _internal3,
6515 memberInfoMap,
6516 _args2 = arguments;
6517
6518 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
6519 while (1) {
6520 switch (_context2.prev = _context2.next) {
6521 case 0:
6522 _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$noCache = _ref.noCache, noCache = _ref$noCache === void 0 ? false : _ref$noCache;
6523 _internal3 = internal(this), memberInfoMap = _internal3.memberInfoMap;
6524
6525 if (!(!memberInfoMap || noCache)) {
6526 _context2.next = 6;
6527 break;
6528 }
6529
6530 _context2.next = 5;
6531 return this._fetchAllMemberInfo();
6532
6533 case 5:
6534 memberInfoMap = _context2.sent;
6535
6536 case 6:
6537 return _context2.abrupt("return", this.members.map(function (memberId) {
6538 return memberInfoMap[memberId];
6539 }));
6540
6541 case 7:
6542 case "end":
6543 return _context2.stop();
6544 }
6545 }
6546 }, _callee2, this);
6547 }));
6548
6549 function getAllMemberInfo() {
6550 return _getAllMemberInfo.apply(this, arguments);
6551 }
6552
6553 return getAllMemberInfo;
6554 }()
6555 /**
6556 * 获取指定成员的对话属性
6557 * @since 4.0.0
6558 * @param {String} memberId 成员 Id
6559 * @return {Promise.<ConversationMemberInfo>} 指定成员的对话属性
6560 */
6561 ;
6562
6563 _proto.getMemberInfo =
6564 /*#__PURE__*/
6565 function () {
6566 var _getMemberInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(memberId) {
6567 var _internal4, memberInfoMap;
6568
6569 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
6570 while (1) {
6571 switch (_context3.prev = _context3.next) {
6572 case 0:
6573 if (!(this.members.indexOf(memberId) === -1)) {
6574 _context3.next = 2;
6575 break;
6576 }
6577
6578 throw new Error("".concat(memberId, " is not the mumber of conversation[").concat(this.id, "]"));
6579
6580 case 2:
6581 _internal4 = internal(this), memberInfoMap = _internal4.memberInfoMap;
6582
6583 if (memberInfoMap && memberInfoMap[memberId]) {
6584 _context3.next = 6;
6585 break;
6586 }
6587
6588 _context3.next = 6;
6589 return this.getAllMemberInfo();
6590
6591 case 6:
6592 return _context3.abrupt("return", internal(this).memberInfoMap[memberId]);
6593
6594 case 7:
6595 case "end":
6596 return _context3.stop();
6597 }
6598 }
6599 }, _callee3, this);
6600 }));
6601
6602 function getMemberInfo(_x) {
6603 return _getMemberInfo.apply(this, arguments);
6604 }
6605
6606 return getMemberInfo;
6607 }()
6608 /**
6609 * 更新指定用户的角色
6610 * @since 4.0.0
6611 * @param {String} memberId 成员 Id
6612 * @param {module:leancloud-realtime.ConversationMemberRole | String} role 角色
6613 * @return {Promise.<this>} self
6614 */
6615 ;
6616
6617 _proto.updateMemberRole =
6618 /*#__PURE__*/
6619 function () {
6620 var _updateMemberRole = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(memberId, role) {
6621 var _internal5, memberInfos;
6622
6623 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
6624 while (1) {
6625 switch (_context4.prev = _context4.next) {
6626 case 0:
6627 this._debug('update member role');
6628
6629 if (!(role === ConversationMemberRole.OWNER)) {
6630 _context4.next = 3;
6631 break;
6632 }
6633
6634 throw createError({
6635 code: ErrorCode.OWNER_PROMOTION_NOT_ALLOWED
6636 });
6637
6638 case 3:
6639 _context4.next = 5;
6640 return this._send(new GenericCommand({
6641 op: OpType.member_info_update,
6642 convMessage: new ConvCommand({
6643 targetClientId: memberId,
6644 info: new ConvMemberInfo({
6645 pid: memberId,
6646 role: role
6647 })
6648 })
6649 }));
6650
6651 case 5:
6652 _internal5 = internal(this), memberInfos = _internal5.memberInfos;
6653
6654 if (memberInfos && memberInfos[memberId]) {
6655 internal(memberInfos[memberId]).role = role;
6656 }
6657
6658 return _context4.abrupt("return", this);
6659
6660 case 8:
6661 case "end":
6662 return _context4.stop();
6663 }
6664 }
6665 }, _callee4, this);
6666 }));
6667
6668 function updateMemberRole(_x2, _x3) {
6669 return _updateMemberRole.apply(this, arguments);
6670 }
6671
6672 return updateMemberRole;
6673 }();
6674
6675 return Conversation;
6676}(PersistentConversation);
6677
6678/**
6679 * 聊天室。
6680 *
6681 * 无法直接实例化,请使用 {@link IMClient#createChatRoom} 创建新的聊天室。
6682 * @since 4.0.0
6683 * @extends PersistentConversation
6684 * @public
6685 */
6686
6687var ChatRoom = /*#__PURE__*/function (_PersistentConversati) {
6688 _inheritsLoose(ChatRoom, _PersistentConversati);
6689
6690 function ChatRoom() {
6691 return _PersistentConversati.apply(this, arguments) || this;
6692 }
6693
6694 return ChatRoom;
6695}(PersistentConversation);
6696
6697/**
6698 * 服务号。
6699 *
6700 * 服务号不支持在客户端创建。
6701 * @since 4.0.0
6702 * @extends PersistentConversation
6703 * @public
6704 */
6705
6706var ServiceConversation = /*#__PURE__*/function (_PersistentConversati) {
6707 _inheritsLoose(ServiceConversation, _PersistentConversati);
6708
6709 function ServiceConversation() {
6710 return _PersistentConversati.apply(this, arguments) || this;
6711 }
6712
6713 var _proto = ServiceConversation.prototype;
6714
6715 /**
6716 * 订阅该服务号
6717 * @return {Promise.<this>} self
6718 */
6719 _proto.subscribe =
6720 /*#__PURE__*/
6721 function () {
6722 var _subscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
6723 return _regeneratorRuntime.wrap(function _callee$(_context) {
6724 while (1) {
6725 switch (_context.prev = _context.next) {
6726 case 0:
6727 return _context.abrupt("return", this.join());
6728
6729 case 1:
6730 case "end":
6731 return _context.stop();
6732 }
6733 }
6734 }, _callee, this);
6735 }));
6736
6737 function subscribe() {
6738 return _subscribe.apply(this, arguments);
6739 }
6740
6741 return subscribe;
6742 }()
6743 /**
6744 * 退订该服务号
6745 * @return {Promise.<this>} self
6746 */
6747 ;
6748
6749 _proto.unsubscribe =
6750 /*#__PURE__*/
6751 function () {
6752 var _unsubscribe = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
6753 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
6754 while (1) {
6755 switch (_context2.prev = _context2.next) {
6756 case 0:
6757 return _context2.abrupt("return", this.quit());
6758
6759 case 1:
6760 case "end":
6761 return _context2.stop();
6762 }
6763 }
6764 }, _callee2, this);
6765 }));
6766
6767 function unsubscribe() {
6768 return _unsubscribe.apply(this, arguments);
6769 }
6770
6771 return unsubscribe;
6772 }();
6773
6774 return ServiceConversation;
6775}(PersistentConversation);
6776
6777function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
6778
6779function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
6780
6781var transformNotFoundError = function transformNotFoundError(error) {
6782 return error.code === ErrorCode.CONVERSATION_NOT_FOUND ? createError({
6783 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
6784 }) : error;
6785};
6786/**
6787 * 临时对话
6788 * @since 4.0.0
6789 * @extends ConversationBase
6790 * @public
6791 */
6792
6793
6794var TemporaryConversation = /*#__PURE__*/function (_ConversationBase) {
6795 _inheritsLoose(TemporaryConversation, _ConversationBase);
6796
6797 /**
6798 * 无法直接实例化,请使用 {@link IMClient#createTemporaryConversation} 创建新的临时对话。
6799 */
6800 function TemporaryConversation(data, _ref, client) {
6801 var expiredAt = _ref.expiredAt;
6802 return _ConversationBase.call(this, _objectSpread$7(_objectSpread$7({}, data), {}, {
6803 expiredAt: expiredAt
6804 }), client) || this;
6805 }
6806 /**
6807 * 对话失效时间
6808 * @type {Date}
6809 */
6810
6811
6812 var _proto = TemporaryConversation.prototype;
6813
6814 _proto._send = /*#__PURE__*/function () {
6815 var _send2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
6816 var _ConversationBase$pro,
6817 _len,
6818 args,
6819 _key,
6820 _args = arguments;
6821
6822 return _regeneratorRuntime.wrap(function _callee$(_context) {
6823 while (1) {
6824 switch (_context.prev = _context.next) {
6825 case 0:
6826 if (!this.expired) {
6827 _context.next = 2;
6828 break;
6829 }
6830
6831 throw createError({
6832 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
6833 });
6834
6835 case 2:
6836 _context.prev = 2;
6837
6838 for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
6839 args[_key] = _args[_key];
6840 }
6841
6842 _context.next = 6;
6843 return (_ConversationBase$pro = _ConversationBase.prototype._send).call.apply(_ConversationBase$pro, [this].concat(args));
6844
6845 case 6:
6846 return _context.abrupt("return", _context.sent);
6847
6848 case 9:
6849 _context.prev = 9;
6850 _context.t0 = _context["catch"](2);
6851 throw transformNotFoundError(_context.t0);
6852
6853 case 12:
6854 case "end":
6855 return _context.stop();
6856 }
6857 }
6858 }, _callee, this, [[2, 9]]);
6859 }));
6860
6861 function _send() {
6862 return _send2.apply(this, arguments);
6863 }
6864
6865 return _send;
6866 }();
6867
6868 _proto.send = /*#__PURE__*/function () {
6869 var _send3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
6870 var _ConversationBase$pro2,
6871 _len2,
6872 args,
6873 _key2,
6874 _args2 = arguments;
6875
6876 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
6877 while (1) {
6878 switch (_context2.prev = _context2.next) {
6879 case 0:
6880 _context2.prev = 0;
6881
6882 for (_len2 = _args2.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
6883 args[_key2] = _args2[_key2];
6884 }
6885
6886 _context2.next = 4;
6887 return (_ConversationBase$pro2 = _ConversationBase.prototype.send).call.apply(_ConversationBase$pro2, [this].concat(args));
6888
6889 case 4:
6890 return _context2.abrupt("return", _context2.sent);
6891
6892 case 7:
6893 _context2.prev = 7;
6894 _context2.t0 = _context2["catch"](0);
6895 throw transformNotFoundError(_context2.t0);
6896
6897 case 10:
6898 case "end":
6899 return _context2.stop();
6900 }
6901 }
6902 }, _callee2, this, [[0, 7]]);
6903 }));
6904
6905 function send() {
6906 return _send3.apply(this, arguments);
6907 }
6908
6909 return send;
6910 }();
6911
6912 _proto.toFullJSON = function toFullJSON() {
6913 var expiredAt = this.expiredAt;
6914 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
6915 expiredAt: getTime(expiredAt)
6916 });
6917 };
6918
6919 _proto.toJSON = function toJSON() {
6920 var expiredAt = this.expiredAt,
6921 expired = this.expired;
6922 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
6923 expiredAt: expiredAt,
6924 expired: expired
6925 });
6926 };
6927
6928 _createClass(TemporaryConversation, [{
6929 key: "expiredAt",
6930 set: function set(value) {
6931 this._expiredAt = decodeDate(value);
6932 },
6933 get: function get() {
6934 return this._expiredAt;
6935 }
6936 /**
6937 * 对话是否已失效
6938 * @type {Boolean}
6939 */
6940
6941 }, {
6942 key: "expired",
6943 get: function get() {
6944 return this.expiredAt < new Date();
6945 }
6946 }]);
6947
6948 return TemporaryConversation;
6949}(ConversationBase);
6950
6951var debug$9 = d('LC:ConversationQuery');
6952
6953var ConversationQuery = /*#__PURE__*/function () {
6954 ConversationQuery._encode = function _encode(value) {
6955 if (value instanceof Date) {
6956 return {
6957 __type: 'Date',
6958 iso: value.toJSON()
6959 };
6960 }
6961
6962 if (value instanceof RegExp) {
6963 return value.source;
6964 }
6965
6966 return value;
6967 };
6968
6969 ConversationQuery._quote = function _quote(s) {
6970 return "\\Q".concat(s.replace('\\E', '\\E\\\\E\\Q'), "\\E");
6971 };
6972
6973 ConversationQuery._calculateFlag = function _calculateFlag(options) {
6974 return ['withLastMessagesRefreshed', 'compact'].reduce( // eslint-disable-next-line no-bitwise
6975 function (prev, key) {
6976 return (prev << 1) + Boolean(options[key]);
6977 }, 0);
6978 }
6979 /**
6980 * 构造一个用 AND 连接所有查询的 ConversationQuery
6981 * @param {...ConversationQuery} queries
6982 * @return {ConversationQuery}
6983 */
6984 ;
6985
6986 ConversationQuery.and = function and() {
6987 for (var _len = arguments.length, queries = new Array(_len), _key = 0; _key < _len; _key++) {
6988 queries[_key] = arguments[_key];
6989 }
6990
6991 if (queries.length < 2) {
6992 throw new Error('The queries must contain at least two elements');
6993 }
6994
6995 if (!queries.every(function (q) {
6996 return q instanceof ConversationQuery;
6997 })) {
6998 throw new Error('The element of queries must be an instance of ConversationQuery');
6999 }
7000
7001 var combined = new ConversationQuery(queries[0]._client);
7002 combined._where.$and = queries.map(function (q) {
7003 return q._where;
7004 });
7005 return combined;
7006 }
7007 /**
7008 * 构造一个用 OR 连接所有查询的 ConversationQuery
7009 * @param {...ConversationQuery} queries
7010 * @return {ConversationQuery}
7011 */
7012 ;
7013
7014 ConversationQuery.or = function or() {
7015 var combined = ConversationQuery.and.apply(ConversationQuery, arguments);
7016 combined._where.$or = combined._where.$and;
7017 delete combined._where.$and;
7018 return combined;
7019 }
7020 /**
7021 * Create a ConversationQuery
7022 * @param {IMClient} client
7023 */
7024 ;
7025
7026 function ConversationQuery(client) {
7027 this._client = client;
7028 this._where = {};
7029 this._extraOptions = {};
7030 }
7031
7032 var _proto = ConversationQuery.prototype;
7033
7034 _proto._addCondition = function _addCondition(key, condition, value) {
7035 // Check if we already have a condition
7036 if (!this._where[key]) {
7037 this._where[key] = {};
7038 }
7039
7040 this._where[key][condition] = this.constructor._encode(value);
7041 return this;
7042 };
7043
7044 _proto.toJSON = function toJSON() {
7045 var json = {
7046 where: this._where,
7047 flag: this.constructor._calculateFlag(this._extraOptions)
7048 };
7049 if (typeof this._skip !== 'undefined') json.skip = this._skip;
7050 if (typeof this._limit !== 'undefined') json.limit = this._limit;
7051 if (typeof this._order !== 'undefined') json.sort = this._order;
7052 debug$9(json);
7053 return json;
7054 }
7055 /**
7056 * 增加查询条件,指定聊天室的组员包含某些成员即可返回
7057 * @param {string[]} peerIds - 成员 ID 列表
7058 * @return {ConversationQuery} self
7059 */
7060 ;
7061
7062 _proto.containsMembers = function containsMembers(peerIds) {
7063 return this.containsAll('m', peerIds);
7064 }
7065 /**
7066 * 增加查询条件,指定聊天室的组员条件满足条件的才返回
7067 *
7068 * @param {string[]} - 成员 ID 列表
7069 * @param {Boolean} includeSelf - 是否包含自己
7070 * @return {ConversationQuery} self
7071 */
7072 ;
7073
7074 _proto.withMembers = function withMembers(peerIds, includeSelf) {
7075 var peerIdsSet = new Set(peerIds);
7076
7077 if (includeSelf) {
7078 peerIdsSet.add(this._client.id);
7079 }
7080
7081 this.sizeEqualTo('m', peerIdsSet.size);
7082 return this.containsMembers(Array.from(peerIdsSet));
7083 }
7084 /**
7085 * 增加查询条件,当 conversation 的属性中对应的字段满足等于条件时即可返回
7086 *
7087 * @param {string} key
7088 * @param value
7089 * @return {ConversationQuery} self
7090 */
7091 ;
7092
7093 _proto.equalTo = function equalTo(key, value) {
7094 this._where[key] = this.constructor._encode(value);
7095 return this;
7096 }
7097 /**
7098 * 增加查询条件,当 conversation 的属性中对应的字段满足小于条件时即可返回
7099 * @param {string} key
7100 * @param value
7101 * @return {ConversationQuery} self
7102 */
7103 ;
7104
7105 _proto.lessThan = function lessThan(key, value) {
7106 return this._addCondition(key, '$lt', value);
7107 }
7108 /**
7109 * 增加查询条件,当 conversation 的属性中对应的字段满足小于等于条件时即可返回
7110 * @param {string} key
7111 * @param value
7112 * @return {ConversationQuery} self
7113 */
7114 ;
7115
7116 _proto.lessThanOrEqualTo = function lessThanOrEqualTo(key, value) {
7117 return this._addCondition(key, '$lte', value);
7118 }
7119 /**
7120 * 增加查询条件,当 conversation 的属性中对应的字段满足大于条件时即可返回
7121 *
7122 * @param {string} key
7123 * @param value
7124 * @return {ConversationQuery} self
7125 */
7126 ;
7127
7128 _proto.greaterThan = function greaterThan(key, value) {
7129 return this._addCondition(key, '$gt', value);
7130 }
7131 /**
7132 * 增加查询条件,当 conversation 的属性中对应的字段满足大于等于条件时即可返回
7133 *
7134 * @param {string} key
7135 * @param value
7136 * @return {ConversationQuery} self
7137 */
7138 ;
7139
7140 _proto.greaterThanOrEqualTo = function greaterThanOrEqualTo(key, value) {
7141 return this._addCondition(key, '$gte', value);
7142 }
7143 /**
7144 * 增加查询条件,当 conversation 的属性中对应的字段满足不等于条件时即可返回
7145 *
7146 * @param {string} key
7147 * @param value
7148 * @return {ConversationQuery} self
7149 */
7150 ;
7151
7152 _proto.notEqualTo = function notEqualTo(key, value) {
7153 return this._addCondition(key, '$ne', value);
7154 }
7155 /**
7156 * 增加查询条件,当 conversation 存在指定的字段时即可返回
7157 *
7158 * @since 3.5.0
7159 * @param {string} key
7160 * @return {ConversationQuery} self
7161 */
7162 ;
7163
7164 _proto.exists = function exists(key) {
7165 return this._addCondition(key, '$exists', true);
7166 }
7167 /**
7168 * 增加查询条件,当 conversation 不存在指定的字段时即可返回
7169 *
7170 * @since 3.5.0
7171 * @param {string} key
7172 * @return {ConversationQuery} self
7173 */
7174 ;
7175
7176 _proto.doesNotExist = function doesNotExist(key) {
7177 return this._addCondition(key, '$exists', false);
7178 }
7179 /**
7180 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含在指定值中时即可返回
7181 *
7182 * @param {string} key
7183 * @param values
7184 * @return {ConversationQuery} self
7185 */
7186 ;
7187
7188 _proto.containedIn = function containedIn(key, values) {
7189 return this._addCondition(key, '$in', values);
7190 }
7191 /**
7192 * 增加查询条件,当 conversation 的属性中对应的字段对应的值不包含在指定值中时即可返回
7193 *
7194 * @param {string} key
7195 * @param values
7196 * @return {ConversationQuery} self
7197 */
7198 ;
7199
7200 _proto.notContainsIn = function notContainsIn(key, values) {
7201 return this._addCondition(key, '$nin', values);
7202 }
7203 /**
7204 * 增加查询条件,当conversation的属性中对应的字段中的元素包含所有的值才可返回
7205 *
7206 * @param {string} key
7207 * @param values
7208 * @return {ConversationQuery} self
7209 */
7210 ;
7211
7212 _proto.containsAll = function containsAll(key, values) {
7213 return this._addCondition(key, '$all', values);
7214 }
7215 /**
7216 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含此字符串即可返回
7217 *
7218 * @param {string} key
7219 * @param {string} subString
7220 * @return {ConversationQuery} self
7221 */
7222 ;
7223
7224 _proto.contains = function contains(key, subString) {
7225 return this._addCondition(key, '$regex', ConversationQuery._quote(subString));
7226 }
7227 /**
7228 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串起始即可返回
7229 *
7230 * @param {string} key
7231 * @param {string} prefix
7232 * @return {ConversationQuery} self
7233 */
7234 ;
7235
7236 _proto.startsWith = function startsWith(key, prefix) {
7237 return this._addCondition(key, '$regex', "^".concat(ConversationQuery._quote(prefix)));
7238 }
7239 /**
7240 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串结束即可返回
7241 *
7242 * @param {string} key
7243 * @param {string} suffix
7244 * @return {ConversationQuery} self
7245 */
7246 ;
7247
7248 _proto.endsWith = function endsWith(key, suffix) {
7249 return this._addCondition(key, '$regex', "".concat(ConversationQuery._quote(suffix), "$"));
7250 }
7251 /**
7252 * 增加查询条件,当 conversation 的属性中对应的字段对应的值满足提供的正则表达式即可返回
7253 *
7254 * @param {string} key
7255 * @param {RegExp} regex
7256 * @return {ConversationQuery} self
7257 */
7258 ;
7259
7260 _proto.matches = function matches(key, regex) {
7261 this._addCondition(key, '$regex', regex); // Javascript regex options support mig as inline options but store them
7262 // as properties of the object. We support mi & should migrate them to
7263 // modifiers
7264
7265
7266 var _modifiers = '';
7267
7268 if (regex.ignoreCase) {
7269 _modifiers += 'i';
7270 }
7271
7272 if (regex.multiline) {
7273 _modifiers += 'm';
7274 }
7275
7276 if (_modifiers && _modifiers.length) {
7277 this._addCondition(key, '$options', _modifiers);
7278 }
7279
7280 return this;
7281 }
7282 /**
7283 * 添加查询约束条件,查找 key 类型是数组,该数组的长度匹配提供的数值
7284 *
7285 * @param {string} key
7286 * @param {Number} length
7287 * @return {ConversationQuery} self
7288 */
7289 ;
7290
7291 _proto.sizeEqualTo = function sizeEqualTo(key, length) {
7292 return this._addCondition(key, '$size', length);
7293 }
7294 /**
7295 * 设置返回集合的大小上限
7296 *
7297 * @param {Number} limit - 上限
7298 * @return {ConversationQuery} self
7299 */
7300 ;
7301
7302 _proto.limit = function limit(_limit) {
7303 this._limit = _limit;
7304 return this;
7305 }
7306 /**
7307 * 设置返回集合的起始位置,一般用于分页
7308 *
7309 * @param {Number} skip - 起始位置跳过几个对象
7310 * @return {ConversationQuery} self
7311 */
7312 ;
7313
7314 _proto.skip = function skip(_skip) {
7315 this._skip = _skip;
7316 return this;
7317 }
7318 /**
7319 * 设置返回集合按照指定key进行增序排列
7320 *
7321 * @param {string} key
7322 * @return {ConversationQuery} self
7323 */
7324 ;
7325
7326 _proto.ascending = function ascending(key) {
7327 this._order = key;
7328 return this;
7329 }
7330 /**
7331 * 设置返回集合按照指定key进行增序排列,如果已设置其他排序,原排序的优先级较高
7332 *
7333 * @param {string} key
7334 * @return {ConversationQuery} self
7335 */
7336 ;
7337
7338 _proto.addAscending = function addAscending(key) {
7339 if (this._order) {
7340 this._order += ",".concat(key);
7341 } else {
7342 this._order = key;
7343 }
7344
7345 return this;
7346 }
7347 /**
7348 * 设置返回集合按照指定 key 进行降序排列
7349 *
7350 * @param {string} key
7351 * @return {ConversationQuery} self
7352 */
7353 ;
7354
7355 _proto.descending = function descending(key) {
7356 this._order = "-".concat(key);
7357 return this;
7358 }
7359 /**
7360 * 设置返回集合按照指定 key 进行降序排列,如果已设置其他排序,原排序的优先级较高
7361 *
7362 * @param {string} key
7363 * @return {ConversationQuery} self
7364 */
7365 ;
7366
7367 _proto.addDescending = function addDescending(key) {
7368 if (this._order) {
7369 this._order += ",-".concat(key);
7370 } else {
7371 this._order = "-".concat(key);
7372 }
7373
7374 return this;
7375 }
7376 /**
7377 * 设置返回的 conversations 刷新最后一条消息
7378 * @param {Boolean} [enabled=true]
7379 * @return {ConversationQuery} self
7380 */
7381 ;
7382
7383 _proto.withLastMessagesRefreshed = function withLastMessagesRefreshed() {
7384 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
7385 this._extraOptions.withLastMessagesRefreshed = enabled;
7386 return this;
7387 }
7388 /**
7389 * 设置返回的 conversations 为精简模式,即不含成员列表
7390 * @param {Boolean} [enabled=true]
7391 * @return {ConversationQuery} self
7392 */
7393 ;
7394
7395 _proto.compact = function compact() {
7396 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
7397 this._extraOptions.compact = enabled;
7398 return this;
7399 }
7400 /**
7401 * 执行查询
7402 * @return {Promise.<ConversationBase[]>}
7403 */
7404 ;
7405
7406 _proto.find =
7407 /*#__PURE__*/
7408 function () {
7409 var _find = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
7410 return _regeneratorRuntime.wrap(function _callee$(_context) {
7411 while (1) {
7412 switch (_context.prev = _context.next) {
7413 case 0:
7414 return _context.abrupt("return", this._client._executeQuery(this));
7415
7416 case 1:
7417 case "end":
7418 return _context.stop();
7419 }
7420 }
7421 }, _callee, this);
7422 }));
7423
7424 function find() {
7425 return _find.apply(this, arguments);
7426 }
7427
7428 return find;
7429 }()
7430 /**
7431 * 返回符合条件的第一个结果
7432 * @return {Promise.<ConversationBase>}
7433 */
7434 ;
7435
7436 _proto.first =
7437 /*#__PURE__*/
7438 function () {
7439 var _first = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
7440 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
7441 while (1) {
7442 switch (_context2.prev = _context2.next) {
7443 case 0:
7444 _context2.next = 2;
7445 return this.limit(1).find();
7446
7447 case 2:
7448 return _context2.abrupt("return", _context2.sent[0]);
7449
7450 case 3:
7451 case "end":
7452 return _context2.stop();
7453 }
7454 }
7455 }, _callee2, this);
7456 }));
7457
7458 function first() {
7459 return _first.apply(this, arguments);
7460 }
7461
7462 return first;
7463 }();
7464
7465 return ConversationQuery;
7466}();
7467
7468var debug$a = d('LC:SessionManager');
7469
7470var SessionManager = /*#__PURE__*/function () {
7471 function SessionManager() {
7472 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
7473 refresh = _ref.refresh,
7474 onBeforeGetSessionToken = _ref.onBeforeGetSessionToken;
7475
7476 this.refresh = refresh;
7477 this._onBeforeGetSessionToken = onBeforeGetSessionToken;
7478 this.setSessionToken(null, 0);
7479 }
7480
7481 var _proto = SessionManager.prototype;
7482
7483 _proto.setSessionToken = function setSessionToken(token, ttl) {
7484 debug$a('set session token', token, ttl);
7485 var sessionToken = new Expirable(token, ttl * 1000);
7486 this._sessionToken = sessionToken;
7487 delete this._pendingSessionTokenPromise;
7488 return sessionToken;
7489 };
7490
7491 _proto.setSessionTokenAsync = /*#__PURE__*/function () {
7492 var _setSessionTokenAsync = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(promise) {
7493 var _this = this;
7494
7495 var currentSessionToken;
7496 return _regeneratorRuntime.wrap(function _callee$(_context) {
7497 while (1) {
7498 switch (_context.prev = _context.next) {
7499 case 0:
7500 currentSessionToken = this._sessionToken;
7501 this._pendingSessionTokenPromise = promise["catch"](function (error) {
7502 // revert, otherwise the following getSessionToken calls
7503 // will all be rejected
7504 _this._sessionToken = currentSessionToken;
7505 throw error;
7506 });
7507 _context.t0 = this.setSessionToken;
7508 _context.t1 = this;
7509 _context.t2 = _toConsumableArray;
7510 _context.next = 7;
7511 return this._pendingSessionTokenPromise;
7512
7513 case 7:
7514 _context.t3 = _context.sent;
7515 _context.t4 = (0, _context.t2)(_context.t3);
7516 return _context.abrupt("return", _context.t0.apply.call(_context.t0, _context.t1, _context.t4));
7517
7518 case 10:
7519 case "end":
7520 return _context.stop();
7521 }
7522 }
7523 }, _callee, this);
7524 }));
7525
7526 function setSessionTokenAsync(_x) {
7527 return _setSessionTokenAsync.apply(this, arguments);
7528 }
7529
7530 return setSessionTokenAsync;
7531 }();
7532
7533 _proto.getSessionToken = /*#__PURE__*/function () {
7534 var _getSessionToken = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
7535 var _ref2,
7536 _ref2$autoRefresh,
7537 autoRefresh,
7538 _ref3,
7539 value,
7540 originalValue,
7541 _yield$this$setSessio,
7542 newValue,
7543 _args2 = arguments;
7544
7545 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
7546 while (1) {
7547 switch (_context2.prev = _context2.next) {
7548 case 0:
7549 _ref2 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref2$autoRefresh = _ref2.autoRefresh, autoRefresh = _ref2$autoRefresh === void 0 ? true : _ref2$autoRefresh;
7550 debug$a('get session token');
7551
7552 if (this._onBeforeGetSessionToken) {
7553 this._onBeforeGetSessionToken(this);
7554 }
7555
7556 _context2.t0 = this._sessionToken;
7557
7558 if (_context2.t0) {
7559 _context2.next = 8;
7560 break;
7561 }
7562
7563 _context2.next = 7;
7564 return this._pendingSessionTokenPromise;
7565
7566 case 7:
7567 _context2.t0 = _context2.sent;
7568
7569 case 8:
7570 _ref3 = _context2.t0;
7571 value = _ref3.value;
7572 originalValue = _ref3.originalValue;
7573
7574 if (!(value === Expirable.EXPIRED && autoRefresh && this.refresh)) {
7575 _context2.next = 19;
7576 break;
7577 }
7578
7579 debug$a('refresh expired session token');
7580 _context2.next = 15;
7581 return this.setSessionTokenAsync(this.refresh(this, originalValue));
7582
7583 case 15:
7584 _yield$this$setSessio = _context2.sent;
7585 newValue = _yield$this$setSessio.value;
7586 debug$a('session token', newValue);
7587 return _context2.abrupt("return", newValue);
7588
7589 case 19:
7590 debug$a('session token', value);
7591 return _context2.abrupt("return", value);
7592
7593 case 21:
7594 case "end":
7595 return _context2.stop();
7596 }
7597 }
7598 }, _callee2, this);
7599 }));
7600
7601 function getSessionToken() {
7602 return _getSessionToken.apply(this, arguments);
7603 }
7604
7605 return getSessionToken;
7606 }();
7607
7608 _proto.revoke = function revoke() {
7609 if (this._sessionToken) this._sessionToken.expiredAt = -1;
7610 };
7611
7612 return SessionManager;
7613}();
7614
7615var _dec$2, _dec2, _class$3;
7616
7617function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
7618
7619function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$8(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
7620var debug$b = d('LC:IMClient');
7621var INVITED$1 = INVITED,
7622 KICKED$1 = KICKED,
7623 MEMBERS_JOINED$1 = MEMBERS_JOINED,
7624 MEMBERS_LEFT$1 = MEMBERS_LEFT,
7625 MEMBER_INFO_UPDATED$1 = MEMBER_INFO_UPDATED,
7626 BLOCKED$1 = BLOCKED,
7627 UNBLOCKED$1 = UNBLOCKED,
7628 MEMBERS_BLOCKED$1 = MEMBERS_BLOCKED,
7629 MEMBERS_UNBLOCKED$1 = MEMBERS_UNBLOCKED,
7630 MUTED$1 = MUTED,
7631 UNMUTED$1 = UNMUTED,
7632 MEMBERS_MUTED$1 = MEMBERS_MUTED,
7633 MEMBERS_UNMUTED$1 = MEMBERS_UNMUTED,
7634 MESSAGE$2 = MESSAGE$1,
7635 UNREAD_MESSAGES_COUNT_UPDATE$1 = UNREAD_MESSAGES_COUNT_UPDATE,
7636 CLOSE$1 = CLOSE,
7637 CONFLICT$1 = CONFLICT,
7638 UNHANDLED_MESSAGE$1 = UNHANDLED_MESSAGE,
7639 CONVERSATION_INFO_UPDATED$1 = CONVERSATION_INFO_UPDATED,
7640 MESSAGE_RECALL$1 = MESSAGE_RECALL,
7641 MESSAGE_UPDATE$1 = MESSAGE_UPDATE,
7642 INFO_UPDATED$1 = INFO_UPDATED;
7643
7644var isTemporaryConversatrionId = function isTemporaryConversatrionId(id) {
7645 return /^_tmp:/.test(id);
7646};
7647/**
7648 * 1 patch-msg
7649 * 1 temp-conv-msg
7650 * 0 auto-bind-deviceid-and-installation
7651 * 1 transient-msg-ack
7652 * 1 keep-notification
7653 * 1 partial-failed-msg
7654 * 0 group-chat-rcp
7655 * 1 omit-peer-id
7656 * @ignore
7657 */
7658
7659
7660var configBitmap = 187;
7661var IMClient = (_dec$2 = throttle(1000), _dec2 = throttle(1000), (_class$3 = /*#__PURE__*/function (_EventEmitter) {
7662 _inheritsLoose(IMClient, _EventEmitter);
7663
7664 /**
7665 * 无法直接实例化,请使用 {@link Realtime#createIMClient} 创建新的 IMClient。
7666 *
7667 * @extends EventEmitter
7668 */
7669 function IMClient(id) {
7670 var _this;
7671
7672 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
7673 var props = arguments.length > 2 ? arguments[2] : undefined;
7674
7675 if (!(id === undefined || typeof id === 'string')) {
7676 throw new TypeError("Client id [".concat(id, "] is not a String"));
7677 }
7678
7679 _this = _EventEmitter.call(this) || this;
7680 Object.assign(_assertThisInitialized(_this), {
7681 /**
7682 * @var id {String} 客户端 id
7683 * @memberof IMClient#
7684 */
7685 id: id,
7686 options: options
7687 }, props);
7688
7689 if (!_this._messageParser) {
7690 throw new Error('IMClient must be initialized with a MessageParser');
7691 }
7692
7693 _this._conversationCache = new Cache("client:".concat(_this.id));
7694 _this._ackMessageBuffer = {};
7695 internal(_assertThisInitialized(_this)).lastPatchTime = Date.now();
7696 internal(_assertThisInitialized(_this)).lastNotificationTime = undefined;
7697 internal(_assertThisInitialized(_this))._eventemitter = new EventEmitter();
7698
7699 if (debug$b.enabled) {
7700 values(IMEvent).forEach(function (event) {
7701 return _this.on(event, function () {
7702 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
7703 payload[_key] = arguments[_key];
7704 }
7705
7706 return _this._debug("".concat(event, " event emitted. %o"), payload);
7707 });
7708 });
7709 } // onIMClientCreate hook
7710
7711
7712 applyDecorators(_this._plugins.onIMClientCreate, _assertThisInitialized(_this));
7713 return _this;
7714 }
7715
7716 var _proto = IMClient.prototype;
7717
7718 _proto._debug = function _debug() {
7719 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
7720 params[_key2] = arguments[_key2];
7721 }
7722
7723 debug$b.apply(void 0, params.concat(["[".concat(this.id, "]")]));
7724 }
7725 /**
7726 * @override
7727 * @private
7728 */
7729 ;
7730
7731 _proto._dispatchCommand =
7732 /*#__PURE__*/
7733 function () {
7734 var _dispatchCommand2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(command) {
7735 return _regeneratorRuntime.wrap(function _callee$(_context) {
7736 while (1) {
7737 switch (_context.prev = _context.next) {
7738 case 0:
7739 this._debug(trim(command), 'received');
7740
7741 if (command.serverTs && command.notificationType === 1) {
7742 internal(this).lastNotificationTime = getTime(decodeDate(command.serverTs));
7743 }
7744
7745 _context.t0 = command.cmd;
7746 _context.next = _context.t0 === CommandType.conv ? 5 : _context.t0 === CommandType.direct ? 6 : _context.t0 === CommandType.session ? 7 : _context.t0 === CommandType.unread ? 8 : _context.t0 === CommandType.rcp ? 9 : _context.t0 === CommandType.patch ? 10 : 11;
7747 break;
7748
7749 case 5:
7750 return _context.abrupt("return", this._dispatchConvMessage(command));
7751
7752 case 6:
7753 return _context.abrupt("return", this._dispatchDirectMessage(command));
7754
7755 case 7:
7756 return _context.abrupt("return", this._dispatchSessionMessage(command));
7757
7758 case 8:
7759 return _context.abrupt("return", this._dispatchUnreadMessage(command));
7760
7761 case 9:
7762 return _context.abrupt("return", this._dispatchRcpMessage(command));
7763
7764 case 10:
7765 return _context.abrupt("return", this._dispatchPatchMessage(command));
7766
7767 case 11:
7768 return _context.abrupt("return", this.emit(UNHANDLED_MESSAGE$1, command));
7769
7770 case 12:
7771 case "end":
7772 return _context.stop();
7773 }
7774 }
7775 }, _callee, this);
7776 }));
7777
7778 function _dispatchCommand(_x) {
7779 return _dispatchCommand2.apply(this, arguments);
7780 }
7781
7782 return _dispatchCommand;
7783 }();
7784
7785 _proto._dispatchSessionMessage = /*#__PURE__*/function () {
7786 var _dispatchSessionMessage2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(message) {
7787 var _message$sessionMessa, code, reason;
7788
7789 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
7790 while (1) {
7791 switch (_context2.prev = _context2.next) {
7792 case 0:
7793 _message$sessionMessa = message.sessionMessage, code = _message$sessionMessa.code, reason = _message$sessionMessa.reason;
7794 _context2.t0 = message.op;
7795 _context2.next = _context2.t0 === OpType.closed ? 4 : 8;
7796 break;
7797
7798 case 4:
7799 internal(this)._eventemitter.emit('close');
7800
7801 if (!(code === ErrorCode.SESSION_CONFLICT)) {
7802 _context2.next = 7;
7803 break;
7804 }
7805
7806 return _context2.abrupt("return", this.emit(CONFLICT$1, {
7807 reason: reason
7808 }));
7809
7810 case 7:
7811 return _context2.abrupt("return", this.emit(CLOSE$1, {
7812 code: code,
7813 reason: reason
7814 }));
7815
7816 case 8:
7817 this.emit(UNHANDLED_MESSAGE$1, message);
7818 throw new Error('Unrecognized session command');
7819
7820 case 10:
7821 case "end":
7822 return _context2.stop();
7823 }
7824 }
7825 }, _callee2, this);
7826 }));
7827
7828 function _dispatchSessionMessage(_x2) {
7829 return _dispatchSessionMessage2.apply(this, arguments);
7830 }
7831
7832 return _dispatchSessionMessage;
7833 }();
7834
7835 _proto._dispatchUnreadMessage = function _dispatchUnreadMessage(_ref) {
7836 var _this2 = this;
7837
7838 var _ref$unreadMessage = _ref.unreadMessage,
7839 convs = _ref$unreadMessage.convs,
7840 notifTime = _ref$unreadMessage.notifTime;
7841 internal(this).lastUnreadNotifTime = notifTime; // ensure all converstions are cached
7842
7843 return this.getConversations(convs.map(function (conv) {
7844 return conv.cid;
7845 })).then(function () {
7846 return (// update conversations data
7847 Promise.all(convs.map(function (_ref2) {
7848 var cid = _ref2.cid,
7849 unread = _ref2.unread,
7850 mid = _ref2.mid,
7851 ts = _ref2.timestamp,
7852 from = _ref2.from,
7853 data = _ref2.data,
7854 binaryMsg = _ref2.binaryMsg,
7855 patchTimestamp = _ref2.patchTimestamp,
7856 mentioned = _ref2.mentioned;
7857
7858 var conversation = _this2._conversationCache.get(cid); // deleted conversation
7859
7860
7861 if (!conversation) return null;
7862 var timestamp;
7863
7864 if (ts) {
7865 timestamp = decodeDate(ts);
7866 conversation.lastMessageAt = timestamp; // eslint-disable-line no-param-reassign
7867 }
7868
7869 return (mid ? _this2._messageParser.parse(binaryMsg || data).then(function (message) {
7870 var messageProps = {
7871 id: mid,
7872 cid: cid,
7873 timestamp: timestamp,
7874 updatedAt: patchTimestamp,
7875 from: from
7876 };
7877 Object.assign(message, messageProps);
7878 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
7879 }) : Promise.resolve()).then(function () {
7880 conversation._setUnreadMessagesMentioned(mentioned);
7881
7882 var countNotUpdated = unread === internal(conversation).unreadMessagesCount;
7883 if (countNotUpdated) return null; // to be filtered
7884 // manipulate internal property directly to skip unreadmessagescountupdate event
7885
7886 internal(conversation).unreadMessagesCount = unread;
7887 return conversation;
7888 }); // filter conversations without unread count update
7889 })).then(function (conversations) {
7890 return conversations.filter(function (conversation) {
7891 return conversation;
7892 });
7893 })
7894 );
7895 }).then(function (conversations) {
7896 if (conversations.length) {
7897 /**
7898 * 未读消息数目更新
7899 * @event IMClient#UNREAD_MESSAGES_COUNT_UPDATE
7900 * @since 3.4.0
7901 * @param {Conversation[]} conversations 未读消息数目有更新的对话列表
7902 */
7903 _this2.emit(UNREAD_MESSAGES_COUNT_UPDATE$1, conversations);
7904 }
7905 });
7906 };
7907
7908 _proto._dispatchRcpMessage = /*#__PURE__*/function () {
7909 var _dispatchRcpMessage2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(message) {
7910 var rcpMessage, read, conversationId, messageId, timestamp, conversation;
7911 return _regeneratorRuntime.wrap(function _callee3$(_context3) {
7912 while (1) {
7913 switch (_context3.prev = _context3.next) {
7914 case 0:
7915 rcpMessage = message.rcpMessage, read = message.rcpMessage.read;
7916 conversationId = rcpMessage.cid;
7917 messageId = rcpMessage.id;
7918 timestamp = decodeDate(rcpMessage.t);
7919 conversation = this._conversationCache.get(conversationId); // conversation not cached means the client does not send the message
7920 // during this session
7921
7922 if (conversation) {
7923 _context3.next = 7;
7924 break;
7925 }
7926
7927 return _context3.abrupt("return");
7928
7929 case 7:
7930 conversation._handleReceipt({
7931 messageId: messageId,
7932 timestamp: timestamp,
7933 read: read
7934 });
7935
7936 case 8:
7937 case "end":
7938 return _context3.stop();
7939 }
7940 }
7941 }, _callee3, this);
7942 }));
7943
7944 function _dispatchRcpMessage(_x3) {
7945 return _dispatchRcpMessage2.apply(this, arguments);
7946 }
7947
7948 return _dispatchRcpMessage;
7949 }();
7950
7951 _proto._dispatchPatchMessage = function _dispatchPatchMessage(_ref3) {
7952 var _this3 = this;
7953
7954 var patches = _ref3.patchMessage.patches;
7955 // ensure all converstions are cached
7956 return this.getConversations(patches.map(function (patch) {
7957 return patch.cid;
7958 })).then(function () {
7959 return Promise.all(patches.map(function (_ref4) {
7960 var cid = _ref4.cid,
7961 mid = _ref4.mid,
7962 timestamp = _ref4.timestamp,
7963 recall = _ref4.recall,
7964 data = _ref4.data,
7965 patchTimestamp = _ref4.patchTimestamp,
7966 from = _ref4.from,
7967 binaryMsg = _ref4.binaryMsg,
7968 mentionAll = _ref4.mentionAll,
7969 mentionPids = _ref4.mentionPids,
7970 patchCode = _ref4.patchCode,
7971 patchReason = _ref4.patchReason;
7972
7973 var conversation = _this3._conversationCache.get(cid); // deleted conversation
7974
7975
7976 if (!conversation) return null;
7977 return _this3._messageParser.parse(binaryMsg || data).then(function (message) {
7978 var patchTime = getTime(decodeDate(patchTimestamp));
7979 var messageProps = {
7980 id: mid,
7981 cid: cid,
7982 timestamp: timestamp,
7983 updatedAt: patchTime,
7984 from: from,
7985 mentionList: mentionPids,
7986 mentionedAll: mentionAll
7987 };
7988 Object.assign(message, messageProps);
7989
7990 message._setStatus(MessageStatus.SENT);
7991
7992 message._updateMentioned(_this3.id);
7993
7994 if (internal(_this3).lastPatchTime < patchTime) {
7995 internal(_this3).lastPatchTime = patchTime;
7996 } // update conversation lastMessage
7997
7998
7999 if (conversation.lastMessage && conversation.lastMessage.id === mid) {
8000 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
8001 }
8002
8003 var reason;
8004
8005 if (patchCode) {
8006 reason = {
8007 code: patchCode.toNumber(),
8008 detail: patchReason
8009 };
8010 }
8011
8012 if (recall) {
8013 /**
8014 * 消息被撤回
8015 * @event IMClient#MESSAGE_RECALL
8016 * @param {AVMessage} message 被撤回的消息
8017 * @param {ConversationBase} conversation 消息所在的会话
8018 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
8019 */
8020 _this3.emit(MESSAGE_RECALL$1, message, conversation, reason);
8021 /**
8022 * 消息被撤回
8023 * @event ConversationBase#MESSAGE_RECALL
8024 * @param {AVMessage} message 被撤回的消息
8025 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
8026 */
8027
8028
8029 conversation.emit(MESSAGE_RECALL$1, message, reason);
8030 } else {
8031 /**
8032 * 消息被修改
8033 * @event IMClient#MESSAGE_UPDATE
8034 * @param {AVMessage} message 被修改的消息
8035 * @param {ConversationBase} conversation 消息所在的会话
8036 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
8037 */
8038 _this3.emit(MESSAGE_UPDATE$1, message, conversation, reason);
8039 /**
8040 * 消息被修改
8041 * @event ConversationBase#MESSAGE_UPDATE
8042 * @param {AVMessage} message 被修改的消息
8043 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
8044 */
8045
8046
8047 conversation.emit(MESSAGE_UPDATE$1, message, reason);
8048 }
8049 });
8050 }));
8051 });
8052 };
8053
8054 _proto._dispatchConvMessage = /*#__PURE__*/function () {
8055 var _dispatchConvMessage2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(message) {
8056 var convMessage, _message$convMessage, initBy, m, info, attr, conversation, payload, _payload, _payload2, _payload3, _payload4, _payload5, _payload6, _payload7, _payload8, _payload9, _payload10, _payload11, pid, role, _internal, memberInfoMap, memberInfo, _payload12, attributes, _payload13;
8057
8058 return _regeneratorRuntime.wrap(function _callee4$(_context4) {
8059 while (1) {
8060 switch (_context4.prev = _context4.next) {
8061 case 0:
8062 convMessage = message.convMessage, _message$convMessage = message.convMessage, initBy = _message$convMessage.initBy, m = _message$convMessage.m, info = _message$convMessage.info, attr = _message$convMessage.attr;
8063 _context4.next = 3;
8064 return this.getConversation(convMessage.cid);
8065
8066 case 3:
8067 conversation = _context4.sent;
8068 _context4.t0 = message.op;
8069 _context4.next = _context4.t0 === OpType.joined ? 7 : _context4.t0 === OpType.left ? 12 : _context4.t0 === OpType.members_joined ? 17 : _context4.t0 === OpType.members_left ? 22 : _context4.t0 === OpType.members_blocked ? 27 : _context4.t0 === OpType.members_unblocked ? 31 : _context4.t0 === OpType.blocked ? 35 : _context4.t0 === OpType.unblocked ? 39 : _context4.t0 === OpType.members_shutuped ? 43 : _context4.t0 === OpType.members_unshutuped ? 47 : _context4.t0 === OpType.shutuped ? 51 : _context4.t0 === OpType.unshutuped ? 55 : _context4.t0 === OpType.member_info_changed ? 59 : _context4.t0 === OpType.updated ? 71 : 77;
8070 break;
8071
8072 case 7:
8073 conversation._addMembers([this.id]);
8074
8075 payload = {
8076 invitedBy: initBy
8077 };
8078 /**
8079 * 当前用户被添加至某个对话
8080 * @event IMClient#INVITED
8081 * @param {Object} payload
8082 * @param {String} payload.invitedBy 邀请者 id
8083 * @param {ConversationBase} conversation
8084 */
8085
8086 this.emit(INVITED$1, payload, conversation);
8087 /**
8088 * 当前用户被添加至当前对话
8089 * @event ConversationBase#INVITED
8090 * @param {Object} payload
8091 * @param {String} payload.invitedBy 该移除操作的发起者 id
8092 */
8093
8094 conversation.emit(INVITED$1, payload);
8095 return _context4.abrupt("return");
8096
8097 case 12:
8098 conversation._removeMembers([this.id]);
8099
8100 _payload = {
8101 kickedBy: initBy
8102 };
8103 /**
8104 * 当前用户被从某个对话中移除
8105 * @event IMClient#KICKED
8106 * @param {Object} payload
8107 * @param {String} payload.kickedBy 该移除操作的发起者 id
8108 * @param {ConversationBase} conversation
8109 */
8110
8111 this.emit(KICKED$1, _payload, conversation);
8112 /**
8113 * 当前用户被从当前对话中移除
8114 * @event ConversationBase#KICKED
8115 * @param {Object} payload
8116 * @param {String} payload.kickedBy 该移除操作的发起者 id
8117 */
8118
8119 conversation.emit(KICKED$1, _payload);
8120 return _context4.abrupt("return");
8121
8122 case 17:
8123 conversation._addMembers(m);
8124
8125 _payload2 = {
8126 invitedBy: initBy,
8127 members: m
8128 };
8129 /**
8130 * 有用户被添加至某个对话
8131 * @event IMClient#MEMBERS_JOINED
8132 * @param {Object} payload
8133 * @param {String[]} payload.members 被添加的用户 id 列表
8134 * @param {String} payload.invitedBy 邀请者 id
8135 * @param {ConversationBase} conversation
8136 */
8137
8138 this.emit(MEMBERS_JOINED$1, _payload2, conversation);
8139 /**
8140 * 有成员被添加至当前对话
8141 * @event ConversationBase#MEMBERS_JOINED
8142 * @param {Object} payload
8143 * @param {String[]} payload.members 被添加的成员 id 列表
8144 * @param {String} payload.invitedBy 邀请者 id
8145 */
8146
8147 conversation.emit(MEMBERS_JOINED$1, _payload2);
8148 return _context4.abrupt("return");
8149
8150 case 22:
8151 conversation._removeMembers(m);
8152
8153 _payload3 = {
8154 kickedBy: initBy,
8155 members: m
8156 };
8157 /**
8158 * 有成员被从某个对话中移除
8159 * @event IMClient#MEMBERS_LEFT
8160 * @param {Object} payload
8161 * @param {String[]} payload.members 被移除的成员 id 列表
8162 * @param {String} payload.kickedBy 该移除操作的发起者 id
8163 * @param {ConversationBase} conversation
8164 */
8165
8166 this.emit(MEMBERS_LEFT$1, _payload3, conversation);
8167 /**
8168 * 有成员被从当前对话中移除
8169 * @event ConversationBase#MEMBERS_LEFT
8170 * @param {Object} payload
8171 * @param {String[]} payload.members 被移除的成员 id 列表
8172 * @param {String} payload.kickedBy 该移除操作的发起者 id
8173 */
8174
8175 conversation.emit(MEMBERS_LEFT$1, _payload3);
8176 return _context4.abrupt("return");
8177
8178 case 27:
8179 _payload4 = {
8180 blockedBy: initBy,
8181 members: m
8182 };
8183 /**
8184 * 有成员被加入某个对话的黑名单
8185 * @event IMClient#MEMBERS_BLOCKED
8186 * @param {Object} payload
8187 * @param {String[]} payload.members 成员 id 列表
8188 * @param {String} payload.blockedBy 该操作的发起者 id
8189 * @param {ConversationBase} conversation
8190 */
8191
8192 this.emit(MEMBERS_BLOCKED$1, _payload4, conversation);
8193 /**
8194 * 有成员被加入当前对话的黑名单
8195 * @event ConversationBase#MEMBERS_BLOCKED
8196 * @param {Object} payload
8197 * @param {String[]} payload.members 成员 id 列表
8198 * @param {String} payload.blockedBy 该操作的发起者 id
8199 */
8200
8201 conversation.emit(MEMBERS_BLOCKED$1, _payload4);
8202 return _context4.abrupt("return");
8203
8204 case 31:
8205 _payload5 = {
8206 unblockedBy: initBy,
8207 members: m
8208 };
8209 /**
8210 * 有成员被移出某个对话的黑名单
8211 * @event IMClient#MEMBERS_UNBLOCKED
8212 * @param {Object} payload
8213 * @param {String[]} payload.members 成员 id 列表
8214 * @param {String} payload.unblockedBy 该操作的发起者 id
8215 * @param {ConversationBase} conversation
8216 */
8217
8218 this.emit(MEMBERS_UNBLOCKED$1, _payload5, conversation);
8219 /**
8220 * 有成员被移出当前对话的黑名单
8221 * @event ConversationBase#MEMBERS_UNBLOCKED
8222 * @param {Object} payload
8223 * @param {String[]} payload.members 成员 id 列表
8224 * @param {String} payload.unblockedBy 该操作的发起者 id
8225 */
8226
8227 conversation.emit(MEMBERS_UNBLOCKED$1, _payload5);
8228 return _context4.abrupt("return");
8229
8230 case 35:
8231 _payload6 = {
8232 blockedBy: initBy
8233 };
8234 /**
8235 * 当前用户被加入某个对话的黑名单
8236 * @event IMClient#BLOCKED
8237 * @param {Object} payload
8238 * @param {String} payload.blockedBy 该操作的发起者 id
8239 * @param {ConversationBase} conversation
8240 */
8241
8242 this.emit(BLOCKED$1, _payload6, conversation);
8243 /**
8244 * 当前用户被加入当前对话的黑名单
8245 * @event ConversationBase#BLOCKED
8246 * @param {Object} payload
8247 * @param {String} payload.blockedBy 该操作的发起者 id
8248 */
8249
8250 conversation.emit(BLOCKED$1, _payload6);
8251 return _context4.abrupt("return");
8252
8253 case 39:
8254 _payload7 = {
8255 unblockedBy: initBy
8256 };
8257 /**
8258 * 当前用户被移出某个对话的黑名单
8259 * @event IMClient#UNBLOCKED
8260 * @param {Object} payload
8261 * @param {String} payload.unblockedBy 该操作的发起者 id
8262 * @param {ConversationBase} conversation
8263 */
8264
8265 this.emit(UNBLOCKED$1, _payload7, conversation);
8266 /**
8267 * 当前用户被移出当前对话的黑名单
8268 * @event ConversationBase#UNBLOCKED
8269 * @param {Object} payload
8270 * @param {String} payload.unblockedBy 该操作的发起者 id
8271 */
8272
8273 conversation.emit(UNBLOCKED$1, _payload7);
8274 return _context4.abrupt("return");
8275
8276 case 43:
8277 _payload8 = {
8278 mutedBy: initBy,
8279 members: m
8280 };
8281 /**
8282 * 有成员在某个对话中被禁言
8283 * @event IMClient#MEMBERS_MUTED
8284 * @param {Object} payload
8285 * @param {String[]} payload.members 成员 id 列表
8286 * @param {String} payload.mutedBy 该操作的发起者 id
8287 * @param {ConversationBase} conversation
8288 */
8289
8290 this.emit(MEMBERS_MUTED$1, _payload8, conversation);
8291 /**
8292 * 有成员在当前对话中被禁言
8293 * @event ConversationBase#MEMBERS_MUTED
8294 * @param {Object} payload
8295 * @param {String[]} payload.members 成员 id 列表
8296 * @param {String} payload.mutedBy 该操作的发起者 id
8297 */
8298
8299 conversation.emit(MEMBERS_MUTED$1, _payload8);
8300 return _context4.abrupt("return");
8301
8302 case 47:
8303 _payload9 = {
8304 unmutedBy: initBy,
8305 members: m
8306 };
8307 /**
8308 * 有成员在某个对话中被解除禁言
8309 * @event IMClient#MEMBERS_UNMUTED
8310 * @param {Object} payload
8311 * @param {String[]} payload.members 成员 id 列表
8312 * @param {String} payload.unmutedBy 该操作的发起者 id
8313 * @param {ConversationBase} conversation
8314 */
8315
8316 this.emit(MEMBERS_UNMUTED$1, _payload9, conversation);
8317 /**
8318 * 有成员在当前对话中被解除禁言
8319 * @event ConversationBase#MEMBERS_UNMUTED
8320 * @param {Object} payload
8321 * @param {String[]} payload.members 成员 id 列表
8322 * @param {String} payload.unmutedBy 该操作的发起者 id
8323 */
8324
8325 conversation.emit(MEMBERS_UNMUTED$1, _payload9);
8326 return _context4.abrupt("return");
8327
8328 case 51:
8329 _payload10 = {
8330 mutedBy: initBy
8331 };
8332 /**
8333 * 有成员在某个对话中被禁言
8334 * @event IMClient#MUTED
8335 * @param {Object} payload
8336 * @param {String} payload.mutedBy 该操作的发起者 id
8337 * @param {ConversationBase} conversation
8338 */
8339
8340 this.emit(MUTED$1, _payload10, conversation);
8341 /**
8342 * 有成员在当前对话中被禁言
8343 * @event ConversationBase#MUTED
8344 * @param {Object} payload
8345 * @param {String} payload.mutedBy 该操作的发起者 id
8346 */
8347
8348 conversation.emit(MUTED$1, _payload10);
8349 return _context4.abrupt("return");
8350
8351 case 55:
8352 _payload11 = {
8353 unmutedBy: initBy
8354 };
8355 /**
8356 * 有成员在某个对话中被解除禁言
8357 * @event IMClient#UNMUTED
8358 * @param {Object} payload
8359 * @param {String} payload.unmutedBy 该操作的发起者 id
8360 * @param {ConversationBase} conversation
8361 */
8362
8363 this.emit(UNMUTED$1, _payload11, conversation);
8364 /**
8365 * 有成员在当前对话中被解除禁言
8366 * @event ConversationBase#UNMUTED
8367 * @param {Object} payload
8368 * @param {String} payload.unmutedBy 该操作的发起者 id
8369 */
8370
8371 conversation.emit(UNMUTED$1, _payload11);
8372 return _context4.abrupt("return");
8373
8374 case 59:
8375 pid = info.pid, role = info.role;
8376 _internal = internal(conversation), memberInfoMap = _internal.memberInfoMap; // 如果不存在缓存,且不是 role 的更新,则不通知
8377
8378 if (!(!memberInfoMap && !role)) {
8379 _context4.next = 63;
8380 break;
8381 }
8382
8383 return _context4.abrupt("return");
8384
8385 case 63:
8386 _context4.next = 65;
8387 return conversation.getMemberInfo(pid);
8388
8389 case 65:
8390 memberInfo = _context4.sent;
8391 internal(memberInfo).role = role;
8392 _payload12 = {
8393 member: pid,
8394 memberInfo: memberInfo,
8395 updatedBy: initBy
8396 };
8397 /**
8398 * 有成员的对话信息被更新
8399 * @event IMClient#MEMBER_INFO_UPDATED
8400 * @param {Object} payload
8401 * @param {String} payload.member 被更新对话信息的成员 id
8402 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
8403 * @param {String} payload.updatedBy 该操作的发起者 id
8404 * @param {ConversationBase} conversation
8405 */
8406
8407 this.emit(MEMBER_INFO_UPDATED$1, _payload12, conversation);
8408 /**
8409 * 有成员的对话信息被更新
8410 * @event ConversationBase#MEMBER_INFO_UPDATED
8411 * @param {Object} payload
8412 * @param {String} payload.member 被更新对话信息的成员 id
8413 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
8414 * @param {String} payload.updatedBy 该操作的发起者 id
8415 */
8416
8417 conversation.emit(MEMBER_INFO_UPDATED$1, _payload12);
8418 return _context4.abrupt("return");
8419
8420 case 71:
8421 attributes = decode(JSON.parse(attr.data));
8422
8423 conversation._updateServerAttributes(attributes);
8424
8425 _payload13 = {
8426 attributes: attributes,
8427 updatedBy: initBy
8428 };
8429 /**
8430 * 该对话信息被更新
8431 * @event IMClient#CONVERSATION_INFO_UPDATED
8432 * @param {Object} payload
8433 * @param {Object} payload.attributes 被更新的属性
8434 * @param {String} payload.updatedBy 该操作的发起者 id
8435 * @param {ConversationBase} conversation
8436 */
8437
8438 this.emit(CONVERSATION_INFO_UPDATED$1, _payload13, conversation);
8439 /**
8440 * 有对话信息被更新
8441 * @event ConversationBase#INFO_UPDATED
8442 * @param {Object} payload
8443 * @param {Object} payload.attributes 被更新的属性
8444 * @param {String} payload.updatedBy 该操作的发起者 id
8445 */
8446
8447 conversation.emit(INFO_UPDATED$1, _payload13);
8448 return _context4.abrupt("return");
8449
8450 case 77:
8451 this.emit(UNHANDLED_MESSAGE$1, message);
8452 throw new Error('Unrecognized conversation command');
8453
8454 case 79:
8455 case "end":
8456 return _context4.stop();
8457 }
8458 }
8459 }, _callee4, this);
8460 }));
8461
8462 function _dispatchConvMessage(_x4) {
8463 return _dispatchConvMessage2.apply(this, arguments);
8464 }
8465
8466 return _dispatchConvMessage;
8467 }();
8468
8469 _proto._dispatchDirectMessage = function _dispatchDirectMessage(originalMessage) {
8470 var _this4 = this;
8471
8472 var directMessage = originalMessage.directMessage,
8473 _originalMessage$dire = originalMessage.directMessage,
8474 id = _originalMessage$dire.id,
8475 cid = _originalMessage$dire.cid,
8476 fromPeerId = _originalMessage$dire.fromPeerId,
8477 timestamp = _originalMessage$dire.timestamp,
8478 _transient = _originalMessage$dire["transient"],
8479 patchTimestamp = _originalMessage$dire.patchTimestamp,
8480 mentionPids = _originalMessage$dire.mentionPids,
8481 mentionAll = _originalMessage$dire.mentionAll,
8482 binaryMsg = _originalMessage$dire.binaryMsg,
8483 msg = _originalMessage$dire.msg;
8484 var content = binaryMsg ? binaryMsg.toArrayBuffer() : msg;
8485 return Promise.all([this.getConversation(directMessage.cid), this._messageParser.parse(content)]).then(function (_ref5) {
8486 var _ref6 = _slicedToArray(_ref5, 2),
8487 conversation = _ref6[0],
8488 message = _ref6[1];
8489
8490 // deleted conversation
8491 if (!conversation) return undefined;
8492 var messageProps = {
8493 id: id,
8494 cid: cid,
8495 timestamp: timestamp,
8496 updatedAt: patchTimestamp,
8497 from: fromPeerId,
8498 mentionList: mentionPids,
8499 mentionedAll: mentionAll
8500 };
8501 Object.assign(message, messageProps);
8502
8503 message._updateMentioned(_this4.id);
8504
8505 message._setStatus(MessageStatus.SENT); // filter outgoing message sent from another device
8506
8507
8508 if (message.from !== _this4.id) {
8509 if (!(_transient || conversation["transient"])) {
8510 _this4._sendAck(message);
8511 }
8512 }
8513
8514 return _this4._dispatchParsedMessage(message, conversation);
8515 });
8516 };
8517
8518 _proto._dispatchParsedMessage = function _dispatchParsedMessage(message, conversation) {
8519 var _this5 = this;
8520
8521 // beforeMessageDispatch hook
8522 return applyDispatcher(this._plugins.beforeMessageDispatch, [message, conversation]).then(function (shouldDispatch) {
8523 if (shouldDispatch === false) return;
8524 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
8525
8526 conversation.lastMessageAt = message.timestamp; // eslint-disable-line no-param-reassign
8527 // filter outgoing message sent from another device
8528
8529 if (message.from !== _this5.id) {
8530 conversation.unreadMessagesCount += 1; // eslint-disable-line no-param-reassign
8531
8532 if (message.mentioned) conversation._setUnreadMessagesMentioned(true);
8533 }
8534 /**
8535 * 当前用户收到消息
8536 * @event IMClient#MESSAGE
8537 * @param {Message} message
8538 * @param {ConversationBase} conversation 收到消息的对话
8539 */
8540
8541
8542 _this5.emit(MESSAGE$2, message, conversation);
8543 /**
8544 * 当前对话收到消息
8545 * @event ConversationBase#MESSAGE
8546 * @param {Message} message
8547 */
8548
8549
8550 conversation.emit(MESSAGE$2, message);
8551 });
8552 };
8553
8554 _proto._sendAck = function _sendAck(message) {
8555 this._debug('send ack for %O', message);
8556
8557 var cid = message.cid;
8558
8559 if (!cid) {
8560 throw new Error('missing cid');
8561 }
8562
8563 if (!this._ackMessageBuffer[cid]) {
8564 this._ackMessageBuffer[cid] = [];
8565 }
8566
8567 this._ackMessageBuffer[cid].push(message);
8568
8569 return this._doSendAck();
8570 } // jsdoc-ignore-start
8571 ;
8572
8573 _proto. // jsdoc-ignore-end
8574 _doSendAck = function _doSendAck() {
8575 var _this6 = this;
8576
8577 // if not connected, just skip everything
8578 if (!this._connection.is('connected')) return;
8579
8580 this._debug('do send ack %O', this._ackMessageBuffer);
8581
8582 Promise.all(Object.keys(this._ackMessageBuffer).map(function (cid) {
8583 var convAckMessages = _this6._ackMessageBuffer[cid];
8584 var timestamps = convAckMessages.map(function (message) {
8585 return message.timestamp;
8586 });
8587 var command = new GenericCommand({
8588 cmd: 'ack',
8589 ackMessage: new AckCommand({
8590 cid: cid,
8591 fromts: Math.min.apply(null, timestamps),
8592 tots: Math.max.apply(null, timestamps)
8593 })
8594 });
8595 delete _this6._ackMessageBuffer[cid];
8596 return _this6._send(command, false)["catch"](function (error) {
8597 _this6._debug('send ack failed: %O', error);
8598
8599 _this6._ackMessageBuffer[cid] = convAckMessages;
8600 });
8601 }));
8602 };
8603
8604 _proto._omitPeerId = function _omitPeerId(value) {
8605 internal(this).peerIdOmittable = value;
8606 };
8607
8608 _proto._send = function _send(cmd) {
8609 var _this$_connection;
8610
8611 var command = cmd;
8612
8613 if (!internal(this).peerIdOmittable && this.id) {
8614 command.peerId = this.id;
8615 }
8616
8617 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
8618 args[_key3 - 1] = arguments[_key3];
8619 }
8620
8621 return (_this$_connection = this._connection).send.apply(_this$_connection, [command].concat(args));
8622 };
8623
8624 _proto._open = /*#__PURE__*/function () {
8625 var _open2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(appId, tag, deviceId) {
8626 var isReconnect,
8627 _internal2,
8628 lastUnreadNotifTime,
8629 lastPatchTime,
8630 lastNotificationTime,
8631 command,
8632 signatureResult,
8633 sessionToken,
8634 resCommand,
8635 _resCommand,
8636 peerId,
8637 sessionMessage,
8638 _resCommand$sessionMe,
8639 token,
8640 tokenTTL,
8641 code,
8642 serverTs,
8643 serverTime,
8644 _args5 = arguments;
8645
8646 return _regeneratorRuntime.wrap(function _callee5$(_context5) {
8647 while (1) {
8648 switch (_context5.prev = _context5.next) {
8649 case 0:
8650 isReconnect = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : false;
8651
8652 this._debug('open session');
8653
8654 _internal2 = internal(this), lastUnreadNotifTime = _internal2.lastUnreadNotifTime, lastPatchTime = _internal2.lastPatchTime, lastNotificationTime = _internal2.lastNotificationTime;
8655 command = new GenericCommand({
8656 cmd: 'session',
8657 op: 'open',
8658 appId: appId,
8659 peerId: this.id,
8660 sessionMessage: new SessionCommand({
8661 ua: "js/".concat(version),
8662 r: isReconnect,
8663 lastUnreadNotifTime: lastUnreadNotifTime,
8664 lastPatchTime: lastPatchTime,
8665 configBitmap: configBitmap
8666 })
8667 });
8668
8669 if (isReconnect) {
8670 _context5.next = 13;
8671 break;
8672 }
8673
8674 Object.assign(command.sessionMessage, trim({
8675 tag: tag,
8676 deviceId: deviceId
8677 }));
8678
8679 if (!this.options.signatureFactory) {
8680 _context5.next = 11;
8681 break;
8682 }
8683
8684 _context5.next = 9;
8685 return runSignatureFactory(this.options.signatureFactory, [this._identity]);
8686
8687 case 9:
8688 signatureResult = _context5.sent;
8689 Object.assign(command.sessionMessage, keyRemap({
8690 signature: 's',
8691 timestamp: 't',
8692 nonce: 'n'
8693 }, signatureResult));
8694
8695 case 11:
8696 _context5.next = 17;
8697 break;
8698
8699 case 13:
8700 _context5.next = 15;
8701 return this._sessionManager.getSessionToken({
8702 autoRefresh: false
8703 });
8704
8705 case 15:
8706 sessionToken = _context5.sent;
8707
8708 if (sessionToken && sessionToken !== Expirable.EXPIRED) {
8709 Object.assign(command.sessionMessage, {
8710 st: sessionToken
8711 });
8712 }
8713
8714 case 17:
8715 _context5.prev = 17;
8716 _context5.next = 20;
8717 return this._send(command);
8718
8719 case 20:
8720 resCommand = _context5.sent;
8721 _context5.next = 32;
8722 break;
8723
8724 case 23:
8725 _context5.prev = 23;
8726 _context5.t0 = _context5["catch"](17);
8727
8728 if (!(_context5.t0.code === ErrorCode.SESSION_TOKEN_EXPIRED)) {
8729 _context5.next = 31;
8730 break;
8731 }
8732
8733 if (this._sessionManager) {
8734 _context5.next = 28;
8735 break;
8736 }
8737
8738 throw new Error('Unexpected session expiration');
8739
8740 case 28:
8741 debug$b('Session token expired, reopening');
8742
8743 this._sessionManager.revoke();
8744
8745 return _context5.abrupt("return", this._open(appId, tag, deviceId, isReconnect));
8746
8747 case 31:
8748 throw _context5.t0;
8749
8750 case 32:
8751 _resCommand = resCommand, peerId = _resCommand.peerId, sessionMessage = _resCommand.sessionMessage, _resCommand$sessionMe = _resCommand.sessionMessage, token = _resCommand$sessionMe.st, tokenTTL = _resCommand$sessionMe.stTtl, code = _resCommand$sessionMe.code, serverTs = _resCommand.serverTs;
8752
8753 if (!code) {
8754 _context5.next = 35;
8755 break;
8756 }
8757
8758 throw createError(sessionMessage);
8759
8760 case 35:
8761 if (peerId) {
8762 this.id = peerId;
8763 if (!this._identity) this._identity = peerId;
8764
8765 if (token) {
8766 this._sessionManager = this._sessionManager || this._createSessionManager();
8767
8768 this._sessionManager.setSessionToken(token, tokenTTL);
8769 }
8770
8771 serverTime = getTime(decodeDate(serverTs));
8772
8773 if (serverTs) {
8774 internal(this).lastPatchTime = serverTime;
8775 }
8776
8777 if (lastNotificationTime) {
8778 // Do not await for it as this is failable
8779 this._syncNotifications(lastNotificationTime)["catch"](function (error) {
8780 return console.warn('Syncing notifications failed:', error);
8781 });
8782 } else {
8783 // Set timestamp to now for next reconnection
8784 internal(this).lastNotificationTime = serverTime;
8785 }
8786 } else {
8787 console.warn('Unexpected session opened without peerId.');
8788 }
8789
8790 return _context5.abrupt("return", undefined);
8791
8792 case 37:
8793 case "end":
8794 return _context5.stop();
8795 }
8796 }
8797 }, _callee5, this, [[17, 23]]);
8798 }));
8799
8800 function _open(_x5, _x6, _x7) {
8801 return _open2.apply(this, arguments);
8802 }
8803
8804 return _open;
8805 }();
8806
8807 _proto._syncNotifications = /*#__PURE__*/function () {
8808 var _syncNotifications2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(timestamp) {
8809 var _this7 = this;
8810
8811 var _yield$this$_fetchNot, hasMore, notifications;
8812
8813 return _regeneratorRuntime.wrap(function _callee6$(_context6) {
8814 while (1) {
8815 switch (_context6.prev = _context6.next) {
8816 case 0:
8817 _context6.next = 2;
8818 return this._fetchNotifications(timestamp);
8819
8820 case 2:
8821 _yield$this$_fetchNot = _context6.sent;
8822 hasMore = _yield$this$_fetchNot.hasMore;
8823 notifications = _yield$this$_fetchNot.notifications;
8824 notifications.forEach(function (notification) {
8825 var cmd = notification.cmd,
8826 op = notification.op,
8827 serverTs = notification.serverTs,
8828 notificationType = notification.notificationType,
8829 payload = _objectWithoutProperties(notification, ["cmd", "op", "serverTs", "notificationType"]);
8830
8831 _this7._dispatchCommand(_defineProperty({
8832 cmd: CommandType[cmd],
8833 op: OpType[op],
8834 serverTs: serverTs,
8835 notificationType: notificationType
8836 }, "".concat(cmd, "Message"), payload));
8837 });
8838
8839 if (!hasMore) {
8840 _context6.next = 8;
8841 break;
8842 }
8843
8844 return _context6.abrupt("return", this._syncNotifications(internal(this).lastNotificationTime));
8845
8846 case 8:
8847 return _context6.abrupt("return", undefined);
8848
8849 case 9:
8850 case "end":
8851 return _context6.stop();
8852 }
8853 }
8854 }, _callee6, this);
8855 }));
8856
8857 function _syncNotifications(_x8) {
8858 return _syncNotifications2.apply(this, arguments);
8859 }
8860
8861 return _syncNotifications;
8862 }();
8863
8864 _proto._fetchNotifications = /*#__PURE__*/function () {
8865 var _fetchNotifications2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(timestamp) {
8866 return _regeneratorRuntime.wrap(function _callee7$(_context7) {
8867 while (1) {
8868 switch (_context7.prev = _context7.next) {
8869 case 0:
8870 return _context7.abrupt("return", this._requestWithSessionToken({
8871 method: 'GET',
8872 path: '/rtm/notifications',
8873 query: {
8874 start_ts: timestamp,
8875 notification_type: 'permanent'
8876 }
8877 }));
8878
8879 case 1:
8880 case "end":
8881 return _context7.stop();
8882 }
8883 }
8884 }, _callee7, this);
8885 }));
8886
8887 function _fetchNotifications(_x9) {
8888 return _fetchNotifications2.apply(this, arguments);
8889 }
8890
8891 return _fetchNotifications;
8892 }();
8893
8894 _proto._createSessionManager = function _createSessionManager() {
8895 var _this8 = this;
8896
8897 debug$b('create SessionManager');
8898 return new SessionManager({
8899 onBeforeGetSessionToken: this._connection.checkConnectionAvailability.bind(this._connection),
8900 refresh: function refresh(manager, expiredSessionToken) {
8901 return manager.setSessionTokenAsync(Promise.resolve(new GenericCommand({
8902 cmd: 'session',
8903 op: 'refresh',
8904 sessionMessage: new SessionCommand({
8905 ua: "js/".concat(version),
8906 st: expiredSessionToken
8907 })
8908 })).then( /*#__PURE__*/function () {
8909 var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(command) {
8910 var signatureResult;
8911 return _regeneratorRuntime.wrap(function _callee8$(_context8) {
8912 while (1) {
8913 switch (_context8.prev = _context8.next) {
8914 case 0:
8915 if (!_this8.options.signatureFactory) {
8916 _context8.next = 5;
8917 break;
8918 }
8919
8920 _context8.next = 3;
8921 return runSignatureFactory(_this8.options.signatureFactory, [_this8._identity]);
8922
8923 case 3:
8924 signatureResult = _context8.sent;
8925 Object.assign(command.sessionMessage, keyRemap({
8926 signature: 's',
8927 timestamp: 't',
8928 nonce: 'n'
8929 }, signatureResult));
8930
8931 case 5:
8932 return _context8.abrupt("return", command);
8933
8934 case 6:
8935 case "end":
8936 return _context8.stop();
8937 }
8938 }
8939 }, _callee8);
8940 }));
8941
8942 return function (_x10) {
8943 return _ref7.apply(this, arguments);
8944 };
8945 }()).then(_this8._send.bind(_this8)).then(function (_ref8) {
8946 var _ref8$sessionMessage = _ref8.sessionMessage,
8947 token = _ref8$sessionMessage.st,
8948 ttl = _ref8$sessionMessage.stTtl;
8949 return [token, ttl];
8950 }));
8951 }
8952 });
8953 };
8954
8955 _proto._requestWithSessionToken = /*#__PURE__*/function () {
8956 var _requestWithSessionToken2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(_ref9) {
8957 var headers, query, params, sessionToken;
8958 return _regeneratorRuntime.wrap(function _callee9$(_context9) {
8959 while (1) {
8960 switch (_context9.prev = _context9.next) {
8961 case 0:
8962 headers = _ref9.headers, query = _ref9.query, params = _objectWithoutProperties(_ref9, ["headers", "query"]);
8963 _context9.next = 3;
8964 return this._sessionManager.getSessionToken();
8965
8966 case 3:
8967 sessionToken = _context9.sent;
8968 return _context9.abrupt("return", this._request(_objectSpread$8({
8969 headers: _objectSpread$8({
8970 'X-LC-IM-Session-Token': sessionToken
8971 }, headers),
8972 query: _objectSpread$8({
8973 client_id: this.id
8974 }, query)
8975 }, params)));
8976
8977 case 5:
8978 case "end":
8979 return _context9.stop();
8980 }
8981 }
8982 }, _callee9, this);
8983 }));
8984
8985 function _requestWithSessionToken(_x11) {
8986 return _requestWithSessionToken2.apply(this, arguments);
8987 }
8988
8989 return _requestWithSessionToken;
8990 }()
8991 /**
8992 * 关闭客户端
8993 * @return {Promise}
8994 */
8995 ;
8996
8997 _proto.close =
8998 /*#__PURE__*/
8999 function () {
9000 var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee10() {
9001 var _ee, command;
9002
9003 return _regeneratorRuntime.wrap(function _callee10$(_context10) {
9004 while (1) {
9005 switch (_context10.prev = _context10.next) {
9006 case 0:
9007 this._debug('close session');
9008
9009 _ee = internal(this)._eventemitter;
9010
9011 _ee.emit('beforeclose');
9012
9013 if (!this._connection.is('connected')) {
9014 _context10.next = 7;
9015 break;
9016 }
9017
9018 command = new GenericCommand({
9019 cmd: 'session',
9020 op: 'close'
9021 });
9022 _context10.next = 7;
9023 return this._send(command);
9024
9025 case 7:
9026 _ee.emit('close');
9027
9028 this.emit(CLOSE$1, {
9029 code: 0
9030 });
9031
9032 case 9:
9033 case "end":
9034 return _context10.stop();
9035 }
9036 }
9037 }, _callee10, this);
9038 }));
9039
9040 function close() {
9041 return _close.apply(this, arguments);
9042 }
9043
9044 return close;
9045 }()
9046 /**
9047 * 获取 client 列表中在线的 client,每次查询最多 20 个 clientId,超出部分会被忽略
9048 * @param {String[]} clientIds 要查询的 client ids
9049 * @return {Primse.<String[]>} 在线的 client ids
9050 */
9051 ;
9052
9053 _proto.ping =
9054 /*#__PURE__*/
9055 function () {
9056 var _ping = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee11(clientIds) {
9057 var command, resCommand;
9058 return _regeneratorRuntime.wrap(function _callee11$(_context11) {
9059 while (1) {
9060 switch (_context11.prev = _context11.next) {
9061 case 0:
9062 this._debug('ping');
9063
9064 if (clientIds instanceof Array) {
9065 _context11.next = 3;
9066 break;
9067 }
9068
9069 throw new TypeError("clientIds ".concat(clientIds, " is not an Array"));
9070
9071 case 3:
9072 if (clientIds.length) {
9073 _context11.next = 5;
9074 break;
9075 }
9076
9077 return _context11.abrupt("return", Promise.resolve([]));
9078
9079 case 5:
9080 command = new GenericCommand({
9081 cmd: 'session',
9082 op: 'query',
9083 sessionMessage: new SessionCommand({
9084 sessionPeerIds: clientIds
9085 })
9086 });
9087 _context11.next = 8;
9088 return this._send(command);
9089
9090 case 8:
9091 resCommand = _context11.sent;
9092 return _context11.abrupt("return", resCommand.sessionMessage.onlineSessionPeerIds);
9093
9094 case 10:
9095 case "end":
9096 return _context11.stop();
9097 }
9098 }
9099 }, _callee11, this);
9100 }));
9101
9102 function ping(_x12) {
9103 return _ping.apply(this, arguments);
9104 }
9105
9106 return ping;
9107 }()
9108 /**
9109 * 获取某个特定的对话
9110 * @param {String} id 对话 id,对应 _Conversation 表中的 objectId
9111 * @param {Boolean} [noCache=false] 强制不从缓存中获取
9112 * @return {Promise.<ConversationBase>} 如果 id 对应的对话不存在则返回 null
9113 */
9114 ;
9115
9116 _proto.getConversation =
9117 /*#__PURE__*/
9118 function () {
9119 var _getConversation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee12(id) {
9120 var noCache,
9121 cachedConversation,
9122 _args12 = arguments;
9123 return _regeneratorRuntime.wrap(function _callee12$(_context12) {
9124 while (1) {
9125 switch (_context12.prev = _context12.next) {
9126 case 0:
9127 noCache = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : false;
9128
9129 if (!(typeof id !== 'string')) {
9130 _context12.next = 3;
9131 break;
9132 }
9133
9134 throw new TypeError("".concat(id, " is not a String"));
9135
9136 case 3:
9137 if (noCache) {
9138 _context12.next = 7;
9139 break;
9140 }
9141
9142 cachedConversation = this._conversationCache.get(id);
9143
9144 if (!cachedConversation) {
9145 _context12.next = 7;
9146 break;
9147 }
9148
9149 return _context12.abrupt("return", cachedConversation);
9150
9151 case 7:
9152 if (!isTemporaryConversatrionId(id)) {
9153 _context12.next = 14;
9154 break;
9155 }
9156
9157 _context12.next = 10;
9158 return this._getTemporaryConversations([id]);
9159
9160 case 10:
9161 _context12.t0 = _context12.sent[0];
9162
9163 if (_context12.t0) {
9164 _context12.next = 13;
9165 break;
9166 }
9167
9168 _context12.t0 = null;
9169
9170 case 13:
9171 return _context12.abrupt("return", _context12.t0);
9172
9173 case 14:
9174 return _context12.abrupt("return", this.getQuery().equalTo('objectId', id).find().then(function (conversations) {
9175 return conversations[0] || null;
9176 }));
9177
9178 case 15:
9179 case "end":
9180 return _context12.stop();
9181 }
9182 }
9183 }, _callee12, this);
9184 }));
9185
9186 function getConversation(_x13) {
9187 return _getConversation.apply(this, arguments);
9188 }
9189
9190 return getConversation;
9191 }()
9192 /**
9193 * 通过 id 批量获取某个特定的对话
9194 * @since 3.4.0
9195 * @param {String[]} ids 对话 id 列表,对应 _Conversation 表中的 objectId
9196 * @param {Boolean} [noCache=false] 强制不从缓存中获取
9197 * @return {Promise.<ConversationBase[]>} 如果 id 对应的对话不存在则返回 null
9198 */
9199 ;
9200
9201 _proto.getConversations =
9202 /*#__PURE__*/
9203 function () {
9204 var _getConversations = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee13(ids) {
9205 var _this9 = this;
9206
9207 var noCache,
9208 remoteConversationIds,
9209 remoteTemporaryConversationIds,
9210 query,
9211 remoteTemporaryConversationsPromise,
9212 _args13 = arguments;
9213 return _regeneratorRuntime.wrap(function _callee13$(_context13) {
9214 while (1) {
9215 switch (_context13.prev = _context13.next) {
9216 case 0:
9217 noCache = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : false;
9218 remoteConversationIds = noCache ? ids : ids.filter(function (id) {
9219 return _this9._conversationCache.get(id) === null;
9220 });
9221
9222 if (!remoteConversationIds.length) {
9223 _context13.next = 9;
9224 break;
9225 }
9226
9227 remoteTemporaryConversationIds = remove(remoteConversationIds, isTemporaryConversatrionId);
9228 query = [];
9229
9230 if (remoteConversationIds.length) {
9231 query.push(this.getQuery().containedIn('objectId', remoteConversationIds).limit(999).find());
9232 }
9233
9234 if (remoteTemporaryConversationIds.length) {
9235 remoteTemporaryConversationsPromise = remoteTemporaryConversationIds.map(this._getTemporaryConversations.bind(this));
9236 query.push.apply(query, _toConsumableArray(remoteTemporaryConversationsPromise));
9237 }
9238
9239 _context13.next = 9;
9240 return Promise.all(query);
9241
9242 case 9:
9243 return _context13.abrupt("return", ids.map(function (id) {
9244 return _this9._conversationCache.get(id);
9245 }));
9246
9247 case 10:
9248 case "end":
9249 return _context13.stop();
9250 }
9251 }
9252 }, _callee13, this);
9253 }));
9254
9255 function getConversations(_x14) {
9256 return _getConversations.apply(this, arguments);
9257 }
9258
9259 return getConversations;
9260 }();
9261
9262 _proto._getTemporaryConversations = /*#__PURE__*/function () {
9263 var _getTemporaryConversations2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee14(ids) {
9264 var command, resCommand;
9265 return _regeneratorRuntime.wrap(function _callee14$(_context14) {
9266 while (1) {
9267 switch (_context14.prev = _context14.next) {
9268 case 0:
9269 command = new GenericCommand({
9270 cmd: 'conv',
9271 op: 'query',
9272 convMessage: new ConvCommand({
9273 tempConvIds: ids
9274 })
9275 });
9276 _context14.next = 3;
9277 return this._send(command);
9278
9279 case 3:
9280 resCommand = _context14.sent;
9281 return _context14.abrupt("return", this._handleQueryResults(resCommand));
9282
9283 case 5:
9284 case "end":
9285 return _context14.stop();
9286 }
9287 }
9288 }, _callee14, this);
9289 }));
9290
9291 function _getTemporaryConversations(_x15) {
9292 return _getTemporaryConversations2.apply(this, arguments);
9293 }
9294
9295 return _getTemporaryConversations;
9296 }()
9297 /**
9298 * 构造一个 ConversationQuery 来查询对话
9299 * @return {ConversationQuery.<PersistentConversation>}
9300 */
9301 ;
9302
9303 _proto.getQuery = function getQuery() {
9304 return new ConversationQuery(this);
9305 }
9306 /**
9307 * 构造一个 ConversationQuery 来查询聊天室
9308 * @return {ConversationQuery.<ChatRoom>}
9309 */
9310 ;
9311
9312 _proto.getChatRoomQuery = function getChatRoomQuery() {
9313 return this.getQuery().equalTo('tr', true);
9314 }
9315 /**
9316 * 构造一个 ConversationQuery 来查询服务号
9317 * @return {ConversationQuery.<ServiceConversation>}
9318 */
9319 ;
9320
9321 _proto.getServiceConversationQuery = function getServiceConversationQuery() {
9322 return this.getQuery().equalTo('sys', true);
9323 };
9324
9325 _proto._executeQuery = /*#__PURE__*/function () {
9326 var _executeQuery2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee15(query) {
9327 var queryJSON, command, resCommand;
9328 return _regeneratorRuntime.wrap(function _callee15$(_context15) {
9329 while (1) {
9330 switch (_context15.prev = _context15.next) {
9331 case 0:
9332 queryJSON = query.toJSON();
9333 queryJSON.where = new JsonObjectMessage({
9334 data: JSON.stringify(encode(queryJSON.where))
9335 });
9336 command = new GenericCommand({
9337 cmd: 'conv',
9338 op: 'query',
9339 convMessage: new ConvCommand(queryJSON)
9340 });
9341 _context15.next = 5;
9342 return this._send(command);
9343
9344 case 5:
9345 resCommand = _context15.sent;
9346 return _context15.abrupt("return", this._handleQueryResults(resCommand));
9347
9348 case 7:
9349 case "end":
9350 return _context15.stop();
9351 }
9352 }
9353 }, _callee15, this);
9354 }));
9355
9356 function _executeQuery(_x16) {
9357 return _executeQuery2.apply(this, arguments);
9358 }
9359
9360 return _executeQuery;
9361 }();
9362
9363 _proto._handleQueryResults = /*#__PURE__*/function () {
9364 var _handleQueryResults2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee16(resCommand) {
9365 var conversations, commandString;
9366 return _regeneratorRuntime.wrap(function _callee16$(_context16) {
9367 while (1) {
9368 switch (_context16.prev = _context16.next) {
9369 case 0:
9370 _context16.prev = 0;
9371 conversations = decode(JSON.parse(resCommand.convMessage.results.data));
9372 _context16.next = 8;
9373 break;
9374
9375 case 4:
9376 _context16.prev = 4;
9377 _context16.t0 = _context16["catch"](0);
9378 commandString = JSON.stringify(trim(resCommand));
9379 throw new Error("Parse query result failed: ".concat(_context16.t0.message, ". Command: ").concat(commandString));
9380
9381 case 8:
9382 _context16.next = 10;
9383 return Promise.all(conversations.map(this._parseConversationFromRawData.bind(this)));
9384
9385 case 10:
9386 conversations = _context16.sent;
9387 return _context16.abrupt("return", conversations.map(this._upsertConversationToCache.bind(this)));
9388
9389 case 12:
9390 case "end":
9391 return _context16.stop();
9392 }
9393 }
9394 }, _callee16, this, [[0, 4]]);
9395 }));
9396
9397 function _handleQueryResults(_x17) {
9398 return _handleQueryResults2.apply(this, arguments);
9399 }
9400
9401 return _handleQueryResults;
9402 }();
9403
9404 _proto._upsertConversationToCache = function _upsertConversationToCache(fetchedConversation) {
9405 var conversation = this._conversationCache.get(fetchedConversation.id);
9406
9407 if (!conversation) {
9408 conversation = fetchedConversation;
9409
9410 this._debug('no match, set cache');
9411
9412 this._conversationCache.set(fetchedConversation.id, fetchedConversation);
9413 } else {
9414 this._debug('update cached conversation');
9415
9416 ['creator', 'createdAt', 'updatedAt', 'lastMessageAt', 'lastMessage', 'mutedMembers', 'members', '_attributes', 'transient', 'muted'].forEach(function (key) {
9417 var value = fetchedConversation[key];
9418 if (value !== undefined) conversation[key] = value;
9419 });
9420 if (conversation._reset) conversation._reset();
9421 }
9422
9423 return conversation;
9424 }
9425 /**
9426 * 反序列化消息,与 {@link Message#toFullJSON} 相对。
9427 * @param {Object}
9428 * @return {AVMessage} 解析后的消息
9429 * @since 4.0.0
9430 */
9431 ;
9432
9433 _proto.parseMessage =
9434 /*#__PURE__*/
9435 function () {
9436 var _parseMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee17(_ref10) {
9437 var data, _ref10$bin, bin, properties, content, message;
9438
9439 return _regeneratorRuntime.wrap(function _callee17$(_context17) {
9440 while (1) {
9441 switch (_context17.prev = _context17.next) {
9442 case 0:
9443 data = _ref10.data, _ref10$bin = _ref10.bin, bin = _ref10$bin === void 0 ? false : _ref10$bin, properties = _objectWithoutProperties(_ref10, ["data", "bin"]);
9444 content = bin ? base64Arraybuffer.decode(data) : data;
9445 _context17.next = 4;
9446 return this._messageParser.parse(content);
9447
9448 case 4:
9449 message = _context17.sent;
9450 Object.assign(message, properties);
9451
9452 message._updateMentioned(this.id);
9453
9454 return _context17.abrupt("return", message);
9455
9456 case 8:
9457 case "end":
9458 return _context17.stop();
9459 }
9460 }
9461 }, _callee17, this);
9462 }));
9463
9464 function parseMessage(_x18) {
9465 return _parseMessage.apply(this, arguments);
9466 }
9467
9468 return parseMessage;
9469 }()
9470 /**
9471 * 反序列化对话,与 {@link Conversation#toFullJSON} 相对。
9472 * @param {Object}
9473 * @return {ConversationBase} 解析后的对话
9474 * @since 4.0.0
9475 */
9476 ;
9477
9478 _proto.parseConversation =
9479 /*#__PURE__*/
9480 function () {
9481 var _parseConversation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(_ref11) {
9482 var id, lastMessageAt, lastMessage, lastDeliveredAt, lastReadAt, unreadMessagesCount, members, mentioned, properties, conversationData, _transient2, system, expiredAt;
9483
9484 return _regeneratorRuntime.wrap(function _callee18$(_context18) {
9485 while (1) {
9486 switch (_context18.prev = _context18.next) {
9487 case 0:
9488 id = _ref11.id, lastMessageAt = _ref11.lastMessageAt, lastMessage = _ref11.lastMessage, lastDeliveredAt = _ref11.lastDeliveredAt, lastReadAt = _ref11.lastReadAt, unreadMessagesCount = _ref11.unreadMessagesCount, members = _ref11.members, mentioned = _ref11.mentioned, properties = _objectWithoutProperties(_ref11, ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"]);
9489 conversationData = {
9490 id: id,
9491 lastMessageAt: lastMessageAt,
9492 lastMessage: lastMessage,
9493 lastDeliveredAt: lastDeliveredAt,
9494 lastReadAt: lastReadAt,
9495 unreadMessagesCount: unreadMessagesCount,
9496 members: members,
9497 mentioned: mentioned
9498 };
9499
9500 if (!lastMessage) {
9501 _context18.next = 7;
9502 break;
9503 }
9504
9505 _context18.next = 5;
9506 return this.parseMessage(lastMessage);
9507
9508 case 5:
9509 conversationData.lastMessage = _context18.sent;
9510
9511 conversationData.lastMessage._setStatus(MessageStatus.SENT);
9512
9513 case 7:
9514 _transient2 = properties["transient"], system = properties.system, expiredAt = properties.expiredAt;
9515
9516 if (!_transient2) {
9517 _context18.next = 10;
9518 break;
9519 }
9520
9521 return _context18.abrupt("return", new ChatRoom(conversationData, properties, this));
9522
9523 case 10:
9524 if (!system) {
9525 _context18.next = 12;
9526 break;
9527 }
9528
9529 return _context18.abrupt("return", new ServiceConversation(conversationData, properties, this));
9530
9531 case 12:
9532 if (!(expiredAt || isTemporaryConversatrionId(id))) {
9533 _context18.next = 14;
9534 break;
9535 }
9536
9537 return _context18.abrupt("return", new TemporaryConversation(conversationData, {
9538 expiredAt: expiredAt
9539 }, this));
9540
9541 case 14:
9542 return _context18.abrupt("return", new Conversation(conversationData, properties, this));
9543
9544 case 15:
9545 case "end":
9546 return _context18.stop();
9547 }
9548 }
9549 }, _callee18, this);
9550 }));
9551
9552 function parseConversation(_x19) {
9553 return _parseConversation.apply(this, arguments);
9554 }
9555
9556 return parseConversation;
9557 }();
9558
9559 _proto._parseConversationFromRawData = /*#__PURE__*/function () {
9560 var _parseConversationFromRawData2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(rawData) {
9561 var data, ttl;
9562 return _regeneratorRuntime.wrap(function _callee19$(_context19) {
9563 while (1) {
9564 switch (_context19.prev = _context19.next) {
9565 case 0:
9566 data = keyRemap({
9567 objectId: 'id',
9568 lm: 'lastMessageAt',
9569 m: 'members',
9570 tr: 'transient',
9571 sys: 'system',
9572 c: 'creator',
9573 mu: 'mutedMembers'
9574 }, rawData);
9575
9576 if (data.msg) {
9577 data.lastMessage = {
9578 data: data.msg,
9579 bin: data.bin,
9580 from: data.msg_from,
9581 id: data.msg_mid,
9582 timestamp: data.msg_timestamp,
9583 updatedAt: data.patch_timestamp
9584 };
9585 delete data.lastMessageFrom;
9586 delete data.lastMessageId;
9587 delete data.lastMessageTimestamp;
9588 delete data.lastMessagePatchTimestamp;
9589 }
9590
9591 ttl = data.ttl;
9592 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
9593 return _context19.abrupt("return", this.parseConversation(data));
9594
9595 case 5:
9596 case "end":
9597 return _context19.stop();
9598 }
9599 }
9600 }, _callee19, this);
9601 }));
9602
9603 function _parseConversationFromRawData(_x20) {
9604 return _parseConversationFromRawData2.apply(this, arguments);
9605 }
9606
9607 return _parseConversationFromRawData;
9608 }()
9609 /**
9610 * 创建一个对话
9611 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
9612 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
9613 * @param {String} [options.name] 对话的名字
9614 * @param {Boolean} [options.unique=true] 唯一对话,当其为 true 时,如果当前已经有相同成员的对话存在则返回该对话,否则会创建新的对话
9615 * @return {Promise.<Conversation>}
9616 */
9617 ;
9618
9619 _proto.createConversation =
9620 /*#__PURE__*/
9621 function () {
9622 var _createConversation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee20() {
9623 var _ref12,
9624 m,
9625 name,
9626 _transient3,
9627 _ref12$unique,
9628 unique,
9629 tempConv,
9630 tempConvTTL,
9631 properties,
9632 members,
9633 attr,
9634 startCommandJson,
9635 command,
9636 params,
9637 signatureResult,
9638 _yield$this$_send,
9639 _yield$this$_send$con,
9640 cid,
9641 cdate,
9642 ttl,
9643 data,
9644 conversation,
9645 _args20 = arguments;
9646
9647 return _regeneratorRuntime.wrap(function _callee20$(_context20) {
9648 while (1) {
9649 switch (_context20.prev = _context20.next) {
9650 case 0:
9651 _ref12 = _args20.length > 0 && _args20[0] !== undefined ? _args20[0] : {}, m = _ref12.members, name = _ref12.name, _transient3 = _ref12["transient"], _ref12$unique = _ref12.unique, unique = _ref12$unique === void 0 ? true : _ref12$unique, tempConv = _ref12._tempConv, tempConvTTL = _ref12._tempConvTTL, properties = _objectWithoutProperties(_ref12, ["members", "name", "transient", "unique", "_tempConv", "_tempConvTTL"]);
9652
9653 if (_transient3 || Array.isArray(m)) {
9654 _context20.next = 3;
9655 break;
9656 }
9657
9658 throw new TypeError("conversation members ".concat(m, " is not an array"));
9659
9660 case 3:
9661 members = new Set(m);
9662 members.add(this.id);
9663 members = Array.from(members).sort();
9664 attr = properties || {};
9665
9666 if (!name) {
9667 _context20.next = 11;
9668 break;
9669 }
9670
9671 if (!(typeof name !== 'string')) {
9672 _context20.next = 10;
9673 break;
9674 }
9675
9676 throw new TypeError("conversation name ".concat(name, " is not a string"));
9677
9678 case 10:
9679 attr.name = name;
9680
9681 case 11:
9682 attr = new JsonObjectMessage({
9683 data: JSON.stringify(encode(attr))
9684 });
9685 startCommandJson = {
9686 m: members,
9687 attr: attr,
9688 "transient": _transient3,
9689 unique: unique,
9690 tempConv: tempConv,
9691 tempConvTTL: tempConvTTL
9692 };
9693 command = new GenericCommand({
9694 cmd: 'conv',
9695 op: 'start',
9696 convMessage: new ConvCommand(startCommandJson)
9697 });
9698
9699 if (!this.options.conversationSignatureFactory) {
9700 _context20.next = 20;
9701 break;
9702 }
9703
9704 params = [null, this._identity, members, 'create'];
9705 _context20.next = 18;
9706 return runSignatureFactory(this.options.conversationSignatureFactory, params);
9707
9708 case 18:
9709 signatureResult = _context20.sent;
9710 Object.assign(command.convMessage, keyRemap({
9711 signature: 's',
9712 timestamp: 't',
9713 nonce: 'n'
9714 }, signatureResult));
9715
9716 case 20:
9717 _context20.next = 22;
9718 return this._send(command);
9719
9720 case 22:
9721 _yield$this$_send = _context20.sent;
9722 _yield$this$_send$con = _yield$this$_send.convMessage;
9723 cid = _yield$this$_send$con.cid;
9724 cdate = _yield$this$_send$con.cdate;
9725 ttl = _yield$this$_send$con.tempConvTTL;
9726 data = _objectSpread$8({
9727 name: name,
9728 "transient": _transient3,
9729 unique: unique,
9730 id: cid,
9731 createdAt: cdate,
9732 updatedAt: cdate,
9733 lastMessageAt: null,
9734 creator: this.id,
9735 members: _transient3 ? [] : members
9736 }, properties);
9737 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
9738 _context20.next = 31;
9739 return this.parseConversation(data);
9740
9741 case 31:
9742 conversation = _context20.sent;
9743 return _context20.abrupt("return", this._upsertConversationToCache(conversation));
9744
9745 case 33:
9746 case "end":
9747 return _context20.stop();
9748 }
9749 }
9750 }, _callee20, this);
9751 }));
9752
9753 function createConversation() {
9754 return _createConversation.apply(this, arguments);
9755 }
9756
9757 return createConversation;
9758 }()
9759 /**
9760 * 创建一个聊天室
9761 * @since 4.0.0
9762 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
9763 * @param {String} [options.name] 对话的名字
9764 * @return {Promise.<ChatRoom>}
9765 */
9766 ;
9767
9768 _proto.createChatRoom =
9769 /*#__PURE__*/
9770 function () {
9771 var _createChatRoom = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee21(param) {
9772 return _regeneratorRuntime.wrap(function _callee21$(_context21) {
9773 while (1) {
9774 switch (_context21.prev = _context21.next) {
9775 case 0:
9776 return _context21.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
9777 "transient": true,
9778 members: null,
9779 unique: false,
9780 _tempConv: false
9781 })));
9782
9783 case 1:
9784 case "end":
9785 return _context21.stop();
9786 }
9787 }
9788 }, _callee21, this);
9789 }));
9790
9791 function createChatRoom(_x21) {
9792 return _createChatRoom.apply(this, arguments);
9793 }
9794
9795 return createChatRoom;
9796 }()
9797 /**
9798 * 创建一个临时对话
9799 * @since 4.0.0
9800 * @param {Object} options
9801 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
9802 * @param {String} [options.ttl] 对话存在时间,单位为秒,最大值与默认值均为 86400(一天),过期后该对话不再可用。
9803 * @return {Promise.<TemporaryConversation>}
9804 */
9805 ;
9806
9807 _proto.createTemporaryConversation =
9808 /*#__PURE__*/
9809 function () {
9810 var _createTemporaryConversation = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee22(_ref13) {
9811 var _tempConvTTL, param;
9812
9813 return _regeneratorRuntime.wrap(function _callee22$(_context22) {
9814 while (1) {
9815 switch (_context22.prev = _context22.next) {
9816 case 0:
9817 _tempConvTTL = _ref13.ttl, param = _objectWithoutProperties(_ref13, ["ttl"]);
9818 return _context22.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
9819 _tempConv: true,
9820 _tempConvTTL: _tempConvTTL
9821 })));
9822
9823 case 2:
9824 case "end":
9825 return _context22.stop();
9826 }
9827 }
9828 }, _callee22, this);
9829 }));
9830
9831 function createTemporaryConversation(_x22) {
9832 return _createTemporaryConversation.apply(this, arguments);
9833 }
9834
9835 return createTemporaryConversation;
9836 }() // jsdoc-ignore-start
9837 ;
9838
9839 _proto. // jsdoc-ignore-end
9840 _doSendRead = function _doSendRead() {
9841 var _this10 = this;
9842
9843 // if not connected, just skip everything
9844 if (!this._connection.is('connected')) return;
9845 var buffer = internal(this).readConversationsBuffer;
9846 var conversations = Array.from(buffer);
9847 if (!conversations.length) return;
9848 var ids = conversations.map(function (conversation) {
9849 if (!(conversation instanceof ConversationBase)) {
9850 throw new TypeError("".concat(conversation, " is not a Conversation"));
9851 }
9852
9853 return conversation.id;
9854 });
9855
9856 this._debug("mark [".concat(ids, "] as read"));
9857
9858 buffer.clear();
9859
9860 this._sendReadCommand(conversations)["catch"](function (error) {
9861 _this10._debug('send read failed: %O', error);
9862
9863 conversations.forEach(buffer.add.bind(buffer));
9864 });
9865 };
9866
9867 _proto._sendReadCommand = function _sendReadCommand(conversations) {
9868 var _this11 = this;
9869
9870 return this._send(new GenericCommand({
9871 cmd: 'read',
9872 readMessage: new ReadCommand({
9873 convs: conversations.map(function (conversation) {
9874 return new ReadTuple({
9875 cid: conversation.id,
9876 mid: conversation.lastMessage && conversation.lastMessage.from !== _this11.id ? conversation.lastMessage.id : undefined,
9877 timestamp: (conversation.lastMessageAt || new Date()).getTime()
9878 });
9879 })
9880 })
9881 }), false);
9882 };
9883
9884 return IMClient;
9885}(EventEmitter), (_applyDecoratedDescriptor(_class$3.prototype, "_doSendAck", [_dec$2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendAck"), _class$3.prototype), _applyDecoratedDescriptor(_class$3.prototype, "_doSendRead", [_dec2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendRead"), _class$3.prototype)), _class$3));
9886/**
9887 * 修改、撤回消息的原因
9888 * @typedef PatchReason
9889 * @type {Object}
9890 * @property {number} code 负数为内置 code,正数为开发者在 hook 中自定义的 code。比如因为敏感词过滤被修改的 code 为 -4408。
9891 * @property {string} [detail] 具体的原因说明。
9892 */
9893
9894var RECONNECT_ERROR = 'reconnecterror';
9895
9896var CoreEvent = /*#__PURE__*/Object.freeze({
9897 __proto__: null,
9898 RECONNECT_ERROR: RECONNECT_ERROR,
9899 DISCONNECT: DISCONNECT,
9900 RECONNECT: RECONNECT,
9901 RETRY: RETRY,
9902 SCHEDULE: SCHEDULE,
9903 OFFLINE: OFFLINE,
9904 ONLINE: ONLINE
9905});
9906
9907var _class$4;
9908
9909function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
9910
9911function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$9(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
9912
9913var // jsdoc-ignore-end
9914BinaryMessage = IE10Compatible(_class$4 = /*#__PURE__*/function (_Message) {
9915 _inheritsLoose(BinaryMessage, _Message);
9916
9917 /**
9918 * 二进制消息
9919 * @extends Message
9920 * @param {ArrayBuffer} buffer
9921 * @since 4.0.0
9922 */
9923 function BinaryMessage(buffer) {
9924 if (!(buffer instanceof ArrayBuffer)) {
9925 throw new TypeError("".concat(buffer, " is not an ArrayBuffer"));
9926 }
9927
9928 return _Message.call(this, buffer) || this;
9929 }
9930 /**
9931 * @type ArrayBuffer
9932 */
9933
9934
9935 BinaryMessage.validate = function validate(target) {
9936 return target instanceof ArrayBuffer;
9937 };
9938
9939 var _proto = BinaryMessage.prototype;
9940
9941 _proto.toJSON = function toJSON() {
9942 return _objectSpread$9(_objectSpread$9({}, _Message.prototype._toJSON.call(this)), {}, {
9943 data: base64Arraybuffer.encode(this.content)
9944 });
9945 };
9946
9947 _proto.toFullJSON = function toFullJSON() {
9948 return _objectSpread$9(_objectSpread$9({}, _Message.prototype.toFullJSON.call(this)), {}, {
9949 bin: true,
9950 data: base64Arraybuffer.encode(this.content)
9951 });
9952 };
9953
9954 _createClass(BinaryMessage, [{
9955 key: "buffer",
9956 get: function get() {
9957 return this.content;
9958 },
9959 set: function set(buffer) {
9960 this.content = buffer;
9961 }
9962 }]);
9963
9964 return BinaryMessage;
9965}(Message)) || _class$4;
9966
9967var _dec$3, _class$5;
9968
9969var // jsdoc-ignore-end
9970TextMessage = (_dec$3 = messageType(-1), _dec$3(_class$5 = IE10Compatible(_class$5 = /*#__PURE__*/function (_TypedMessage) {
9971 _inheritsLoose(TextMessage, _TypedMessage);
9972
9973 /**
9974 * 文类类型消息
9975 * @extends TypedMessage
9976 * @param {String} [text='']
9977 * @throws {TypeError} text 不是 String 类型
9978 */
9979 function TextMessage() {
9980 var _this;
9981
9982 var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
9983
9984 if (typeof text !== 'string') {
9985 throw new TypeError("".concat(text, " is not a string"));
9986 }
9987
9988 _this = _TypedMessage.call(this) || this;
9989
9990 _this.setText(text);
9991
9992 return _this;
9993 }
9994
9995 return TextMessage;
9996}(TypedMessage)) || _class$5) || _class$5);
9997/**
9998 * @name TYPE
9999 * @memberof TextMessage
10000 * @type Number
10001 * @static
10002 * @const
10003 */
10004
10005var _class$6;
10006
10007function ownKeys$a(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
10008
10009function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$a(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
10010
10011function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
10012
10013function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10014
10015function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
10016var debug$c = d('LC:MessageParser');
10017
10018var tryParseJson = function tryParseJson(target, key, descriptor) {
10019 var fn = descriptor.value; // eslint-disable-next-line no-param-reassign
10020
10021 descriptor.value = function wrapper(param) {
10022 var content;
10023
10024 if (typeof param !== 'string') {
10025 content = param;
10026 } else {
10027 try {
10028 content = JSON.parse(param);
10029 } catch (error) {
10030 content = param;
10031 }
10032 }
10033
10034 return fn.call(this, content);
10035 };
10036};
10037
10038var applyPlugins = function applyPlugins(target, key, descriptor) {
10039 var fn = descriptor.value; // eslint-disable-next-line no-param-reassign
10040
10041 descriptor.value = function wrapper(json) {
10042 var _this = this;
10043
10044 return Promise.resolve(json).then(applyMiddlewares(this._plugins.beforeMessageParse)).then(function (decoratedJson) {
10045 return fn.call(_this, decoratedJson);
10046 }).then(applyMiddlewares(this._plugins.afterMessageParse));
10047 };
10048};
10049
10050var MessageParser = (_class$6 = /*#__PURE__*/function () {
10051 /**
10052 * 消息解析器
10053 * @param {Object} plugins 插件,插件的 messageClasses 会自动被注册,在解析时 beforeMessageParse 与 afterMessageParse Middleware 会被应用。
10054 */
10055 function MessageParser() {
10056 var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
10057 this._plugins = plugins;
10058 this._messageClasses = [];
10059 this.register(plugins.messageClasses);
10060 }
10061 /**
10062 * 注册消息类
10063 *
10064 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
10065 * 建议继承自 {@link TypedMessage},也可以传入一个消息类数组。
10066 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
10067 */
10068
10069
10070 var _proto = MessageParser.prototype;
10071
10072 _proto.register = function register(messageClasses) {
10073 var _this2 = this;
10074
10075 ensureArray(messageClasses).map(function (klass) {
10076 return _this2._register(klass);
10077 });
10078 };
10079
10080 _proto._register = function _register(messageClass) {
10081 if (messageClass && messageClass.parse && messageClass.prototype && messageClass.prototype.getPayload) {
10082 this._messageClasses.unshift(messageClass);
10083 } else {
10084 throw new TypeError('Invalid messageClass');
10085 }
10086 } // jsdoc-ignore-start
10087 ;
10088
10089 _proto. // jsdoc-ignore-end
10090
10091 /**
10092 * 解析消息内容
10093 * @param {Object | string | any} target 消息内容,如果是字符串会尝试 parse 为 JSON。
10094 * @return {AVMessage} 解析后的消息
10095 * @throws {Error} 如果不匹配任何注册的消息则抛出异常
10096 */
10097 parse = function parse(content) {
10098 debug$c('parsing message: %O', content); // eslint-disable-next-line
10099
10100 var _iterator = _createForOfIteratorHelper(this._messageClasses),
10101 _step;
10102
10103 try {
10104 for (_iterator.s(); !(_step = _iterator.n()).done;) {
10105 var Klass = _step.value;
10106 var contentCopy = isPlainObject(content) ? _objectSpread$a({}, content) : content;
10107 var valid = void 0;
10108 var result = void 0;
10109
10110 try {
10111 valid = Klass.validate(contentCopy);
10112 } catch (error) {// eslint-disable-line no-empty
10113 }
10114
10115 if (valid) {
10116 try {
10117 result = Klass.parse(contentCopy);
10118 } catch (error) {
10119 console.warn('parsing a valid message content error', {
10120 error: error,
10121 Klass: Klass,
10122 content: contentCopy
10123 });
10124 }
10125
10126 if (result !== undefined) {
10127 debug$c('parse result: %O', result);
10128 return result;
10129 }
10130 }
10131 }
10132 } catch (err) {
10133 _iterator.e(err);
10134 } finally {
10135 _iterator.f();
10136 }
10137
10138 throw new Error('No Message Class matched');
10139 };
10140
10141 return MessageParser;
10142}(), (_applyDecoratedDescriptor(_class$6.prototype, "parse", [tryParseJson, applyPlugins], Object.getOwnPropertyDescriptor(_class$6.prototype, "parse"), _class$6.prototype)), _class$6);
10143
10144function ownKeys$b(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
10145
10146function _objectSpread$b(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$b(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$b(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
10147var debug$d = d('LC:IMPlugin');
10148/**
10149 * 消息优先级枚举
10150 * @enum {Number}
10151 * @since 3.3.0
10152 */
10153
10154var MessagePriority = {
10155 /** 高 */
10156 HIGH: 1,
10157
10158 /** 普通 */
10159 NORMAL: 2,
10160
10161 /** 低 */
10162 LOW: 3
10163};
10164Object.freeze(MessagePriority);
10165/**
10166 * 为 Conversation 定义一个新属性
10167 * @param {String} prop 属性名
10168 * @param {Object} [descriptor] 属性的描述符,参见 {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description getOwnPropertyDescriptor#Description - MDN},默认为该属性名对应的 Conversation 自定义属性的 getter/setter
10169 * @returns void
10170 * @example
10171 *
10172 * conversation.get('type');
10173 * conversation.set('type', 1);
10174 *
10175 * // equals to
10176 * defineConversationProperty('type');
10177 * conversation.type;
10178 * conversation.type = 1;
10179 */
10180
10181var defineConversationProperty = function defineConversationProperty(prop) {
10182 var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
10183 get: function get() {
10184 return this.get(prop);
10185 },
10186 set: function set(value) {
10187 this.set(prop, value);
10188 }
10189 };
10190 Object.defineProperty(Conversation.prototype, prop, descriptor);
10191};
10192
10193var onRealtimeCreate = function onRealtimeCreate(realtime) {
10194 /* eslint-disable no-param-reassign */
10195 var deviceId = uuid();
10196 realtime._IMClients = {};
10197 realtime._IMClientsCreationCount = 0;
10198 var messageParser = new MessageParser(realtime._plugins);
10199 realtime._messageParser = messageParser;
10200
10201 var signAVUser = /*#__PURE__*/function () {
10202 var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(user) {
10203 return _regeneratorRuntime.wrap(function _callee$(_context) {
10204 while (1) {
10205 switch (_context.prev = _context.next) {
10206 case 0:
10207 return _context.abrupt("return", realtime._request({
10208 method: 'POST',
10209 path: '/rtm/sign',
10210 data: {
10211 session_token: user.getSessionToken()
10212 }
10213 }));
10214
10215 case 1:
10216 case "end":
10217 return _context.stop();
10218 }
10219 }
10220 }, _callee);
10221 }));
10222
10223 return function signAVUser(_x) {
10224 return _ref.apply(this, arguments);
10225 };
10226 }();
10227 /**
10228 * 注册消息类
10229 *
10230 * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容
10231 *
10232 * @memberof Realtime
10233 * @instance
10234 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
10235 * 建议继承自 {@link TypedMessage}
10236 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
10237 */
10238
10239
10240 var register = messageParser.register.bind(messageParser);
10241 /**
10242 * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例
10243 * @memberof Realtime
10244 * @instance
10245 * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity,
10246 * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。
10247 * @param {Object} [options]
10248 * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details
10249 * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法
10250 * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法
10251 * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能
10252 * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录
10253 * @return {Promise.<IMClient>}
10254 */
10255
10256 var createIMClient = /*#__PURE__*/function () {
10257 var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(identity) {
10258 var _realtime$_open$then;
10259
10260 var _ref3,
10261 tag,
10262 isReconnect,
10263 clientOptions,
10264 lagecyTag,
10265 id,
10266 buildinOptions,
10267 sessionToken,
10268 _tag,
10269 promise,
10270 _args2 = arguments;
10271
10272 return _regeneratorRuntime.wrap(function _callee2$(_context2) {
10273 while (1) {
10274 switch (_context2.prev = _context2.next) {
10275 case 0:
10276 _ref3 = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}, tag = _ref3.tag, isReconnect = _ref3.isReconnect, clientOptions = _objectWithoutProperties(_ref3, ["tag", "isReconnect"]);
10277 lagecyTag = _args2.length > 2 ? _args2[2] : undefined;
10278 buildinOptions = {};
10279
10280 if (!identity) {
10281 _context2.next = 19;
10282 break;
10283 }
10284
10285 if (!(typeof identity === 'string')) {
10286 _context2.next = 8;
10287 break;
10288 }
10289
10290 id = identity;
10291 _context2.next = 17;
10292 break;
10293
10294 case 8:
10295 if (!(identity.id && identity.getSessionToken)) {
10296 _context2.next = 16;
10297 break;
10298 }
10299
10300 id = identity.id;
10301 sessionToken = identity.getSessionToken();
10302
10303 if (sessionToken) {
10304 _context2.next = 13;
10305 break;
10306 }
10307
10308 throw new Error('User must be authenticated');
10309
10310 case 13:
10311 buildinOptions.signatureFactory = signAVUser;
10312 _context2.next = 17;
10313 break;
10314
10315 case 16:
10316 throw new TypeError('Identity must be a String or an AV.User');
10317
10318 case 17:
10319 if (!(realtime._IMClients[id] !== undefined)) {
10320 _context2.next = 19;
10321 break;
10322 }
10323
10324 return _context2.abrupt("return", realtime._IMClients[id]);
10325
10326 case 19:
10327 if (lagecyTag) {
10328 console.warn('DEPRECATION createIMClient tag param: Use options.tag instead.');
10329 }
10330
10331 _tag = tag || lagecyTag;
10332 promise = (_realtime$_open$then = realtime._open().then(function (connection) {
10333 var client = new IMClient(id, _objectSpread$b(_objectSpread$b({}, buildinOptions), clientOptions), {
10334 _connection: connection,
10335 _request: realtime._request.bind(realtime),
10336 _messageParser: messageParser,
10337 _plugins: realtime._plugins,
10338 _identity: identity
10339 });
10340 connection.on(RECONNECT, function () {
10341 return client._open(realtime._options.appId, _tag, deviceId, true)
10342 /**
10343 * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生
10344 * @event IMClient#RECONNECT
10345 * @see Realtime#event:RECONNECT
10346 * @since 3.2.0
10347 */
10348
10349 /**
10350 * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误)
10351 * @event IMClient#RECONNECT_ERROR
10352 * @since 3.2.0
10353 */
10354 .then(function () {
10355 return client.emit(RECONNECT);
10356 }, function (error) {
10357 return client.emit(RECONNECT_ERROR, error);
10358 });
10359 });
10360
10361 internal(client)._eventemitter.on('beforeclose', function () {
10362 delete realtime._IMClients[client.id];
10363
10364 if (realtime._firstIMClient === client) {
10365 delete realtime._firstIMClient;
10366 }
10367 }, realtime);
10368
10369 internal(client)._eventemitter.on('close', function () {
10370 realtime._deregister(client);
10371 }, realtime);
10372
10373 return client._open(realtime._options.appId, _tag, deviceId, isReconnect).then(function () {
10374 realtime._IMClients[client.id] = client;
10375 realtime._IMClientsCreationCount += 1;
10376
10377 if (realtime._IMClientsCreationCount === 1) {
10378 client._omitPeerId(true);
10379
10380 realtime._firstIMClient = client;
10381 } else if (realtime._IMClientsCreationCount > 1 && realtime._firstIMClient) {
10382 realtime._firstIMClient._omitPeerId(false);
10383 }
10384
10385 realtime._register(client);
10386
10387 return client;
10388 })["catch"](function (error) {
10389 delete realtime._IMClients[client.id];
10390 throw error;
10391 });
10392 })).then.apply(_realtime$_open$then, _toConsumableArray(finalize(function () {
10393 realtime._deregisterPending(promise);
10394 })))["catch"](function (error) {
10395 delete realtime._IMClients[id];
10396 throw error;
10397 });
10398
10399 if (identity) {
10400 realtime._IMClients[id] = promise;
10401 }
10402
10403 realtime._registerPending(promise);
10404
10405 return _context2.abrupt("return", promise);
10406
10407 case 25:
10408 case "end":
10409 return _context2.stop();
10410 }
10411 }
10412 }, _callee2);
10413 }));
10414
10415 return function createIMClient(_x2) {
10416 return _ref2.apply(this, arguments);
10417 };
10418 }();
10419
10420 Object.assign(realtime, {
10421 register: register,
10422 createIMClient: createIMClient
10423 });
10424 /* eslint-enable no-param-reassign */
10425};
10426
10427var beforeCommandDispatch = function beforeCommandDispatch(command, realtime) {
10428 var isIMCommand = command.service === null || command.service === 2;
10429 if (!isIMCommand) return true;
10430 var targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient;
10431
10432 if (targetClient) {
10433 Promise.resolve(targetClient).then(function (client) {
10434 return client._dispatchCommand(command);
10435 })["catch"](debug$d);
10436 } else {
10437 debug$d('[WARN] Unexpected message received without any live client match: %O', trim(command));
10438 }
10439
10440 return false;
10441};
10442
10443var IMPlugin = {
10444 name: 'leancloud-realtime-plugin-im',
10445 onRealtimeCreate: onRealtimeCreate,
10446 beforeCommandDispatch: beforeCommandDispatch,
10447 messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage]
10448};
10449
10450function ownKeys$c(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
10451
10452function _objectSpread$c(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$c(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$c(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
10453Realtime.defineConversationProperty = defineConversationProperty;
10454Realtime.__preRegisteredPlugins = [IMPlugin];
10455
10456var Event = _objectSpread$c(_objectSpread$c({}, CoreEvent), IMEvent);
10457
10458/** core + plugins + platform adapters */
10459setAdapters({
10460 WebSocket: platformAdaptersNode.WebSocket,
10461 request: platformAdaptersNode.request
10462});
10463
10464exports.EventEmitter = EventEmitter;
10465exports.BinaryMessage = BinaryMessage;
10466exports.ChatRoom = ChatRoom;
10467exports.Conversation = Conversation;
10468exports.ConversationMemberRole = ConversationMemberRole;
10469exports.ConversationQuery = ConversationQuery;
10470exports.ErrorCode = ErrorCode;
10471exports.Event = Event;
10472exports.IE10Compatible = IE10Compatible;
10473exports.IMPlugin = IMPlugin;
10474exports.Message = Message;
10475exports.MessageParser = MessageParser;
10476exports.MessagePriority = MessagePriority;
10477exports.MessageQueryDirection = MessageQueryDirection;
10478exports.MessageStatus = MessageStatus;
10479exports.Promise = polyfilledPromise;
10480exports.Protocals = message;
10481exports.Protocols = message;
10482exports.Realtime = Realtime;
10483exports.RecalledMessage = RecalledMessage;
10484exports.ServiceConversation = ServiceConversation;
10485exports.TemporaryConversation = TemporaryConversation;
10486exports.TextMessage = TextMessage;
10487exports.TypedMessage = TypedMessage;
10488exports.debug = debug$2;
10489exports.defineConversationProperty = defineConversationProperty;
10490exports.getAdapter = getAdapter;
10491exports.messageField = messageField;
10492exports.messageType = messageType;
10493exports.setAdapters = setAdapters;
10494//# sourceMappingURL=im-node.js.map