x-next 0.0.0-alpha.1

Sign up to get free protection for your applications and to get access to all the features.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Pudon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,4 @@
1
+ # x-next
2
+ xiaocaiyun.com 前端组件库。
3
+
4
+
@@ -0,0 +1,2 @@
1
+ function consoleLog(e,t,n,c){console.log("".concat("\n"," %c ").concat(e," %c ").concat(t," ").concat("\n"),"color: ".concat(n,"; background: ").concat(c,"; padding:5px 0;border-radius:3px 0 0 3px;"),"color:#666666;background: #f1f5fa; padding:5px 0;border-radius:0 3px 3px 0;")}function now(){return"".concat((new Date).getHours()<10?"0"+(new Date).getHours():(new Date).getHours(),":").concat((new Date).getMinutes()<10?"0"+(new Date).getMinutes():(new Date).getMinutes(),":").concat((new Date).getSeconds()<10?"0"+(new Date).getSeconds():(new Date).getSeconds())}function jsonStringify2Parse(t){if("string"==typeof t)try{return JSON.parse(t)}catch(e){return JSON.parse(JSON.stringify('{"value":'.concat(t)))}return{}}var extendStatics=function(e,t){return(extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};function __extends(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}extendStatics(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}var WebSocketBucketState,Exception=function(c){function e(e,t){var n=c.call(this,t)||this;return n.name="Client.io Error",n.message="Error message",n.name=e||n.name,n.message=t||n.message,n.stack=(new Error).stack,n}return __extends(e,c),e}(Error),WebSocketBucket=(!function(e){e.CONNECTING="CONNECTING",e.OPEN="OPEN",e.CLOSING="CLOSING",e.CLOSED="CLOSED",e.FAIL="FAIL"}(WebSocketBucketState=WebSocketBucketState||{}),function(){function k(){this.bucketName=k.DEFAULT_NAME,this.buckets=new Map,this.bucketName=k.DEFAULT_NAME}return k.create=function(e){var c,o,t,n=e.url,a=e.name,r=e.heartbeat,s=e.heartRate,s=void 0===s?3e3:s,i=e.restartTime,i=void 0===i?5e3:i,u=e.restartTimes,u=void 0===u?0:u,f=e.restartedTimes,g=void 0===f?0:f,f=e.receive,e=e.send;if(/(ws|wss):\/\/\s*/.test(n))return c=a||k.getBucketName(a),t=new WebSocket(n),o=-1,t.onopen=function(e){consoleLog("".concat(c," ▶ SUCCESS"),"◔ ".concat(now()),"#ffffff","#1bc800"),k.setBucketKeyValue("restartedTimes",0,c),k.bindMessage(a)},t.onerror=function(e){consoleLog("".concat(c," ▶ ERROR"),"◔ ".concat(now()," ▶ ").concat(c),"#ffffff","#c80000")},t.onclose=function(e){consoleLog("".concat(c," ▶ CLOSE"),"◔ ".concat(now()," ▶ ").concat(c),"#ffffff","#000000"),clearInterval(o);var t=k.getBucket(c),n=(t.restartedTimes!==g?g=t.restartedTimes+1:g+=1,Math.pow(2,g-1)*t.restartTime);consoleLog("".concat(c," ▶ REBOOT WAITING"),"◔ ".concat(now()," ▶ ").concat(c," RESTART IN ").concat(Math.round(n/1e3)," SECONDS"),"#ffffff","#00c8b4"),setTimeout(function(){t.restartedTimes=g,k.create(t)},n)},"function"==typeof r&&(o=setInterval(function(){r(function(e){k.sendMessage(e,c)})},s)),t={name:c,client:t,url:n,heartbeat:r,heartRate:s,heartRateTimer:o,restartTime:i,restartTimes:u,restartedTimes:g,receive:f,send:e,receiveMessageCallbacks:new Map},k.getInstance().buckets.set(c,t),k.getBucketClient(c);throw new Error("传入的url必须是ws或wss地址")},k.getBucket=function(e){e=k.getBucketName(e);if(!k.getInstance().buckets.has(e))throw new Exception("名称为".concat(e,"是WebSocket实例不存在"),k.NO_BUCKET);var t=k.getInstance().buckets.get(e);if(t&&t.client instanceof WebSocket)return t;throw new Exception("名称为".concat(e,"是WebSocket实例不存在"),k.NO_BUCKET_CLIENT)},k.setBucketKeyValue=function(e,t,n){var c=k.getBucket(n);if(!c||"object"!=typeof c||!Reflect.has(c,e))throw new Exception("名称为".concat(k.getBucketName(n),"的WebSocket Bucket不存在").concat(e,"属性"),k.NO_BUCKET_KEY);c[e]=t,k.getInstance().buckets.set(n,c)},k.getBucketClient=function(e){try{return k.getBucket(e).client}catch(e){console.log("Exception",e)}},k.getBucketName=function(e){return e||k.getInstance().bucketName},k.getBucketClientState=function(e){try{switch(k.getBucketClient(e).readyState){case WebSocket.CONNECTING:return WebSocketBucketState.CONNECTING;case WebSocket.OPEN:return WebSocketBucketState.OPEN;case WebSocket.CLOSING:return WebSocketBucketState.CLOSING;case WebSocket.CLOSED:return WebSocketBucketState.CLOSED;default:return WebSocketBucketState.FAIL}}catch(e){return WebSocketBucketState.FAIL}},k.wsErrorEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onerror=function(e){"function"==typeof t?t(e):console.warn("监听ws报错的回调函数wsError不存在")}}catch(e){console.warn("".concat(e))}},k.wsCloseEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onclose=function(e){"function"==typeof t?t(e):console.warn("监听ws关闭的回调函数wsClose不存在")}}catch(e){console.warn("".concat(e))}},k.wsOpenEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onopen=function(e){"function"==typeof t?t(e):console.warn("wsOpenEventListener缺少回调函数")}}catch(e){console.warn("".concat(e))}},k.sendMessage=function(e,t,n){if(void 0===e&&(e=""),void 0===n&&(n=!1),["CONNECTING","CLOSING","CLOSED"].includes(k.getBucketClientState(t=void 0===t?void 0:t)))n||console.warn("BUCKET:".concat(k.getBucketName(t),"|STATUS:").concat(k.getBucketClientState(t),"|无法进行消息发送"));else try{var c=k.getBucket(t).send;"function"==typeof c&&(e=c(e)),k.getBucketClient(t).send(e)}catch(e){console.warn("".concat(e))}},k.bindMessage=function(e){0<k.getBucket(e).receiveMessageCallbacks.size&&k.registerOnMessage(e)},k.receiveMessage=function(e,t){try{var n;"function"==typeof e?(n="".concat(e),k.getBucket(t).receiveMessageCallbacks.get(n)||k.getBucket(t).receiveMessageCallbacks.set(n,e)):console.warn("receiveMessage缺少回调"),k.registerOnMessage(t)}catch(e){console.warn("".concat(e))}},k.registerOnMessage=function(n){k.getBucketClient(n).onmessage=function(t){var e=k.getBucket(n).receive;"function"==typeof e&&(t=e(t,function(e){k.sendMessage(e,n)})),k.getBucket(n).receiveMessageCallbacks.forEach(function(e){try{e(t)}catch(e){console.warn("".concat(e))}})}},k.getInstance=function(){var e=k.instance;return e=e&&e instanceof k?e:k.instance=new k},k.NO_BUCKET="10001",k.NO_BUCKET_CLIENT="10002",k.NO_BUCKET_KEY="10003",k.DEFAULT_NAME="DEFAULT_BUCKET",k}());export{WebSocketBucket,jsonStringify2Parse};
2
+ //# sourceMappingURL=client.io.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.io.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Exception Class
3
+ * throw diy Exception
4
+ * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error
5
+ * 目前原生的错误类型
6
+ * Error [一般错误类型]
7
+ * SyntaxError [语法错误]
8
+ * ReferenceError [不存在的变量]
9
+ * RangeError [超出有效范围]
10
+ * TypeError [非预期类型]
11
+ * URIError [URI参数错误]
12
+ * EvalError [eval函数没有正确执行]
13
+ * example:: throw new Exception() catch(error) error.message,error.name,error.code,error.stack
14
+ * NewException extends Exception diy yourself Exception;
15
+ */
16
+ export declare class Exception extends Error {
17
+ name: string;
18
+ message: string;
19
+ /**
20
+ * Error constructor
21
+ * @param {String} name 自定义错误名称
22
+ * @param {String|Number} message 自定义错误提示
23
+ */
24
+ constructor(name?: string, message?: string);
25
+ }
@@ -0,0 +1,2 @@
1
+ export { WebSocketBucket } from './websocket';
2
+ export { jsonStringify2Parse } from './util';
@@ -0,0 +1,33 @@
1
+ export declare type WebSocketUrl = `ws://${string}` | `wss://${string}`;
2
+ export declare type Heartbeat = (callback: HeartbeatCallback) => void;
3
+ export declare type HeartbeatCallback = (msg: string) => void;
4
+ export declare type ReceiveInterceptor = (event: MessageEvent<any>, send: (msg: SendMsg) => void) => any;
5
+ export declare type SendInterceptor = (event: any) => any;
6
+ export declare type WebSocketBucketCreate = {
7
+ url: WebSocketUrl;
8
+ name?: string;
9
+ heartbeat?: Heartbeat;
10
+ heartRate?: Millisecond;
11
+ restartTime?: Millisecond;
12
+ restartTimes?: number;
13
+ restartedTimes?: number;
14
+ receive?: ReceiveInterceptor;
15
+ send?: SendInterceptor;
16
+ };
17
+ export declare type WebSocketBucketOptions = {
18
+ name: string;
19
+ client: WebSocket;
20
+ url: WebSocketUrl;
21
+ heartbeat?: Heartbeat;
22
+ heartRate: Millisecond;
23
+ heartRateTimer: number;
24
+ restartTime: Millisecond;
25
+ restartTimes: number;
26
+ restartedTimes: number;
27
+ receive?: ReceiveInterceptor;
28
+ send?: SendInterceptor;
29
+ receiveMessageCallbacks: Map<string, (event: MessageEvent<any>) => void>;
30
+ [key: string]: unknown;
31
+ };
32
+ export declare type Millisecond = number;
33
+ export declare type SendMsg = string | ArrayBufferLike | Blob | ArrayBufferView;
@@ -0,0 +1,36 @@
1
+ export declare function isArray(obj: any): obj is any[];
2
+ export declare function isNull(obj: any): obj is null;
3
+ export declare function isBoolean(obj: unknown): obj is boolean;
4
+ export declare function isObject(obj: any): obj is Record<string, unknown>;
5
+ export declare const isPromise: <T>(obj: unknown) => obj is Promise<T>;
6
+ export declare function isString(obj: any): obj is string;
7
+ export declare function isNumber(obj: any): obj is number;
8
+ export declare function isRegExp(obj: any): boolean;
9
+ export declare function isDate(obj: any): boolean;
10
+ export declare function isColor(color: any): boolean;
11
+ export declare function isUndefined(obj: any): obj is undefined;
12
+ export declare function isFunction(obj: any): obj is (...args: any[]) => any;
13
+ export declare function isClass(value: unknown): boolean;
14
+ export declare function isEmptyObject(obj: any): boolean;
15
+ export declare function isEmpty(obj: any): boolean;
16
+ export declare function isExist(obj: any): boolean;
17
+ export declare function isWindow(el: any): el is Window;
18
+ /**
19
+ * 控制台消息打印
20
+ * @param name
21
+ * @param message
22
+ * @param color
23
+ * @param bgColor
24
+ */
25
+ export declare function consoleLog(name: string, message: string, color: string, bgColor: string): void;
26
+ /**
27
+ * 当前时间
28
+ * @description 用于控制台打印使用
29
+ */
30
+ export declare function now(): string;
31
+ /**
32
+ * jsonStringify2Parse
33
+ * @param value
34
+ * @description 将JSON字符串转换为JSON对象
35
+ */
36
+ export declare function jsonStringify2Parse(value: unknown): any;
@@ -0,0 +1,118 @@
1
+ import { SendMsg, WebSocketBucketCreate, WebSocketBucketOptions } from './types';
2
+ declare enum WebSocketBucketState {
3
+ CONNECTING = "CONNECTING",
4
+ OPEN = "OPEN",
5
+ CLOSING = "CLOSING",
6
+ CLOSED = "CLOSED",
7
+ FAIL = "FAIL"
8
+ }
9
+ /**
10
+ * @class WebSocketBucket
11
+ * @public
12
+ * @classdesc WebSocket快速部署开发,可同开多个WebSocket,并分别命名,可对多个Client进行监听,每一个Bucket为Client运行所必需的空间环境。
13
+ * @example
14
+ * WebSocketBucket.create({url:'wss://ws.demo.com/socket-io'})
15
+ * WebSocketBucket.sendMessage('Hello World')
16
+ */
17
+ export declare class WebSocketBucket {
18
+ static NO_BUCKET: string;
19
+ static NO_BUCKET_CLIENT: string;
20
+ static NO_BUCKET_KEY: string;
21
+ static DEFAULT_NAME: string;
22
+ client: WebSocket | undefined;
23
+ buckets: Map<string, WebSocketBucketOptions>;
24
+ bucketName: string;
25
+ static instance: WebSocketBucket;
26
+ constructor();
27
+ /**
28
+ * create
29
+ * 创建一个Bucket空间
30
+ * @param url {string} 服务地址(SSL)
31
+ * @param name {string} 实例名称
32
+ * @param heartbeat {function} (sendMessage,instanceName)=>void 心跳执行函数 send {Function} 消息发送函数
33
+ * @param heartRate 心跳频率 毫秒
34
+ * @param restartTime 重启时间,按照通用方式,例如第一次3秒后重连如果没连上第二次就3*2=6秒后重连,如果还没有连上第三次就是3*2*2=12秒后重连,以此类推直到重连上为止,一旦重连上重连等待时间就会自动回到3秒这个初始值
35
+ * @param restartTimes 重启次数,0为不限制,>0为最大重启次数
36
+ * @param restartedTimes 已重启次数
37
+ * @param receive 接收拦截器
38
+ * @param send 发送拦截器
39
+ */
40
+ static create({ url, name, heartbeat, heartRate, restartTime, restartTimes, restartedTimes, receive, send, }: WebSocketBucketCreate): WebSocket | undefined;
41
+ /**
42
+ * readBucket
43
+ * 读取Bucket空间
44
+ * @param name
45
+ * @return WebSocketBucketOptions
46
+ */
47
+ static getBucket(name: string | undefined): WebSocketBucketOptions;
48
+ /**
49
+ * setBucketKeyValue
50
+ * 设置Bucket属性值
51
+ * @param key
52
+ * @param value
53
+ * @param name
54
+ */
55
+ static setBucketKeyValue(key: string, value: number, name: string): void;
56
+ /**
57
+ * 获取Bucket客户端
58
+ * @param name
59
+ */
60
+ static getBucketClient(name: string | undefined): WebSocket | undefined;
61
+ /**
62
+ * 获取Bucket空间名称
63
+ * @param name
64
+ */
65
+ static getBucketName(name: string | undefined): string;
66
+ /**
67
+ * 获取Bucket客户端状态
68
+ * @param name
69
+ */
70
+ static getBucketClientState(name: string | undefined): WebSocketBucketState;
71
+ /**
72
+ * 监听WebSocket报错
73
+ * @param callback
74
+ * @param name
75
+ */
76
+ static wsErrorEventListener(callback: (event: Event) => void, name?: undefined): void;
77
+ /**
78
+ * 监听WebSocket关闭
79
+ * @param callback
80
+ * @param name
81
+ */
82
+ static wsCloseEventListener(callback: (event: CloseEvent) => void, name?: undefined): void;
83
+ /**
84
+ * 监听WebSocket打开
85
+ * @param callback
86
+ * @param name
87
+ */
88
+ static wsOpenEventListener(callback: (event: Event) => void, name?: undefined): void;
89
+ /**
90
+ * 发送消息
91
+ * @param msg 消息
92
+ * @param name Bucket名称
93
+ * @param isCloseWarn 是否关闭警告
94
+ */
95
+ static sendMessage(msg?: SendMsg, name?: string | undefined, isCloseWarn?: boolean): void;
96
+ /**
97
+ * 绑定消息
98
+ * @param name
99
+ */
100
+ static bindMessage(name: string | undefined): void;
101
+ /**
102
+ * 接收消息
103
+ * @param callback 接收消息的回调函数
104
+ * @param name Bucket名称
105
+ */
106
+ static receiveMessage(callback: (event: MessageEvent<any>) => void, name?: string): void;
107
+ /**
108
+ * 注册消息接收事件
109
+ * @param name
110
+ */
111
+ static registerOnMessage(name?: string): void;
112
+ /**
113
+ * 获取单例实例
114
+ * @description 采用单例方式有利于减少内存占用
115
+ */
116
+ static getInstance(): WebSocketBucket;
117
+ }
118
+ export {};
@@ -0,0 +1,2 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Transform={})}(this,function(e){"use strict";function g(e,t,n,c){console.log("".concat("\n"," %c ").concat(e," %c ").concat(t," ").concat("\n"),"color: ".concat(n,"; background: ").concat(c,"; padding:5px 0;border-radius:3px 0 0 3px;"),"color:#666666;background: #f1f5fa; padding:5px 0;border-radius:0 3px 3px 0;")}function d(){return"".concat((new Date).getHours()<10?"0"+(new Date).getHours():(new Date).getHours(),":").concat((new Date).getMinutes()<10?"0"+(new Date).getMinutes():(new Date).getMinutes(),":").concat((new Date).getSeconds()<10?"0"+(new Date).getSeconds():(new Date).getSeconds())}var r=function(e,t){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,t)};var t,o=function(c){var e=o,t=c;if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}function o(e,t){var n=c.call(this,t)||this;return n.name="Client.io Error",n.message="Error message",n.name=e||n.name,n.message=t||n.message,n.stack=(new Error).stack,n}return r(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n),o}(Error),n=((n=t=t||{}).CONNECTING="CONNECTING",n.OPEN="OPEN",n.CLOSING="CLOSING",n.CLOSED="CLOSED",n.FAIL="FAIL",k.create=function(e){var c,o,t,n=e.url,r=e.name,a=e.heartbeat,s=e.heartRate,s=void 0===s?3e3:s,i=e.restartTime,i=void 0===i?5e3:i,u=e.restartTimes,u=void 0===u?0:u,f=e.restartedTimes,l=void 0===f?0:f,f=e.receive,e=e.send;if(/(ws|wss):\/\/\s*/.test(n))return c=r||k.getBucketName(r),t=new WebSocket(n),o=-1,t.onopen=function(e){g("".concat(c," ▶ SUCCESS"),"◔ ".concat(d()),"#ffffff","#1bc800"),k.setBucketKeyValue("restartedTimes",0,c),k.bindMessage(r)},t.onerror=function(e){g("".concat(c," ▶ ERROR"),"◔ ".concat(d()," ▶ ").concat(c),"#ffffff","#c80000")},t.onclose=function(e){g("".concat(c," ▶ CLOSE"),"◔ ".concat(d()," ▶ ").concat(c),"#ffffff","#000000"),clearInterval(o);var t=k.getBucket(c),n=(t.restartedTimes!==l?l=t.restartedTimes+1:l+=1,Math.pow(2,l-1)*t.restartTime);g("".concat(c," ▶ REBOOT WAITING"),"◔ ".concat(d()," ▶ ").concat(c," RESTART IN ").concat(Math.round(n/1e3)," SECONDS"),"#ffffff","#00c8b4"),setTimeout(function(){t.restartedTimes=l,k.create(t)},n)},"function"==typeof a&&(o=setInterval(function(){a(function(e){k.sendMessage(e,c)})},s)),t={name:c,client:t,url:n,heartbeat:a,heartRate:s,heartRateTimer:o,restartTime:i,restartTimes:u,restartedTimes:l,receive:f,send:e,receiveMessageCallbacks:new Map},k.getInstance().buckets.set(c,t),k.getBucketClient(c);throw new Error("传入的url必须是ws或wss地址")},k.getBucket=function(e){e=k.getBucketName(e);if(!k.getInstance().buckets.has(e))throw new o("名称为".concat(e,"是WebSocket实例不存在"),k.NO_BUCKET);var t=k.getInstance().buckets.get(e);if(t&&t.client instanceof WebSocket)return t;throw new o("名称为".concat(e,"是WebSocket实例不存在"),k.NO_BUCKET_CLIENT)},k.setBucketKeyValue=function(e,t,n){var c=k.getBucket(n);if(!c||"object"!=typeof c||!Reflect.has(c,e))throw new o("名称为".concat(k.getBucketName(n),"的WebSocket Bucket不存在").concat(e,"属性"),k.NO_BUCKET_KEY);c[e]=t,k.getInstance().buckets.set(n,c)},k.getBucketClient=function(e){try{return k.getBucket(e).client}catch(e){console.log("Exception",e)}},k.getBucketName=function(e){return e||k.getInstance().bucketName},k.getBucketClientState=function(e){try{switch(k.getBucketClient(e).readyState){case WebSocket.CONNECTING:return t.CONNECTING;case WebSocket.OPEN:return t.OPEN;case WebSocket.CLOSING:return t.CLOSING;case WebSocket.CLOSED:return t.CLOSED;default:return t.FAIL}}catch(e){return t.FAIL}},k.wsErrorEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onerror=function(e){"function"==typeof t?t(e):console.warn("监听ws报错的回调函数wsError不存在")}}catch(e){console.warn("".concat(e))}},k.wsCloseEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onclose=function(e){"function"==typeof t?t(e):console.warn("监听ws关闭的回调函数wsClose不存在")}}catch(e){console.warn("".concat(e))}},k.wsOpenEventListener=function(t,e){void 0===e&&(e=void 0);try{k.getBucketClient(e).onopen=function(e){"function"==typeof t?t(e):console.warn("wsOpenEventListener缺少回调函数")}}catch(e){console.warn("".concat(e))}},k.sendMessage=function(e,t,n){if(void 0===e&&(e=""),void 0===n&&(n=!1),["CONNECTING","CLOSING","CLOSED"].includes(k.getBucketClientState(t=void 0===t?void 0:t)))n||console.warn("BUCKET:".concat(k.getBucketName(t),"|STATUS:").concat(k.getBucketClientState(t),"|无法进行消息发送"));else try{var c=k.getBucket(t).send;"function"==typeof c&&(e=c(e)),k.getBucketClient(t).send(e)}catch(e){console.warn("".concat(e))}},k.bindMessage=function(e){0<k.getBucket(e).receiveMessageCallbacks.size&&k.registerOnMessage(e)},k.receiveMessage=function(e,t){try{var n;"function"==typeof e?(n="".concat(e),k.getBucket(t).receiveMessageCallbacks.get(n)||k.getBucket(t).receiveMessageCallbacks.set(n,e)):console.warn("receiveMessage缺少回调"),k.registerOnMessage(t)}catch(e){console.warn("".concat(e))}},k.registerOnMessage=function(n){k.getBucketClient(n).onmessage=function(t){var e=k.getBucket(n).receive;"function"==typeof e&&(t=e(t,function(e){k.sendMessage(e,n)})),k.getBucket(n).receiveMessageCallbacks.forEach(function(e){try{e(t)}catch(e){console.warn("".concat(e))}})}},k.getInstance=function(){var e=k.instance;return e=e&&e instanceof k?e:k.instance=new k},k.NO_BUCKET="10001",k.NO_BUCKET_CLIENT="10002",k.NO_BUCKET_KEY="10003",k.DEFAULT_NAME="DEFAULT_BUCKET",k);function k(){this.bucketName=k.DEFAULT_NAME,this.buckets=new Map,this.bucketName=k.DEFAULT_NAME}e.WebSocketBucket=n,e.jsonStringify2Parse=function(t){if("string"==typeof t)try{return JSON.parse(t)}catch(e){return JSON.parse(JSON.stringify('{"value":'.concat(t)))}return{}},Object.defineProperty(e,"__esModule",{value:!0})});
2
+ //# sourceMappingURL=client.io.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.io.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Exception Class
3
+ * throw diy Exception
4
+ * https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error
5
+ * 目前原生的错误类型
6
+ * Error [一般错误类型]
7
+ * SyntaxError [语法错误]
8
+ * ReferenceError [不存在的变量]
9
+ * RangeError [超出有效范围]
10
+ * TypeError [非预期类型]
11
+ * URIError [URI参数错误]
12
+ * EvalError [eval函数没有正确执行]
13
+ * example:: throw new Exception() catch(error) error.message,error.name,error.code,error.stack
14
+ * NewException extends Exception diy yourself Exception;
15
+ */
16
+ export declare class Exception extends Error {
17
+ name: string;
18
+ message: string;
19
+ /**
20
+ * Error constructor
21
+ * @param {String} name 自定义错误名称
22
+ * @param {String|Number} message 自定义错误提示
23
+ */
24
+ constructor(name?: string, message?: string);
25
+ }
@@ -0,0 +1,2 @@
1
+ export { WebSocketBucket } from './websocket';
2
+ export { jsonStringify2Parse } from './util';
@@ -0,0 +1,33 @@
1
+ export declare type WebSocketUrl = `ws://${string}` | `wss://${string}`;
2
+ export declare type Heartbeat = (callback: HeartbeatCallback) => void;
3
+ export declare type HeartbeatCallback = (msg: string) => void;
4
+ export declare type ReceiveInterceptor = (event: MessageEvent<any>, send: (msg: SendMsg) => void) => any;
5
+ export declare type SendInterceptor = (event: any) => any;
6
+ export declare type WebSocketBucketCreate = {
7
+ url: WebSocketUrl;
8
+ name?: string;
9
+ heartbeat?: Heartbeat;
10
+ heartRate?: Millisecond;
11
+ restartTime?: Millisecond;
12
+ restartTimes?: number;
13
+ restartedTimes?: number;
14
+ receive?: ReceiveInterceptor;
15
+ send?: SendInterceptor;
16
+ };
17
+ export declare type WebSocketBucketOptions = {
18
+ name: string;
19
+ client: WebSocket;
20
+ url: WebSocketUrl;
21
+ heartbeat?: Heartbeat;
22
+ heartRate: Millisecond;
23
+ heartRateTimer: number;
24
+ restartTime: Millisecond;
25
+ restartTimes: number;
26
+ restartedTimes: number;
27
+ receive?: ReceiveInterceptor;
28
+ send?: SendInterceptor;
29
+ receiveMessageCallbacks: Map<string, (event: MessageEvent<any>) => void>;
30
+ [key: string]: unknown;
31
+ };
32
+ export declare type Millisecond = number;
33
+ export declare type SendMsg = string | ArrayBufferLike | Blob | ArrayBufferView;
@@ -0,0 +1,36 @@
1
+ export declare function isArray(obj: any): obj is any[];
2
+ export declare function isNull(obj: any): obj is null;
3
+ export declare function isBoolean(obj: unknown): obj is boolean;
4
+ export declare function isObject(obj: any): obj is Record<string, unknown>;
5
+ export declare const isPromise: <T>(obj: unknown) => obj is Promise<T>;
6
+ export declare function isString(obj: any): obj is string;
7
+ export declare function isNumber(obj: any): obj is number;
8
+ export declare function isRegExp(obj: any): boolean;
9
+ export declare function isDate(obj: any): boolean;
10
+ export declare function isColor(color: any): boolean;
11
+ export declare function isUndefined(obj: any): obj is undefined;
12
+ export declare function isFunction(obj: any): obj is (...args: any[]) => any;
13
+ export declare function isClass(value: unknown): boolean;
14
+ export declare function isEmptyObject(obj: any): boolean;
15
+ export declare function isEmpty(obj: any): boolean;
16
+ export declare function isExist(obj: any): boolean;
17
+ export declare function isWindow(el: any): el is Window;
18
+ /**
19
+ * 控制台消息打印
20
+ * @param name
21
+ * @param message
22
+ * @param color
23
+ * @param bgColor
24
+ */
25
+ export declare function consoleLog(name: string, message: string, color: string, bgColor: string): void;
26
+ /**
27
+ * 当前时间
28
+ * @description 用于控制台打印使用
29
+ */
30
+ export declare function now(): string;
31
+ /**
32
+ * jsonStringify2Parse
33
+ * @param value
34
+ * @description 将JSON字符串转换为JSON对象
35
+ */
36
+ export declare function jsonStringify2Parse(value: unknown): any;
@@ -0,0 +1,118 @@
1
+ import { SendMsg, WebSocketBucketCreate, WebSocketBucketOptions } from './types';
2
+ declare enum WebSocketBucketState {
3
+ CONNECTING = "CONNECTING",
4
+ OPEN = "OPEN",
5
+ CLOSING = "CLOSING",
6
+ CLOSED = "CLOSED",
7
+ FAIL = "FAIL"
8
+ }
9
+ /**
10
+ * @class WebSocketBucket
11
+ * @public
12
+ * @classdesc WebSocket快速部署开发,可同开多个WebSocket,并分别命名,可对多个Client进行监听,每一个Bucket为Client运行所必需的空间环境。
13
+ * @example
14
+ * WebSocketBucket.create({url:'wss://ws.demo.com/socket-io'})
15
+ * WebSocketBucket.sendMessage('Hello World')
16
+ */
17
+ export declare class WebSocketBucket {
18
+ static NO_BUCKET: string;
19
+ static NO_BUCKET_CLIENT: string;
20
+ static NO_BUCKET_KEY: string;
21
+ static DEFAULT_NAME: string;
22
+ client: WebSocket | undefined;
23
+ buckets: Map<string, WebSocketBucketOptions>;
24
+ bucketName: string;
25
+ static instance: WebSocketBucket;
26
+ constructor();
27
+ /**
28
+ * create
29
+ * 创建一个Bucket空间
30
+ * @param url {string} 服务地址(SSL)
31
+ * @param name {string} 实例名称
32
+ * @param heartbeat {function} (sendMessage,instanceName)=>void 心跳执行函数 send {Function} 消息发送函数
33
+ * @param heartRate 心跳频率 毫秒
34
+ * @param restartTime 重启时间,按照通用方式,例如第一次3秒后重连如果没连上第二次就3*2=6秒后重连,如果还没有连上第三次就是3*2*2=12秒后重连,以此类推直到重连上为止,一旦重连上重连等待时间就会自动回到3秒这个初始值
35
+ * @param restartTimes 重启次数,0为不限制,>0为最大重启次数
36
+ * @param restartedTimes 已重启次数
37
+ * @param receive 接收拦截器
38
+ * @param send 发送拦截器
39
+ */
40
+ static create({ url, name, heartbeat, heartRate, restartTime, restartTimes, restartedTimes, receive, send, }: WebSocketBucketCreate): WebSocket | undefined;
41
+ /**
42
+ * readBucket
43
+ * 读取Bucket空间
44
+ * @param name
45
+ * @return WebSocketBucketOptions
46
+ */
47
+ static getBucket(name: string | undefined): WebSocketBucketOptions;
48
+ /**
49
+ * setBucketKeyValue
50
+ * 设置Bucket属性值
51
+ * @param key
52
+ * @param value
53
+ * @param name
54
+ */
55
+ static setBucketKeyValue(key: string, value: number, name: string): void;
56
+ /**
57
+ * 获取Bucket客户端
58
+ * @param name
59
+ */
60
+ static getBucketClient(name: string | undefined): WebSocket | undefined;
61
+ /**
62
+ * 获取Bucket空间名称
63
+ * @param name
64
+ */
65
+ static getBucketName(name: string | undefined): string;
66
+ /**
67
+ * 获取Bucket客户端状态
68
+ * @param name
69
+ */
70
+ static getBucketClientState(name: string | undefined): WebSocketBucketState;
71
+ /**
72
+ * 监听WebSocket报错
73
+ * @param callback
74
+ * @param name
75
+ */
76
+ static wsErrorEventListener(callback: (event: Event) => void, name?: undefined): void;
77
+ /**
78
+ * 监听WebSocket关闭
79
+ * @param callback
80
+ * @param name
81
+ */
82
+ static wsCloseEventListener(callback: (event: CloseEvent) => void, name?: undefined): void;
83
+ /**
84
+ * 监听WebSocket打开
85
+ * @param callback
86
+ * @param name
87
+ */
88
+ static wsOpenEventListener(callback: (event: Event) => void, name?: undefined): void;
89
+ /**
90
+ * 发送消息
91
+ * @param msg 消息
92
+ * @param name Bucket名称
93
+ * @param isCloseWarn 是否关闭警告
94
+ */
95
+ static sendMessage(msg?: SendMsg, name?: string | undefined, isCloseWarn?: boolean): void;
96
+ /**
97
+ * 绑定消息
98
+ * @param name
99
+ */
100
+ static bindMessage(name: string | undefined): void;
101
+ /**
102
+ * 接收消息
103
+ * @param callback 接收消息的回调函数
104
+ * @param name Bucket名称
105
+ */
106
+ static receiveMessage(callback: (event: MessageEvent<any>) => void, name?: string): void;
107
+ /**
108
+ * 注册消息接收事件
109
+ * @param name
110
+ */
111
+ static registerOnMessage(name?: string): void;
112
+ /**
113
+ * 获取单例实例
114
+ * @description 采用单例方式有利于减少内存占用
115
+ */
116
+ static getInstance(): WebSocketBucket;
117
+ }
118
+ export {};
package/index.d.ts ADDED
@@ -0,0 +1,159 @@
1
+ declare type WebSocketUrl = `ws://${string}` | `wss://${string}`;
2
+ declare type Heartbeat = (callback: HeartbeatCallback) => void;
3
+ declare type HeartbeatCallback = (msg: string) => void;
4
+ declare type ReceiveInterceptor = (event: MessageEvent<any>, send: (msg: SendMsg) => void) => any;
5
+ declare type SendInterceptor = (event: any) => any;
6
+ declare type WebSocketBucketCreate = {
7
+ url: WebSocketUrl;
8
+ name?: string;
9
+ heartbeat?: Heartbeat;
10
+ heartRate?: Millisecond;
11
+ restartTime?: Millisecond;
12
+ restartTimes?: number;
13
+ restartedTimes?: number;
14
+ receive?: ReceiveInterceptor;
15
+ send?: SendInterceptor;
16
+ };
17
+ declare type WebSocketBucketOptions = {
18
+ name: string;
19
+ client: WebSocket;
20
+ url: WebSocketUrl;
21
+ heartbeat?: Heartbeat;
22
+ heartRate: Millisecond;
23
+ heartRateTimer: number;
24
+ restartTime: Millisecond;
25
+ restartTimes: number;
26
+ restartedTimes: number;
27
+ receive?: ReceiveInterceptor;
28
+ send?: SendInterceptor;
29
+ receiveMessageCallbacks: Map<string, (event: MessageEvent<any>) => void>;
30
+ [key: string]: unknown;
31
+ };
32
+ declare type Millisecond = number;
33
+ declare type SendMsg = string | ArrayBufferLike | Blob | ArrayBufferView;
34
+
35
+ declare enum WebSocketBucketState {
36
+ CONNECTING = "CONNECTING",
37
+ OPEN = "OPEN",
38
+ CLOSING = "CLOSING",
39
+ CLOSED = "CLOSED",
40
+ FAIL = "FAIL"
41
+ }
42
+ /**
43
+ * @class WebSocketBucket
44
+ * @public
45
+ * @classdesc WebSocket快速部署开发,可同开多个WebSocket,并分别命名,可对多个Client进行监听,每一个Bucket为Client运行所必需的空间环境。
46
+ * @example
47
+ * WebSocketBucket.create({url:'wss://ws.demo.com/socket-io'})
48
+ * WebSocketBucket.sendMessage('Hello World')
49
+ */
50
+ declare class WebSocketBucket {
51
+ static NO_BUCKET: string;
52
+ static NO_BUCKET_CLIENT: string;
53
+ static NO_BUCKET_KEY: string;
54
+ static DEFAULT_NAME: string;
55
+ client: WebSocket | undefined;
56
+ buckets: Map<string, WebSocketBucketOptions>;
57
+ bucketName: string;
58
+ static instance: WebSocketBucket;
59
+ constructor();
60
+ /**
61
+ * create
62
+ * 创建一个Bucket空间
63
+ * @param url {string} 服务地址(SSL)
64
+ * @param name {string} 实例名称
65
+ * @param heartbeat {function} (sendMessage,instanceName)=>void 心跳执行函数 send {Function} 消息发送函数
66
+ * @param heartRate 心跳频率 毫秒
67
+ * @param restartTime 重启时间,按照通用方式,例如第一次3秒后重连如果没连上第二次就3*2=6秒后重连,如果还没有连上第三次就是3*2*2=12秒后重连,以此类推直到重连上为止,一旦重连上重连等待时间就会自动回到3秒这个初始值
68
+ * @param restartTimes 重启次数,0为不限制,>0为最大重启次数
69
+ * @param restartedTimes 已重启次数
70
+ * @param receive 接收拦截器
71
+ * @param send 发送拦截器
72
+ */
73
+ static create({ url, name, heartbeat, heartRate, restartTime, restartTimes, restartedTimes, receive, send, }: WebSocketBucketCreate): WebSocket | undefined;
74
+ /**
75
+ * readBucket
76
+ * 读取Bucket空间
77
+ * @param name
78
+ * @return WebSocketBucketOptions
79
+ */
80
+ static getBucket(name: string | undefined): WebSocketBucketOptions;
81
+ /**
82
+ * setBucketKeyValue
83
+ * 设置Bucket属性值
84
+ * @param key
85
+ * @param value
86
+ * @param name
87
+ */
88
+ static setBucketKeyValue(key: string, value: number, name: string): void;
89
+ /**
90
+ * 获取Bucket客户端
91
+ * @param name
92
+ */
93
+ static getBucketClient(name: string | undefined): WebSocket | undefined;
94
+ /**
95
+ * 获取Bucket空间名称
96
+ * @param name
97
+ */
98
+ static getBucketName(name: string | undefined): string;
99
+ /**
100
+ * 获取Bucket客户端状态
101
+ * @param name
102
+ */
103
+ static getBucketClientState(name: string | undefined): WebSocketBucketState;
104
+ /**
105
+ * 监听WebSocket报错
106
+ * @param callback
107
+ * @param name
108
+ */
109
+ static wsErrorEventListener(callback: (event: Event) => void, name?: undefined): void;
110
+ /**
111
+ * 监听WebSocket关闭
112
+ * @param callback
113
+ * @param name
114
+ */
115
+ static wsCloseEventListener(callback: (event: CloseEvent) => void, name?: undefined): void;
116
+ /**
117
+ * 监听WebSocket打开
118
+ * @param callback
119
+ * @param name
120
+ */
121
+ static wsOpenEventListener(callback: (event: Event) => void, name?: undefined): void;
122
+ /**
123
+ * 发送消息
124
+ * @param msg 消息
125
+ * @param name Bucket名称
126
+ * @param isCloseWarn 是否关闭警告
127
+ */
128
+ static sendMessage(msg?: SendMsg, name?: string | undefined, isCloseWarn?: boolean): void;
129
+ /**
130
+ * 绑定消息
131
+ * @param name
132
+ */
133
+ static bindMessage(name: string | undefined): void;
134
+ /**
135
+ * 接收消息
136
+ * @param callback 接收消息的回调函数
137
+ * @param name Bucket名称
138
+ */
139
+ static receiveMessage(callback: (event: MessageEvent<any>) => void, name?: string): void;
140
+ /**
141
+ * 注册消息接收事件
142
+ * @param name
143
+ */
144
+ static registerOnMessage(name?: string): void;
145
+ /**
146
+ * 获取单例实例
147
+ * @description 采用单例方式有利于减少内存占用
148
+ */
149
+ static getInstance(): WebSocketBucket;
150
+ }
151
+
152
+ /**
153
+ * jsonStringify2Parse
154
+ * @param value
155
+ * @description 将JSON字符串转换为JSON对象
156
+ */
157
+ declare function jsonStringify2Parse(value: unknown): any;
158
+
159
+ export { WebSocketBucket, jsonStringify2Parse };
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "x-next",
3
+ "version": "0.0.0-alpha.1",
4
+ "description": "X-Component.",
5
+ "main": "framework/umd/client.io.js",
6
+ "module": "framework/es/client.io.js",
7
+ "typings": "framework/es/index.d.ts",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/ztes/client.io.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/ztes/client.io/issues"
14
+ },
15
+ "author": "ztes.com <xy@ztes.com>",
16
+ "blog": "https://ztes.com",
17
+ "keywords": [
18
+ "realtime",
19
+ "websocket",
20
+ "io",
21
+ "sse"
22
+ ],
23
+ "license": "MIT",
24
+ "scripts": {
25
+ "build:pkg": "rollup --config rollup.config.js",
26
+ "create": "tsc",
27
+ "dev": "set NODE_ENV=developemnt&& rollup -c rollup.config.js -w",
28
+ "build": "rollup -c rollup.config.js",
29
+ "eslint:fix": "./node_modules/.bin/eslint --fix ./",
30
+ "publish": "npm publish --access=public"
31
+ },
32
+ "devDependencies": {
33
+ "@babel/core": "^7.18.10",
34
+ "@babel/preset-env": "^7.18.10",
35
+ "@rollup/plugin-babel": "^6.0.4",
36
+ "@rollup/plugin-json": "^6.0.0",
37
+ "@rollup/plugin-typescript": "^11.1.6",
38
+ "@types/node": "^18.7.6",
39
+ "@types/qs": "^6.9.7",
40
+ "@types/webpack-env": "^1.17.0",
41
+ "@typescript-eslint/eslint-plugin": "^5.59.2",
42
+ "@typescript-eslint/parser": "^5.0.0",
43
+ "core-js": "3",
44
+ "eslint": "^8.17.0",
45
+ "eslint-config-prettier": "^8.5.0",
46
+ "eslint-define-config": "^1.5.0",
47
+ "eslint-plugin-prettier": "^4.0.0",
48
+ "prettier": "^2.8.8",
49
+ "rollup": "^2.79.1",
50
+ "rollup-plugin-commonjs": "^10.1.0",
51
+ "rollup-plugin-dts": "^4.2.2",
52
+ "rollup-plugin-eslint": "^7.0.0",
53
+ "rollup-plugin-node-resolve": "^5.2.0",
54
+ "rollup-plugin-typescript": "^1.0.1",
55
+ "rollup-plugin-typescript2": "^0.31.1",
56
+ "rollup-plugin-uglify": "^6.0.4",
57
+ "tslib": "^2.6.3",
58
+ "typescript": "^4.4.4"
59
+ },
60
+ "files": [
61
+ "/framework",
62
+ "README.md",
63
+ "index.d.ts"
64
+ ]
65
+ }