basil-ws-flipper
Version:
Websocket Flipper Plugin
79 lines (78 loc) • 3.15 kB
JavaScript
import forEach from 'lodash/forEach';
import filter from 'lodash/filter';
import head from 'lodash/head';
import { addPlugin } from 'react-native-flipper';
let nativeSocket = global.window.WebSocket;
const sockets = [];
const currentSocketIds = [];
global.window.WebSocket = function (...args) {
const socket = new nativeSocket(...args);
const sendProxyHandler = {
apply: (target, thisArg, argumentList) => {
pluginSend('send', { key: socket.url, data: argumentList });
return Reflect.apply(target, thisArg, argumentList);
}
};
const sendProxy = new Proxy(socket.send, sendProxyHandler);
socket.send = sendProxy;
sockets.push(socket);
return socket;
};
setInterval(() => {
forEach(sockets, (socket) => {
if (!currentSocketIds.includes(socket.url)) {
pluginSend('add', { key: socket.url });
currentSocketIds.push(socket.url);
socket.addEventListener('open', (ev) => {
pluginSend("open", { key: socket.url, data: ev });
});
socket.addEventListener('message', (ev) => {
pluginSend("message", { key: socket.url, data: ev });
});
socket.addEventListener('close', (ev) => {
pluginSend("close", { key: socket.url, data: ev });
});
socket.addEventListener('error', (ev) => {
pluginSend("error", { key: socket.url, data: ev });
});
}
pluginSend('status', { key: socket.url, data: socket.readyState });
});
}, 1000, [sockets, pluginSend]);
let currentConnection = null;
function pluginSend(method, data) {
currentConnection === null || currentConnection === void 0 ? void 0 : currentConnection.send(method, data);
}
const createDebugger = () => {
let event = {
type: 'message',
isTrusted: false
};
addPlugin({
getId() {
return 'flipper-plugin-basil-ws';
},
onConnect(connection) {
console.log("basil-ws-flipper [CONNECTED]");
currentConnection = connection;
currentConnection === null || currentConnection === void 0 ? void 0 : currentConnection.receive('send', (state, responder) => {
const { data, socketUrl } = state;
const socket = head(filter(sockets, x => x.url === socketUrl));
socket === null || socket === void 0 ? void 0 : socket.send(data);
});
currentConnection === null || currentConnection === void 0 ? void 0 : currentConnection.receive('mock', (state, responder) => {
const { data, socketUrl } = state;
const socket = head(filter(sockets, x => x.url === socketUrl));
socket === null || socket === void 0 ? void 0 : socket.dispatchEvent({ type: 'message', data });
});
},
onDisconnect() {
console.log("basil-ws-flipper [DISCONNECTED]");
currentConnection = null;
},
runInBackground() {
return true;
}
});
};
const wsDebugPlugin = createDebugger();