hj-ddp.es.js 12.0 KB
Newer Older
yu's avatar
yu 已提交
1 2 3 4
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
yu's avatar
yu 已提交
5 6 7 8 9 10
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
	enumerable: true,
	configurable: true,
	writable: true,
	value
}) : obj[key] = value;
yu's avatar
yu 已提交
11
var __spreadValues = (a, b) => {
yu's avatar
yu 已提交
12 13 14 15 16 17 18 19 20
	for (var prop in b || (b = {}))
		if (__hasOwnProp.call(b, prop))
			__defNormalProp(a, prop, b[prop]);
	if (__getOwnPropSymbols)
		for (var prop of __getOwnPropSymbols(b)) {
			if (__propIsEnum.call(b, prop))
				__defNormalProp(a, prop, b[prop]);
		}
	return a;
yu's avatar
yu 已提交
21
};
yu's avatar
yu 已提交
22 23 24 25 26 27
import {
	EventEmitter,
	UniSocket,
	EJSON
} from "../../hj-core/js_sdk";

yu's avatar
yu 已提交
28
function deepCopy(d) {
yu's avatar
yu 已提交
29
	return JSON.parse(JSON.stringify(d));
yu's avatar
yu 已提交
30 31
}
const uuid = {
yu's avatar
yu 已提交
32 33 34 35
	id: 1,
	next() {
		return (this.id++).toString();
	}
yu's avatar
yu 已提交
36 37
};
const DDPConnectionState = {
yu's avatar
yu 已提交
38 39 40 41 42 43 44
	CLOSED: 0,
	CONNECTING: 1,
	CONNECTED: 2,
	READY: 3,
	FAIL: 4,
	CLOSING: 5,
	RECONNECTING: 6
yu's avatar
yu 已提交
45 46
};
const DDPConnectionEvent = {
yu's avatar
yu 已提交
47
	STATE_CHANGE: "state-change"
yu's avatar
yu 已提交
48 49 50
};
const supportedDdpVersions = ["1", "pre2", "pre1"];
class DDPConnection extends EventEmitter {
yu's avatar
yu 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	constructor(opts) {
		super();
		this.supportedDdpVersions = supportedDdpVersions;
		this.state = DDPConnectionState.CLOSED;
		this.messages = [];
		this.checkTick = null;
		this.tlsOpts = (opts == null ? void 0 : opts.tlsOpts) || {};
		this.autoReconnect = "autoReconnect" in opts ? !!(opts == null ? void 0 : opts.autoReconnect) : true;
		this.autoReconnectTimer = (opts == null ? void 0 : opts.autoReconnectTimer) || 1e4;
		this.url = opts == null ? void 0 : opts.url;
		this.socketConstructor = opts.socketConstructor || UniSocket;
		this.ddpVersion = (opts == null ? void 0 : opts.ddpVersion) || "1";
		this._callbacks = {};
		this._updatedCallbacks = {};
		this._pendingMethods = {};
		this.on("connected", () => {
			this._clearReconnectTimeout();
			this.changeState(DDPConnectionState.READY);
			this.checkMessage();
		});
		this.on("failed", (error) => {
			this.changeState(DDPConnectionState.FAIL, error);
		});
		if ("autoConnect" in opts ? opts.autoConnect : true) {
			this.connect();
		}
	}
	get isSocketBusy() {
		return this.state === DDPConnectionState.CLOSING || this.state === DDPConnectionState.CONNECTING || this
			.state === DDPConnectionState.RECONNECTING;
	}
	changeState(state, data) {
		this.state = state;
		this.emit(DDPConnectionEvent.STATE_CHANGE, {
			state,
			data
		});
	}
	connect(url, protos, data) {
		if (this.state !== DDPConnectionState.CLOSED && this.state !== DDPConnectionState.RECONNECTING) {
			return;
		}
		this.changeState(DDPConnectionState.CONNECTING);
		this.url = this.parseUrl(url || this.url);
		this.socket = new this.socketConstructor(this.url + "/websocket", protos, data);
		this._prepareHandlers();
	}
	parseUrl(url = "") {
		if (url.endsWith("/"))
			url = url.slice(0, -1);
		if (url.endsWith("/websocket"))
			url = url.slice(0, -10);
		return url;
	}
	_prepareHandlers() {
		const socket = this.socket;
		socket.onopen = () => {
			this.changeState(DDPConnectionState.CONNECTED);
			this.send({
				msg: "connect",
				version: this.ddpVersion,
				support: this.supportedDdpVersions
			}, true);
		};
		socket.onerror = (error) => {
			if (this.state === DDPConnectionState.CONNECTING) {
				this.emit("failed", error.message);
				this.changeState(DDPConnectionState.FAIL);
			}
			this.emit("socket-error", error);
		};
		socket.onclose = (ev) => {
			this.changeState(DDPConnectionState.CLOSED, ev);
			if (this.state === DDPConnectionState.CONNECTED) {
				this.emit("socket-close", ev == null ? void 0 : ev.code, ev == null ? void 0 : ev.reason);
				this._endPendingMethodCalls();
			}
			this.reconnect();
		};
		socket.onmessage = (event) => {
			this.ddpMessageHandler(event.data);
			this.emit("message", event.data);
		};
	}
	close() {
		this.changeState(DDPConnectionState.CLOSING);
		this.socket.close();
	}
	call(name, params, callback, updatedCallback, options = {}) {
		var id = this._getNextId();
		let timer;
		if (options.timeout) timer = setTimeout(() => {
			this.revokeCallBack(id, 'TIMEOUT')
		}, options.timeout);
		if (typeof callback === "function") {
			this._pendingMethods[id] = true;
			this._callbacks[id] = (...args) => {
				delete this._callbacks[id]
				delete this._pendingMethods[id];
				if (callback) {
					callback.apply(this, args);
				}
				timer && clearTimeout(timer)
			};
		}
		if (typeof updatedCallback === "function") {
			this._pendingMethods[id] = true;
			const callback = this._updatedCallbacks[id]
			this._updatedCallbacks[id] = (...args) => {
				delete this._pendingMethods[id];
				delete this._updatedCallbacks[id]
				if (callback) {
					callback.apply(this, args);
				}
				timer && clearTimeout(timer)
			};
		}
		this.send({
			msg: "method",
			id,
			method: name,
			params
		});
	}
	callWithRandomSeed(method, params, randomSeed, callback, updatedCallback) {
		var id = this._getNextId();
		if (callback) {
			this._callbacks[id] = callback;
		}
		if (updatedCallback) {
			this._updatedCallbacks[id] = updatedCallback;
		}
		this.send({
			msg: "method",
			id,
			method,
			randomSeed,
			params
		});
	}
	subscribe(name, params, callback) {
		const id = uuid.next();
		const data = {
			msg: "sub",
			id,
			name,
			params
		};
		if (typeof callback === "function")
			this._callbacks[id] = (err) => {
				callback(err, !err ? {
					id,
					name,
					params,
					stop: () => this.unsubscribe(id)
				} : undefined);
			};
		this.send(data);
		return id;
	}
	unsubscribe(id) {
		this.send({
			msg: "unsub",
			id
		});
	}
	_clearReconnectTimeout() {
		if (this.reconnectTimeout) {
			clearTimeout(this.reconnectTimeout);
			this.reconnectTimeout = null;
		}
	}
	reconnect() {
		if (!this.autoReconnect || this.isSocketBusy)
			return;
		this._clearReconnectTimeout();
		this.reconnectTimeout = setTimeout(() => {
			this.connect();
		}, this.autoReconnectTimer);
		this.changeState(DDPConnectionState.RECONNECTING);
	}
	send(data, force = false) {
		if (force) {
			if (this.state === DDPConnectionState.CONNECTED)
				this.socket.send(EJSON.stringify(data));
			else
				this.messages.unshift(data);
			return;
		}
		if (data.id) {
			const oldIndex = this.messages.findIndex((el) => {
				return el.method && el.method === data.method && JSON.stringify(el.params) === JSON
					.stringify(data.params);
			});
			if (oldIndex > -1) {
				const oo = this.messages.splice(oldIndex, 1)[0];
yu's avatar
yu 已提交
247
				this.revokeCallBack(oo.id, "忽略了相同参数的相同方法调用");
yu's avatar
yu 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
			}
		}
		this.messages.push(data);
		this.checkMessage();
	}
	checkMessage() {
		if (this.state !== DDPConnectionState.READY || this.messages.length === 0)
			return;
		clearTimeout(this.checkTick);
		this.socket.send(JSON.stringify(this.messages.shift()));
		this.checkTick = setTimeout(() => {
			this.checkMessage();
		}, 0);
	}
	ddpMessageHandler(data) {
		data = EJSON.parse(data);
		const type = data == null ? void 0 : data.msg;
		this.emit('ddp-message', data)
		switch (type) {
			case "failed": {
				if (this.supportedDdpVersions.indexOf(data.version) !== -1) {
					this.ddpVersion = data.version;
					this.connect();
				} else {
					this.autoReconnect = false;
					this.emit("failed", "Cannot negotiate DDP version");
				}
				break;
			}
			case "connected": {
				this.session = data.session;
				this.emit("connected");
				break;
			}
			case "result": {
				this.revokeCallBack(data.id, data.error, data.result);
				break;
			}
			case "updated": {
				Array.from(data.methods).forEach((method) => {
					var cb = this._updatedCallbacks[method];
					if (cb) {
						cb();
						delete this._updatedCallbacks[method];
					}
				});
				break;
			}
			case "nosub": {
				this.revokeCallBack(data.id, data.error);
				break;
			}
			case "ready": {
				Array.from(data.subs).forEach((id) => {
					this.revokeCallBack(id);
				});
				break;
			}
			case "ping": {
				this.send(Object.prototype.hasOwnProperty.call(data, "id") ? {
					msg: "pong",
					id: data.id
				} : {
					msg: "pong"
				});
			}
		}
	}
	_getNextId() {
		return uuid.next();
	}
	_endPendingMethodCalls() {
		var ids = Object.keys(this._pendingMethods);
		this._pendingMethods = {};
		ids.forEach((id) => {
			if (this._callbacks[id]) {
				this._callbacks[id]('DISCONNECTED');
				delete this._callbacks[id];
			}
			if (this._updatedCallbacks[id]) {
				this._updatedCallbacks[id]();
				delete this._updatedCallbacks[id];
			}
		});
	}
	revokeCallBack(id, ...args) {
		const cb = this._callbacks[id];
		typeof cb === "function" && cb(...args);
		delete this._callbacks[id];
	}
yu's avatar
yu 已提交
338 339
}
var IDDPConnectionState;
yu's avatar
yu 已提交
340
(function(IDDPConnectionState2) {
yu's avatar
yu 已提交
341 342 343 344 345 346 347
	IDDPConnectionState2[IDDPConnectionState2["CLOSED"] = 0] = "CLOSED";
	IDDPConnectionState2[IDDPConnectionState2["CONNECTING"] = 1] = "CONNECTING";
	IDDPConnectionState2[IDDPConnectionState2["CONNECTED"] = 2] = "CONNECTED";
	IDDPConnectionState2[IDDPConnectionState2["READY"] = 3] = "READY";
	IDDPConnectionState2[IDDPConnectionState2["FAIL"] = 4] = "FAIL";
	IDDPConnectionState2[IDDPConnectionState2["CLOSING"] = 5] = "CLOSING";
	IDDPConnectionState2[IDDPConnectionState2["RECONNECTING"] = 6] = "RECONNECTING";
yu's avatar
yu 已提交
348
})(IDDPConnectionState || (IDDPConnectionState = {}));
yu's avatar
yu 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
class Client {
	constructor({
		url = "ws://localhost:3000/websocket"
	}) {
		this.plugins = {};
		if (Client.clients.has(url))
			return Client.clients.get(url);
		Client.clients.set(url, this);
		this.connection = new DDPConnection({
			url
		});
		this.on = this.connection.on.bind(this.connection)
		this.isReady = () => new Promise(resolve => {
			if (this.connection.state === DDPConnectionState.CONNECTED) {
				return resolve()
			}
yu's avatar
yu 已提交
365 366 367
			const cb = ({
				state
			}) => {
yu's avatar
yu 已提交
368 369 370 371 372 373 374 375 376 377 378
				if (state === DDPConnectionState.CONNECTED) {
					this.connection.off(DDPConnectionEvent.STATE_CHANGE, cb)
					resolve()
				}
			}
			this.connection.on(DDPConnectionEvent.STATE_CHANGE, cb)
		})
		this.isClose = () => new Promise(resolve => {
			if (this.connection.state !== DDPConnectionState.CONNECTED) {
				return resolve()
			}
yu's avatar
yu 已提交
379 380 381
			const cb = ({
				state
			}) => {
yu's avatar
yu 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
				if (state !== DDPConnectionState.CONNECTED) {
					this.connection.off(DDPConnectionEvent.STATE_CHANGE, cb)
					resolve()
				}
			}
			this.connection.on(DDPConnectionEvent.STATE_CHANGE, cb)
		})
		const onReadys = new Set()
		const onCloses = new Set()
		this.onReady = cb => {
			if (typeof cb !== "function") return console.warn(`must be function onReady`)
			if (this.connection.state === DDPConnectionState.CONNECTED) cb()
			onReadys.add(cb)
			return () => onReadys.delete(cb)
		}
		this.onClose = cb => {
			if (typeof cb !== "function") return console.warn(`must be function onClose`)
			if (this.connection.state !== DDPConnectionState.CONNECTED) cb()
			onCloses.add(cb)
			return () => onCloses.delete(cb)
		}
		let connected = false;
yu's avatar
yu 已提交
404 405 406
		this.connection.on(DDPConnectionEvent.STATE_CHANGE, ({
			state
		}) => {
yu's avatar
yu 已提交
407 408 409 410 411 412 413 414 415 416 417
			const newState = state === DDPConnectionState.CONNECTED;
			if (newState === connected) return;
			connected = newState;
			(connected ? onReadys : onCloses).forEach(el => el());
		})
	}
	call(name, ...args) {
		const callArgs = args.filter((el) => typeof el !== "function");
		const callback = args.filter((el) => typeof el === "function");
		return this.connection.call(name, callArgs, callback[0], callback[1]);
	}
yu's avatar
yu 已提交
418 419 420 421 422
	callAsync(name, ...args) {
		return new Promise((res, rej) => {
			this.connection.call(name, callArgs, (err, data) => err ? rej(err) : res(data));
		})
	}
yu's avatar
yu 已提交
423 424 425 426 427 428 429 430 431 432 433
	subscribe(name, ...args) {
		const callArgs = args.filter((el) => typeof el !== "function");
		const callback = args.filter((el) => typeof el === "function");
		return this.connection.subscribe(name, callArgs, callback[0]);
	}
	unsubscribe(id) {
		this.connection.unsubscribe(id);
	}
	destroy() {
		this.connection.close();
	}
yu's avatar
yu 已提交
434 435 436
};
Client.clients = new Map();
const buildedClients = new Map();
yu's avatar
yu 已提交
437 438 439 440 441 442 443 444 445 446 447 448

function connect(opt) {
	if (!opt)
		opt = "ws://localhost:3000/websocket";
	const userOpt = typeof opt === "string" ? {
		url: opt
	} : opt;
	if (buildedClients.has(userOpt.url))
		return buildedClients.get(userOpt.url);
	return Object.freeze(new Client(__spreadValues({
		socketConstructor: UniSocket
	}, userOpt)));
yu's avatar
yu 已提交
449
}
yu's avatar
yu 已提交
450 451 452 453
export {
	IDDPConnectionState,
	connect
};