From 74ec84117e63c076978543874e03bb1c6c924e30 Mon Sep 17 00:00:00 2001 From: Ethan Weber Date: Thu, 7 Jul 2022 16:00:30 -0700 Subject: [PATCH] cleaning up viewer code (#101) --- .vscode/settings.json | 5 +- docs/tutorials/viewer.md | 9 +- notebooks/visualize_viewer.ipynb | 45 +- pyrad/engine/trainer.py | 4 +- pyrad/graphs/base.py | 2 +- pyrad/viewer/app/package.json | 4 +- pyrad/viewer/app/src/Animator.js | 234 - pyrad/viewer/app/src/Background.js | 19 - .../viewer/app/src/ExtensibleObjectLoader.js | 11 +- pyrad/viewer/app/src/SceneNode.js | 240 +- pyrad/viewer/app/src/Viewer.js | 374 - pyrad/viewer/app/src/Viewer.jsx | 373 + pyrad/viewer/app/src/index.css | 47 +- pyrad/viewer/app/src/serviceWorker.js | 210 +- pyrad/viewer/app/src/setupTests.js | 2 +- pyrad/viewer/app/src/socket.io.js | 7915 ----------------- pyrad/viewer/app/src/utils.js | 2 +- pyrad/viewer/app/src/web_rtc.js | 48 - pyrad/viewer/app/yarn.lock | 19 + pyrad/viewer/server/__init__.py | 25 - pyrad/viewer/server/commands.py | 15 +- pyrad/viewer/server/geometry.py | 4 +- pyrad/viewer/server/server.py | 2 - pyrad/viewer/server/socket.py | 141 - pyrad/viewer/server/transformations.py | 1965 +--- .../server/{vis_utils.py => viewer_utils.py} | 45 +- pyrad/viewer/server/visualizer.py | 56 +- ..._server.py => run_viewer_bridge_server.py} | 0 tests/viewer/test_drawing.py | 325 - .../viewer/{test_comms.py => test_viewer.py} | 50 +- 30 files changed, 829 insertions(+), 11362 deletions(-) delete mode 100644 pyrad/viewer/app/src/Animator.js delete mode 100644 pyrad/viewer/app/src/Background.js delete mode 100644 pyrad/viewer/app/src/Viewer.js create mode 100644 pyrad/viewer/app/src/Viewer.jsx delete mode 100644 pyrad/viewer/app/src/socket.io.js delete mode 100644 pyrad/viewer/app/src/web_rtc.js delete mode 100644 pyrad/viewer/server/socket.py rename pyrad/viewer/server/{vis_utils.py => viewer_utils.py} (92%) rename scripts/{run_viewer_server.py => run_viewer_bridge_server.py} (100%) delete mode 100644 tests/viewer/test_drawing.py rename tests/viewer/{test_comms.py => test_viewer.py} (75%) diff --git a/.vscode/settings.json b/.vscode/settings.json index 3a9b1b0cf..c973d2df0 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,4 @@ { - // "python.pythonPath": "/path/to/bin/python", "files.watcherExclude": { "**/__pycache__/": true, "**/.ipynb_checkpoints": true, @@ -8,6 +7,10 @@ "**/runs*": true, "**/temp*": true, }, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "[python]": { + "editor.defaultFormatter": "ms-python.python" + }, "editor.formatOnSave": true, "python.envFile": "${workspaceFolder}/.env", "python.formatting.provider": "black", diff --git a/docs/tutorials/viewer.md b/docs/tutorials/viewer.md index d3e60771f..ca199cbee 100644 --- a/docs/tutorials/viewer.md +++ b/docs/tutorials/viewer.md @@ -9,8 +9,11 @@ The viewer is built using [ThreeJS](https://threejs.org/) and packaged into a [R ## Quick start ``` -# run training script with the viewer +# Run bridge server in the background. +python scripts/run_viewer_bridge_server.py +# Run training script with viewer enabled. +python scripts/run_train.py viewer.enable=True ```
@@ -63,8 +66,8 @@ yarn start # forward port and open in your local browser # the URL takes the following form -# http://localhost:/localhost: -http://localhost:4000/localhost:8051 +# http://localhost:?localhost: +http://localhost:4000?localhost:8051 ``` Possibly edit the port in `app/.env.development` file with the following: diff --git a/notebooks/visualize_viewer.ipynb b/notebooks/visualize_viewer.ipynb index 5cfaa6ddd..2f20ab375 100644 --- a/notebooks/visualize_viewer.ipynb +++ b/notebooks/visualize_viewer.ipynb @@ -10,7 +10,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": null, "id": "8501e01d-f932-4a75-8259-2def67a546d7", "metadata": {}, "outputs": [], @@ -23,7 +23,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": null, "id": "b15dfdc1-5054-40bc-9631-4c7426eecfd9", "metadata": {}, "outputs": [], @@ -52,7 +52,7 @@ "from pyrad.utils.config import Config, setup_config\n", "\n", "# the new import\n", - "from pyrad.viewer.server import vis_utils\n", + "from pyrad.viewer.server import viewer_utils\n", "\n", "\n", "from hydra import compose, initialize\n", @@ -71,7 +71,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": null, "id": "7fe7478d", "metadata": {}, "outputs": [], @@ -90,7 +90,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": null, "id": "26d6da3c-e28a-4c55-9592-d90dccb86051", "metadata": {}, "outputs": [], @@ -100,7 +100,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": null, "id": "642b0a25-0e88-4eac-b661-a57a74fb10fc", "metadata": {}, "outputs": [], @@ -110,7 +110,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": null, "id": "938f090b-3b28-4fd6-82dc-d4b5c5917134", "metadata": {}, "outputs": [], @@ -121,19 +121,10 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": null, "id": "fd04703a-aa50-45e4-95fd-4d881ff18d61", "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "estimated_time: 3.3333333333333335\n", - "time_elapsed: 3.510408878326416\n" - ] - } - ], + "outputs": [], "source": [ "# move a camera around\n", "num_cameras = len(dataset_inputs.intrinsics)\n", @@ -153,7 +144,7 @@ "\n", "start = time.time()\n", "for camera in cameras:\n", - " vis_utils.set_camera(vis, camera)\n", + " viewer_utils.set_camera(vis, camera)\n", "\n", " # render an image\n", " # outputs = trainer.render_image_in_viewer()\n", @@ -171,6 +162,22 @@ "metadata": {}, "outputs": [], "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd32ba39-fdfe-4689-8ed0-4531d8f2ff04", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ae52a7e6-2a1d-46db-9cc1-7c96b6433a33", + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { diff --git a/pyrad/engine/trainer.py b/pyrad/engine/trainer.py index 5052e71be..eca8d307e 100644 --- a/pyrad/engine/trainer.py +++ b/pyrad/engine/trainer.py @@ -32,7 +32,7 @@ from pyrad.utils import profiler, writer from pyrad.utils.config import Config from pyrad.utils.decorators import check_main_thread from pyrad.utils.writer import EventName, TimeWriter -from pyrad.viewer.server import vis_utils +from pyrad.viewer.server import viewer_utils logging.getLogger("PIL").setLevel(logging.WARNING) @@ -63,7 +63,7 @@ class Trainer: writer.setup_event_writers(config.logging, max_iter=config.trainer.max_num_iterations) profiler.setup_profiler(config.logging) # visualizer variable - self.visualizer_state = vis_utils.VisualizerState(config.viewer) + self.visualizer_state = viewer_utils.VisualizerState(config.viewer) def setup(self, test_mode=False): """Setup the Trainer by calling other setup functions.""" diff --git a/pyrad/graphs/base.py b/pyrad/graphs/base.py index e79ecbf99..b6453bcb6 100644 --- a/pyrad/graphs/base.py +++ b/pyrad/graphs/base.py @@ -34,7 +34,7 @@ from pyrad.graphs.modules.ray_generator import RayGenerator from pyrad.utils import profiler from pyrad.utils.config import GraphConfig from pyrad.utils.misc import get_masked_dict, instantiate_from_dict_config, is_not_none -from pyrad.viewer.server.vis_utils import CameraChangeException +from pyrad.viewer.server.viewer_utils import CameraChangeException @profiler.time_function diff --git a/pyrad/viewer/app/package.json b/pyrad/viewer/app/package.json index 7a4971918..9c9d878c4 100644 --- a/pyrad/viewer/app/package.json +++ b/pyrad/viewer/app/package.json @@ -15,7 +15,9 @@ "react-scripts": "^5.0.1", "socket.io-client": "^4.5.1", "three": "^0.142.0", - "websocket": "^1.0.34" + "websocket": "^1.0.34", + "three-wtm": "^1.0", + "wwobjloader2": "^4.0" }, "scripts": { "start": "react-scripts start", diff --git a/pyrad/viewer/app/src/Animator.js b/pyrad/viewer/app/src/Animator.js deleted file mode 100644 index 93b9f152f..000000000 --- a/pyrad/viewer/app/src/Animator.js +++ /dev/null @@ -1,234 +0,0 @@ -import * as THREE from 'three'; -import CCapture from 'ccapture.js'; //TODO(ethan): check if this is correct -const dat = require('dat.gui'); - -function remove_folders(gui) { - for (let name of Object.keys(gui.__folders)) { - let folder = gui.__folders[name]; - remove_folders(folder); - dat.dom.dom.unbind(window, 'resize', folder.__resizeHandler); - gui.removeFolder(folder); - } -} - -export class Animator { - constructor(viewer) { - this.viewer = viewer; - this.folder = this.viewer.gui.addFolder("Animations"); - this.mixer = new THREE.AnimationMixer(); - this.loader = new THREE.ObjectLoader(); - this.clock = new THREE.Clock(); - this.actions = []; - this.playing = false; - this.time = 0; - this.time_scrubber = null; - this.setup_capturer("png"); - this.duration = 0; - } - - setup_capturer(format) { - this.capturer = new CCapture({ - format: format, - name: "pyrad_" + String(Date.now()) - }); - this.capturer.format = format; - } - - play() { - this.clock.start(); - // this.mixer.timeScale = 1; - for (let action of this.actions) { - action.play(); - } - this.playing = true; - } - - record() { - this.reset(); - this.play(); - this.recording = true; - this.capturer.start(); - } - - pause() { - // this.mixer.timeScale = 0; - this.clock.stop(); - this.playing = false; - - if (this.recording) { - this.stop_capture(); - this.save_capture(); - } - } - - stop_capture() { - this.recording = false; - this.capturer.stop(); - this.viewer.animate(); // restore the animation loop which gets disabled by capturer.stop() - } - - save_capture() { - this.capturer.save(); - if (this.capturer.format === "png") { - alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.png \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4"); - } else if (this.capturer.format === "jpg") { - alert("To convert the still frames into a video, extract the `.tar` file and run: \nffmpeg -r 60 -i %07d.jpg \\\n\t -vcodec libx264 \\\n\t -preset slow \\\n\t -crf 18 \\\n\t output.mp4"); - } - } - - display_progress(time) { - this.time = time; - if (this.time_scrubber !== null) { - this.time_scrubber.updateDisplay(); - } - } - - seek(time) { - this.actions.forEach((action) => { - action.time = Math.max(0, Math.min(action._clip.duration, time)); - }); - this.mixer.update(0); - this.viewer.set_dirty(); - } - - reset() { - for (let action of this.actions) { - action.reset(); - } - this.display_progress(0); - this.mixer.update(0); - this.setup_capturer(this.capturer.format); - this.viewer.set_dirty(); - } - - clear() { - remove_folders(this.folder); - this.mixer.stopAllAction(); - this.actions = []; - this.duration = 0; - this.display_progress(0); - this.mixer = new THREE.AnimationMixer(); - } - - load(animations, options) { - this.clear(); - - this.folder.open(); - let folder = this.folder.addFolder("default"); - folder.open(); - folder.add(this, "play"); - folder.add(this, "pause"); - folder.add(this, "reset"); - - // Note, for some reason when you call `.max()` on a slider controller it does - // correctly change how the slider behaves but does not change the range of values - // that can be entered into the text box attached to the slider. Oh well. We work - // around this by creating the slider with an unreasonably huge range and then calling - // `.min()` and `.max()` on it later. - this.time_scrubber = folder.add(this, "time", 0, 1e9, 0.001); - this.time_scrubber.onChange((value) => this.seek(value)); - - folder.add(this.mixer, "timeScale").step(0.01).min(0); - let recording_folder = folder.addFolder("Recording"); - recording_folder.add(this, "record"); - recording_folder.add({format: "png"}, "format", ["png", "jpg"]).onChange(value => { - this.setup_capturer(value); - }); - - - if (options.play === undefined) { - options.play = true - } - if (options.loopMode === undefined) { - options.loopMode = THREE.LoopRepeat - } - if (options.repetitions === undefined) { - options.repetitions = 1 - } - if (options.clampWhenFinished === undefined) { - options.clampWhenFinished = true - } - - this.duration = 0; - this.progress = 0; - for (let animation of animations) { - let target = this.viewer.scene_tree.find(animation.path).object; - let clip = this.loader.parseAnimations([animation.clip])[0]; - let action = this.mixer.clipAction(clip, target); - action.clampWhenFinished = options.clampWhenFinished; - action.setLoop(options.loopMode, options.repetitions); - this.actions.push(action); - this.duration = Math.max(this.duration, clip.duration); - } - this.time_scrubber.min(0); - this.time_scrubber.max(this.duration); - this.reset(); - if (options.play) { - this.play(); - } - } - - update() { - if (this.playing) { - this.mixer.update(this.clock.getDelta()); - this.viewer.set_dirty(); - if (this.duration != 0) { - let current_time = this.actions.reduce((acc, action) => { - return Math.max(acc, action.time); - }, 0); - this.display_progress(current_time); - } else { - this.display_progress(0); - } - - if (this.actions.every((action) => action.paused)) { - this.pause(); - for (let action of this.actions) { - action.reset(); - } - } - } - } - - after_render() { - if (this.recording) { - this.capturer.capture(this.viewer.renderer.domElement); - } - } -} - -// Generates a gradient texture without filling up -// an entire canvas. We simply create a 2x1 image -// containing only the two colored pixels and then -// set up the appropriate magnification and wrapping -// modes to generate the gradient automatically -function gradient_texture(top_color, bottom_color) { - let colors = [bottom_color, top_color]; - - let width = 1; - let height = 2; - let size = width * height; - var data = new Uint8Array(3 * size); - for (let row = 0; row < height; row++) { - let color = colors[row]; - for (let col = 0; col < width; col++) { - let i = 3 * (row * width + col); - for (let j = 0; j < 3; j++) { - data[i + j] = color[j]; - } - } - } - var texture = new THREE.DataTexture(data, width, height, THREE.RGBFormat); - texture.magFilter = THREE.LinearFilter; - texture.encoding = THREE.LinearEncoding; - // By default, the points in our texture map to the center of - // the pixels, which means that the gradient only occupies - // the middle half of the screen. To get around that, we just have - // to tweak the UV transform matrix - texture.matrixAutoUpdate = false; - texture.matrix.set(0.5, 0, 0.25, - 0, 0.5, 0.25, - 0, 0, 1); - texture.needsUpdate = true - return texture; -} \ No newline at end of file diff --git a/pyrad/viewer/app/src/Background.js b/pyrad/viewer/app/src/Background.js deleted file mode 100644 index 3cc938458..000000000 --- a/pyrad/viewer/app/src/Background.js +++ /dev/null @@ -1,19 +0,0 @@ -import React, { Component } from "react"; - -export class BackgroundDiv extends Component { - componentDidMount() { - document.getElementById("BackgroundDiv-video").play(); - } - render() { - return ( -
- {" "} -
- ); - } -} diff --git a/pyrad/viewer/app/src/ExtensibleObjectLoader.js b/pyrad/viewer/app/src/ExtensibleObjectLoader.js index 3b5e3a8e5..97076364f 100644 --- a/pyrad/viewer/app/src/ExtensibleObjectLoader.js +++ b/pyrad/viewer/app/src/ExtensibleObjectLoader.js @@ -2,7 +2,7 @@ import * as THREE from "three"; import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js"; import { ColladaLoader } from "three/examples/jsm/loaders/ColladaLoader.js"; import { MTLLoader } from "three/examples/jsm/loaders/MTLLoader.js"; -// import {MtlObjBridge} from 'three/examples/jsm/loaders/obj2/bridge/MtlObjBridge.js'; +import { MtlObjBridge } from "wwobjloader2"; import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js"; import { PLYLoader } from "three/examples/jsm/loaders/PLYLoader.js"; import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js"; @@ -193,11 +193,10 @@ export class ExtensibleObjectLoader extends THREE.ObjectLoader { if (json.mtl_library) { let mtl_loader = new MTLLoader(manager); let mtl_parse_result = mtl_loader.parse(json.mtl_library + "\n", ""); - console.log(mtl_parse_result); - // let materials = MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result); - // console.log(materials); - // loader.addMaterials(materials); - // this.onTextureLoad(); + let materials = + MtlObjBridge.addMaterialsFromMtlLoader(mtl_parse_result); + loader.setMaterials(materials); + this.onTextureLoad(); } let obj = loader.parse(json.data + "\n", path); geometry = merge_geometries(obj, true); diff --git a/pyrad/viewer/app/src/SceneNode.js b/pyrad/viewer/app/src/SceneNode.js index 293def860..4f24ce31c 100644 --- a/pyrad/viewer/app/src/SceneNode.js +++ b/pyrad/viewer/app/src/SceneNode.js @@ -3,142 +3,142 @@ import * as THREE from "three"; const dat = require("dat.gui"); function remove_folders(gui) { - for (let name of Object.keys(gui.__folders)) { - let folder = gui.__folders[name]; - remove_folders(folder); - dat.dom.dom.unbind(window, "resize", folder.__resizeHandler); - gui.removeFolder(folder); - } + for (let name of Object.keys(gui.__folders)) { + let folder = gui.__folders[name]; + remove_folders(folder); + dat.dom.dom.unbind(window, "resize", folder.__resizeHandler); + gui.removeFolder(folder); + } } function dispose(object) { - if (!object) { - return; - } - if (object.geometry) { - object.geometry.dispose(); - } - if (object.material) { - if (Array.isArray(object.material)) { - for (let material of object.material) { - if (material.map) { - material.map.dispose(); + if (!object) { + return; + } + if (object.geometry) { + object.geometry.dispose(); + } + if (object.material) { + if (Array.isArray(object.material)) { + for (let material of object.material) { + if (material.map) { + material.map.dispose(); + } + material.dispose(); + } + } else { + if (object.material.map) { + object.material.map.dispose(); + } + object.material.dispose(); } - material.dispose(); - } - } else { - if (object.material.map) { - object.material.map.dispose(); - } - object.material.dispose(); } - } } export class SceneNode { - constructor(object, folder) { - this.object = object; - this.folder = folder; - this.children = {}; - this.create_controls(); - for (let c of this.object.children) { - this.add_child(c); + constructor(object, folder) { + this.object = object; + this.folder = folder; + this.children = {}; + this.create_controls(); + for (let c of this.object.children) { + this.add_child(c); + } } - } - add_child(object) { - let f = this.folder.addFolder(object.name); - let node = new SceneNode(object, f); - this.children[object.name] = node; - return node; - } - - create_child(name) { - let obj = new THREE.Group(); - obj.name = name; - this.object.add(obj); - return this.add_child(obj); - } - - find(path) { - if (path.length == 0) { - return this; - } else { - let name = path[0]; - let child = this.children[name]; - if (child === undefined) { - child = this.create_child(name); - } - return child.find(path.slice(1)); + add_child(object) { + let f = this.folder.addFolder(object.name); + let node = new SceneNode(object, f); + this.children[object.name] = node; + return node; } - } - create_controls() { - if (this.vis_controller !== undefined) { - this.folder.domElement.removeChild(this.vis_controller.domElement); + create_child(name) { + let obj = new THREE.Group(); + obj.name = name; + this.object.add(obj); + return this.add_child(obj); } - this.vis_controller = new dat.controllers.BooleanController( - this.object, - "visible" - ); - this.folder.domElement.prepend(this.vis_controller.domElement); - this.vis_controller.domElement.style.height = "0"; - this.vis_controller.domElement.style.float = "right"; - } - set_property(property, value) { - if (property === "position") { - this.object.position.set(value[0], value[1], value[2]); - } else if (property === "quaternion") { - this.object.quaternion.set(value[0], value[1], value[2], value[3]); - } else if (property === "scale") { - this.object.scale.set(value[0], value[1], value[2]); - } else { - this.object[property] = value; + find(path) { + if (path.length == 0) { + return this; + } else { + let name = path[0]; + let child = this.children[name]; + if (child === undefined) { + child = this.create_child(name); + } + return child.find(path.slice(1)); + } } - this.vis_controller.updateDisplay(); - } - set_transform(matrix) { - let mat = new THREE.Matrix4(); - mat.fromArray(matrix); - mat.decompose( - this.object.position, - this.object.quaternion, - this.object.scale - ); - } - - set_object(object) { - let parent = this.object.parent; - this.dispose_recursive(); - this.object.parent.remove(this.object); - this.object = object; - parent.add(object); - this.create_controls(); - } - - dispose_recursive() { - for (let name of Object.keys(this.children)) { - this.children[name].dispose_recursive(); + create_controls() { + if (this.vis_controller !== undefined) { + this.folder.domElement.removeChild(this.vis_controller.domElement); + } + this.vis_controller = new dat.controllers.BooleanController( + this.object, + "visible" + ); + this.folder.domElement.prepend(this.vis_controller.domElement); + this.vis_controller.domElement.style.height = "0"; + this.vis_controller.domElement.style.float = "right"; } - dispose(this.object); - } - delete(path) { - if (path.length == 0) { - console.error("Can't delete an empty path"); - } else { - let parent = this.find(path.slice(0, path.length - 1)); - let name = path[path.length - 1]; - let child = parent.children[name]; - if (child !== undefined) { - child.dispose_recursive(); - parent.object.remove(child.object); - remove_folders(child.folder); - parent.folder.removeFolder(child.folder); - delete parent.children[name]; - } + set_property(property, value) { + if (property === "position") { + this.object.position.set(value[0], value[1], value[2]); + } else if (property === "quaternion") { + this.object.quaternion.set(value[0], value[1], value[2], value[3]); + } else if (property === "scale") { + this.object.scale.set(value[0], value[1], value[2]); + } else { + this.object[property] = value; + } + this.vis_controller.updateDisplay(); } - } -} + + set_transform(matrix) { + let mat = new THREE.Matrix4(); + mat.fromArray(matrix); + mat.decompose( + this.object.position, + this.object.quaternion, + this.object.scale + ); + } + + set_object(object) { + let parent = this.object.parent; + this.dispose_recursive(); + this.object.parent.remove(this.object); + this.object = object; + parent.add(object); + this.create_controls(); + } + + dispose_recursive() { + for (let name of Object.keys(this.children)) { + this.children[name].dispose_recursive(); + } + dispose(this.object); + } + + delete(path) { + if (path.length == 0) { + console.error("Can't delete an empty path"); + } else { + let parent = this.find(path.slice(0, path.length - 1)); + let name = path[path.length - 1]; + let child = parent.children[name]; + if (child !== undefined) { + child.dispose_recursive(); + parent.object.remove(child.object); + remove_folders(child.folder); + parent.folder.removeFolder(child.folder); + delete parent.children[name]; + } + } + } +} \ No newline at end of file diff --git a/pyrad/viewer/app/src/Viewer.js b/pyrad/viewer/app/src/Viewer.js deleted file mode 100644 index 718e6c13d..000000000 --- a/pyrad/viewer/app/src/Viewer.js +++ /dev/null @@ -1,374 +0,0 @@ -import React, { Component } from "react"; -import * as THREE from "three"; -import { TrackballControls } from "three/examples/jsm/controls/TrackballControls"; -import Stats from "three/examples/jsm/libs/stats.module.js"; -import { GUI } from "dat.gui"; -import { split_path } from "./utils"; -import { SceneNode } from "./SceneNode"; -import { ExtensibleObjectLoader } from "./ExtensibleObjectLoader"; - -function websocket_endpoint_from_url(url) { - let endpoint = url.split("?").pop(); - if (endpoint == "") { - let message = - "Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051"; - window.alert(message); - return null; - } - return endpoint; -} - -function findCameraObjectUnderObject3D(object) { - // seach the tree for the camera - if (object instanceof THREE.Camera) { - return object; - } - for (let name of Object.keys(object.children)) { - return findCameraObjectUnderObject3D(object.children[name]); - } - return null; -} - -var msgpack = require("msgpack-lite"); - -export class Viewer extends Component { - constructor(props) { - super(props); - this.state = { - scene: null, - controls: null, - renderer: null, - gui: null, - scene_tree: null, - viewport_width: null, - viewport_height: null, - }; - this.update = this.update.bind(this); - this.set_object = this.set_object.bind(this); - this.handle_command = this.handle_command.bind(this); - this.threejs_ref = React.createRef(); - } - - handleResize() { - this.state.viewport_width = this.getViewportWidth(); - this.state.viewport_height = this.getViewportHeight(); - this.state.camera_main.aspect = - this.state.viewport_width / this.state.viewport_height; - this.state.camera_main.updateProjectionMatrix(); - this.state.renderer_main.setSize( - this.state.viewport_width, - this.state.viewport_height - ); - } - - update() { - requestAnimationFrame(this.update); - this.handleResize(); - let camera_main = findCameraObjectUnderObject3D( - this.state.scene_tree.find(["Cameras", "Main Camera"]).object - ); - camera_main.updateProjectionMatrix(); - if (this.state.controls_main != null) { - this.state.controls_main.update(); - } - this.state.renderer_main.render(this.state.scene, camera_main); - this.send_camera_over_websocket(); - } - - send_camera_over_websocket() { - /* update the camera information in the python server - if the websocket is connected */ - console.log("send_camera_over_websocket"); - if (this.state.websocket.readyState === WebSocket.OPEN) { - // update the camera information in the python server - let camera_main = findCameraObjectUnderObject3D( - this.state.scene_tree.find(["Cameras", "Main Camera"]).object - ); - console.log(camera_main.toJSON()); - let cmd = "set_object"; - let path = "Cameras/Main Camera"; - let data = { - type: cmd, - path: path, - object: camera_main.toJSON(), - }; - let message = msgpack.encode(data); - this.state.websocket.send(message); - } - } - - set_object(path, object) { - this.state.scene_tree.find(path.concat([""])).set_object(object); - // add controls if object is a camera - if (object instanceof THREE.Camera) { - this.state.controls_main = new TrackballControls( - object, - this.state.renderer_main.domElement - ); - this.state.controls_main.rotateSpeed = 2.0; - this.state.controls_main.zoomSpeed = 0.3; - this.state.controls_main.panSpeed = 0.2; - this.state.controls_main.staticMoving = false; // false is default - this.state.controls_main.target.set(0, 0, 0); // focus point of the controls - this.state.controls_main.autoRotate = false; - this.state.controls_main.dynamicDampingFactor = 1.0; - this.state.controls_main.update(); - // this.send_camera_over_websocket(); - // this.state.controls_main.addEventListener("change", () => { - // this.send_camera_over_websocket(); - // }); - } - } - - set_object_from_json(path, object_json) { - let loader = new ExtensibleObjectLoader(); - loader.parse(object_json, (obj) => { - if ( - obj.geometry !== undefined && - obj.geometry.type === "BufferGeometry" - ) { - if ( - obj.geometry.attributes.normal === undefined || - obj.geometry.attributes.normal.count === 0 - ) { - obj.geometry.computeVertexNormals(); - } - } - obj.castShadow = true; - obj.receiveShadow = true; - this.set_object(path, obj); - }); - } - - set_transform(path, matrix) { - this.state.scene_tree.find(path).set_transform(matrix); - } - - delete_path(path) { - if (path.length === 0) { - console.error("Deleting the entire scene is not implemented."); - } else { - this.state.scene_tree.delete(path); - } - } - - set_property(path, property, value) { - this.state.scene_tree.find(path).set_property(property, value); - // TODO(ethan): handle this issue - if (path[0] === "Background") { - // The background is not an Object3d, so needs a little help. - this.state.scene_tree.find(path).on_update(); - } - } - - handle_command(cmd) { - // convert binary serialization format back to JSON - cmd = msgpack.decode(new Uint8Array(cmd)); - console.log(cmd); - - // three js scene commands - if (cmd.type === "set_object") { - let path = split_path(cmd.path); - this.set_object_from_json(path, cmd.object); - } else if (cmd.type === "set_transform") { - let path = split_path(cmd.path); - this.set_transform(path, cmd.matrix); - } else if (cmd.type === "delete") { - let path = split_path(cmd.path); - this.delete_path(path); - } else if (cmd.type === "set_property") { - let path = split_path(cmd.path); - this.set_property(path, cmd.property, cmd.value); - } - // web rtc commands - else if (cmd.type === "answer") { - let answer = cmd.data; - this.state.pc.setRemoteDescription(answer); - } - - // possibly update the camera information in the python server - // this.send_camera_over_websocket(); - } - - getViewportWidth() { - return window.innerWidth - (window.innerWidth % 2); - } - - getViewportHeight() { - return window.innerHeight; - } - - setupWebRTC() { - console.log("setting up WebRTC"); - // The iceServers config comes from the following URL: - // https://www.metered.ca/tools/openrelay/ - this.state.pc = new RTCPeerConnection({ - iceServers: [{ - urls: "stun:openrelay.metered.ca:80", - }, - { - urls: "turn:openrelay.metered.ca:80", - username: "openrelayproject", - credential: "openrelayproject", - }, - { - urls: "turn:openrelay.metered.ca:443", - username: "openrelayproject", - credential: "openrelayproject", - }, - { - urls: "turn:openrelay.metered.ca:443?transport=tcp", - username: "openrelayproject", - credential: "openrelayproject", - }, - ], - }); - - // connect video - this.state.pc.addEventListener("track", function(evt) { - if (evt.track.kind == "video") { - console.log("setting event stream"); - document.getElementById("WebRTCVideo-video").srcObject = evt.streams[0]; - } - }); - this.state.pc.addTransceiver("video", { direction: "recvonly" }); - - this.state.pc - .createOffer() - .then((offer) => { - return this.state.pc.setLocalDescription(offer); - }) - .then(() => { - // wait for ICE gathering to complete - return new Promise((resolve) => { - if (this.state.pc.iceGatheringState === "complete") { - resolve(); - } else { - var checkState = () => { - if (this.state.pc.iceGatheringState === "complete") { - this.state.pc.removeEventListener( - "icegatheringstatechange", - checkState - ); - resolve(); - } - }; - this.state.pc.addEventListener( - "icegatheringstatechange", - checkState - ); - } - }); - }) - .then(() => { - var offer = this.state.pc.localDescription; - console.log("sending the offer"); - let cmd = "offer"; - let path = ""; - let data = { - type: cmd, - path: path, - data: { - sdp: offer.sdp, - type: offer.type, - }, - }; - let message = msgpack.encode(data); - this.state.websocket.send(message); - }); - } - - componentDidMount() { - // Open the websocket - let endpoint = websocket_endpoint_from_url(window.location.href); - this.state.websocket = new WebSocket("ws://" + endpoint + "/"); - this.state.websocket.onopen = () => { - console.log("websocket connected"); - this.setupWebRTC(); - }; - this.state.websocket.binaryType = "arraybuffer"; - // 'command' for updates to Viewer - this.state.websocket.onmessage = (cmd) => this.handle_command(cmd.data); - this.state.websocket.onclose = function(evt) { - console.log("onclose:", evt); - }; - - // Get size of screen - this.state.viewport_width = this.getViewportWidth(); - this.state.viewport_height = this.getViewportHeight(); - - // Scene - this.state.scene = new THREE.Scene(); - - // GUI - this.state.gui = new GUI(); - let scene_folder = this.state.gui.addFolder("Scene"); - scene_folder.open(); - this.state.scene_tree = new SceneNode(this.state.scene, scene_folder); - - // Renderer main - this.state.renderer_main = new THREE.WebGLRenderer({ - antialias: true, - alpha: true, - }); - this.state.renderer_main.setPixelRatio(window.devicePixelRatio); - this.state.renderer_main.setSize( - this.state.viewport_width, - this.state.viewport_height - ); - this.state.renderer_main.domElement.style.border = "1px solid black"; - - let domElement = document.getElementById("canvas-container-main"); - domElement.append(this.state.renderer_main.domElement); - - // Camera main - this.state.camera_main = new THREE.PerspectiveCamera( - 120, - this.state.viewport_width / this.state.viewport_height, - 0.01, - 100 - ); - this.state.camera_main.position.x = 5; - this.state.camera_main.position.y = -5; - this.state.camera_main.position.z = 5; - this.state.camera_main.up = new THREE.Vector3(0, 0, 1); - this.set_object(["Cameras", "Main Camera"], this.state.camera_main); - - // Axes display - let axes = new THREE.AxesHelper(5); - this.set_object(["Axes"], axes); - - // Grid - let grid = new THREE.GridHelper(20, 20); - this.set_object(["Grid"], grid); - - // Lights - let color = 0xffffff; - let intensity = 1; - let light = new THREE.AmbientLight(color, intensity); - this.set_object(["Light"], light); - - // Stats - var stats = new Stats(); - let domElement_stats = document.getElementById("canvas-container-main"); - domElement_stats.append(stats.dom); - - this.update(); - } - - render() { - return ( < - div > - < - div className = "WebRTCVideo" > - < - video id = "WebRTCVideo-video" - autoPlay playsInline muted > { " " } < - /video>{" "} < - /div>{" "} < - div id = "canvas-container-main" > < /div>{" "} < - div id = "stats-container" > < /div>{" "} < - /div> - ); - } -} \ No newline at end of file diff --git a/pyrad/viewer/app/src/Viewer.jsx b/pyrad/viewer/app/src/Viewer.jsx new file mode 100644 index 000000000..68d404913 --- /dev/null +++ b/pyrad/viewer/app/src/Viewer.jsx @@ -0,0 +1,373 @@ +import React, { Component } from "react"; +import * as THREE from "three"; +import { TrackballControls } from "three/examples/jsm/controls/TrackballControls"; +import Stats from "three/examples/jsm/libs/stats.module.js"; +import { GUI } from "dat.gui"; +import { split_path } from "./utils"; +import { SceneNode } from "./SceneNode"; +import { ExtensibleObjectLoader } from "./ExtensibleObjectLoader"; + +function websocket_endpoint_from_url(url) { + let endpoint = url.split("?").pop(); + if (endpoint == "") { + let message = + "Please set the websocket endpoint. E.g., a correct URL may be: http://localhost:4000?localhost:8051"; + window.alert(message); + return null; + } + return endpoint; +} + +function findCameraObjectUnderObject3D(object) { + // seach the tree for the camera + if (object instanceof THREE.Camera) { + return object; + } + for (let name of Object.keys(object.children)) { + return findCameraObjectUnderObject3D(object.children[name]); + } + return null; +} + +var msgpack = require("msgpack-lite"); + +export class Viewer extends Component { + constructor(props) { + super(props); + this.state = { + scene: null, + controls: null, + renderer: null, + gui: null, + scene_tree: null, + viewport_width: null, + viewport_height: null, + }; + this.update = this.update.bind(this); + this.set_object = this.set_object.bind(this); + this.handle_command = this.handle_command.bind(this); + this.threejs_ref = React.createRef(); + } + + handleResize() { + this.state.viewport_width = this.getViewportWidth(); + this.state.viewport_height = this.getViewportHeight(); + this.state.camera_main.aspect = + this.state.viewport_width / this.state.viewport_height; + this.state.camera_main.updateProjectionMatrix(); + this.state.renderer_main.setSize( + this.state.viewport_width, + this.state.viewport_height + ); + } + + update() { + requestAnimationFrame(this.update); + this.handleResize(); + let camera_main = findCameraObjectUnderObject3D( + this.state.scene_tree.find(["Cameras", "Main Camera"]).object + ); + camera_main.updateProjectionMatrix(); + if (this.state.controls_main != null) { + this.state.controls_main.update(); + } + this.state.renderer_main.render(this.state.scene, camera_main); + this.send_camera_over_websocket(); + } + + send_camera_over_websocket() { + /* update the camera information in the python server + if the websocket is connected */ + // console.log("send_camera_over_websocket"); + if (this.state.websocket.readyState === WebSocket.OPEN) { + // update the camera information in the python server + let camera_main = findCameraObjectUnderObject3D( + this.state.scene_tree.find(["Cameras", "Main Camera"]).object + ); + // console.log(camera_main.toJSON()); + let cmd = "set_object"; + let path = "Cameras/Main Camera"; + let data = { + type: cmd, + path: path, + object: camera_main.toJSON(), + }; + let message = msgpack.encode(data); + this.state.websocket.send(message); + } + } + + set_object(path, object) { + this.state.scene_tree.find(path.concat([""])).set_object(object); + // add controls if object is a camera + if (object instanceof THREE.Camera) { + this.state.controls_main = new TrackballControls( + object, + this.state.renderer_main.domElement + ); + this.state.controls_main.rotateSpeed = 2.0; + this.state.controls_main.zoomSpeed = 0.3; + this.state.controls_main.panSpeed = 0.2; + this.state.controls_main.staticMoving = false; // false is default + this.state.controls_main.target.set(0, 0, 0); // focus point of the controls + this.state.controls_main.autoRotate = false; + this.state.controls_main.dynamicDampingFactor = 1.0; + this.state.controls_main.update(); + // this.send_camera_over_websocket(); + // this.state.controls_main.addEventListener("change", () => { + // this.send_camera_over_websocket(); + // }); + } + } + + set_object_from_json(path, object_json) { + let loader = new ExtensibleObjectLoader(); + loader.parse(object_json, (obj) => { + if ( + obj.geometry !== undefined && + obj.geometry.type === "BufferGeometry" + ) { + if ( + obj.geometry.attributes.normal === undefined || + obj.geometry.attributes.normal.count === 0 + ) { + obj.geometry.computeVertexNormals(); + } + } + obj.castShadow = true; + obj.receiveShadow = true; + this.set_object(path, obj); + }); + } + + set_transform(path, matrix) { + this.state.scene_tree.find(path).set_transform(matrix); + } + + delete_path(path) { + if (path.length === 0) { + console.error("Deleting the entire scene is not implemented."); + } else { + this.state.scene_tree.delete(path); + } + } + + set_property(path, property, value) { + this.state.scene_tree.find(path).set_property(property, value); + // TODO(ethan): handle this issue + if (path[0] === "Background") { + // The background is not an Object3d, so needs a little help. + this.state.scene_tree.find(path).on_update(); + } + } + + handle_command(cmd) { + // convert binary serialization format back to JSON + cmd = msgpack.decode(new Uint8Array(cmd)); + // console.log(cmd); + + // three js scene commands + if (cmd.type === "set_object") { + let path = split_path(cmd.path); + this.set_object_from_json(path, cmd.object); + } else if (cmd.type === "set_transform") { + let path = split_path(cmd.path); + this.set_transform(path, cmd.matrix); + } else if (cmd.type === "delete") { + let path = split_path(cmd.path); + this.delete_path(path); + } else if (cmd.type === "set_property") { + let path = split_path(cmd.path); + this.set_property(path, cmd.property, cmd.value); + } + // web rtc commands + else if (cmd.type === "answer") { + let answer = cmd.data; + this.state.pc.setRemoteDescription(answer); + } + + // possibly update the camera information in the python server + // this.send_camera_over_websocket(); + } + + getViewportWidth() { + return window.innerWidth - (window.innerWidth % 2); + } + + getViewportHeight() { + return window.innerHeight; + } + + setupWebRTC() { + console.log("setting up WebRTC"); + // The iceServers config comes from the following URL: + // https://www.metered.ca/tools/openrelay/ + this.state.pc = new RTCPeerConnection({ + iceServers: [ + { + urls: "stun:openrelay.metered.ca:80", + }, + { + urls: "turn:openrelay.metered.ca:80", + username: "openrelayproject", + credential: "openrelayproject", + }, + { + urls: "turn:openrelay.metered.ca:443", + username: "openrelayproject", + credential: "openrelayproject", + }, + { + urls: "turn:openrelay.metered.ca:443?transport=tcp", + username: "openrelayproject", + credential: "openrelayproject", + }, + ], + }); + + // connect video + this.state.pc.addEventListener("track", function (evt) { + if (evt.track.kind == "video") { + console.log("setting event stream"); + document.getElementById("WebRTCVideo-video").srcObject = evt.streams[0]; + } + }); + this.state.pc.addTransceiver("video", { direction: "recvonly" }); + + this.state.pc + .createOffer() + .then((offer) => { + return this.state.pc.setLocalDescription(offer); + }) + .then(() => { + // wait for ICE gathering to complete + return new Promise((resolve) => { + if (this.state.pc.iceGatheringState === "complete") { + resolve(); + } else { + var checkState = () => { + if (this.state.pc.iceGatheringState === "complete") { + this.state.pc.removeEventListener( + "icegatheringstatechange", + checkState + ); + resolve(); + } + }; + this.state.pc.addEventListener( + "icegatheringstatechange", + checkState + ); + } + }); + }) + .then(() => { + var offer = this.state.pc.localDescription; + console.log("sending the offer"); + let cmd = "offer"; + let path = ""; + let data = { + type: cmd, + path: path, + data: { + sdp: offer.sdp, + type: offer.type, + }, + }; + let message = msgpack.encode(data); + this.state.websocket.send(message); + }); + } + + componentDidMount() { + // Open the websocket + let endpoint = websocket_endpoint_from_url(window.location.href); + this.state.websocket = new WebSocket("ws://" + endpoint + "/"); + this.state.websocket.onopen = () => { + console.log("websocket connected"); + this.setupWebRTC(); + }; + this.state.websocket.binaryType = "arraybuffer"; + // 'command' for updates to Viewer + this.state.websocket.onmessage = (cmd) => this.handle_command(cmd.data); + this.state.websocket.onclose = function (evt) { + console.log("onclose:", evt); + }; + + // Get size of screen + this.state.viewport_width = this.getViewportWidth(); + this.state.viewport_height = this.getViewportHeight(); + + // Scene + this.state.scene = new THREE.Scene(); + + // GUI + this.state.gui = new GUI(); + let scene_folder = this.state.gui.addFolder("Scene"); + scene_folder.open(); + this.state.scene_tree = new SceneNode(this.state.scene, scene_folder); + + // Renderer main + this.state.renderer_main = new THREE.WebGLRenderer({ + antialias: true, + alpha: true, + }); + this.state.renderer_main.setPixelRatio(window.devicePixelRatio); + this.state.renderer_main.setSize( + this.state.viewport_width, + this.state.viewport_height + ); + this.state.renderer_main.domElement.style.border = "1px solid black"; + + let domElement = document.getElementById("canvas-container-main"); + domElement.append(this.state.renderer_main.domElement); + + // Camera main + this.state.camera_main = new THREE.PerspectiveCamera( + 120, + this.state.viewport_width / this.state.viewport_height, + 0.01, + 100 + ); + this.state.camera_main.position.x = 5; + this.state.camera_main.position.y = -5; + this.state.camera_main.position.z = 5; + this.state.camera_main.up = new THREE.Vector3(0, 0, 1); + this.set_object(["Cameras", "Main Camera"], this.state.camera_main); + + // Axes display + let axes = new THREE.AxesHelper(5); + this.set_object(["Axes"], axes); + + // Grid + let grid = new THREE.GridHelper(20, 20); + grid.rotateX(Math.PI / 2); // now on xy plane + this.set_object(["Grid"], grid); + + // Lights + let color = 0xffffff; + let intensity = 1; + let light = new THREE.AmbientLight(color, intensity); + this.set_object(["Light"], light); + + // Stats + var stats = new Stats(); + let domElement_stats = document.getElementById("canvas-container-main"); + domElement_stats.append(stats.dom); + + this.update(); + } + + render() { + return ( +
+
+ +
+
+
+
+ ); + } +} diff --git a/pyrad/viewer/app/src/index.css b/pyrad/viewer/app/src/index.css index 80277e1f3..8c40d46b5 100644 --- a/pyrad/viewer/app/src/index.css +++ b/pyrad/viewer/app/src/index.css @@ -1,43 +1,40 @@ body { - margin: 0; - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", - "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", - sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } code { - font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", - monospace; + font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace; } .BackgroundDiv, .WebRTCVideo { - position: absolute; - top: 0px; - right: 0px; - bottom: 0px; - left: 0px; + position: absolute; + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; } #BackgroundDiv-video, #WebRTCVideo-video { - width: 100%; - height: 100%; - object-fit: fill; + width: 100%; + height: 100%; + object-fit: fill; } #canvas-container-main { - position: absolute; - top: 0px; - right: 0px; - bottom: 0px; - left: 0px; + position: absolute; + top: 0px; + right: 0px; + bottom: 0px; + left: 0px; } #canvas-container-main canvas { - position: relative; - height: 100%; - width: 100%; -} + position: relative; + height: 100%; + width: 100%; +} \ No newline at end of file diff --git a/pyrad/viewer/app/src/serviceWorker.js b/pyrad/viewer/app/src/serviceWorker.js index b04b771a8..a756f090f 100644 --- a/pyrad/viewer/app/src/serviceWorker.js +++ b/pyrad/viewer/app/src/serviceWorker.js @@ -11,131 +11,131 @@ // opt-in, read https://bit.ly/CRA-PWA const isLocalhost = Boolean( - window.location.hostname === 'localhost' || + window.location.hostname === "localhost" || // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || + window.location.hostname === "[::1]" || // 127.0.0.0/8 are considered localhost for IPv4. window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export function register(config) { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebook/create-react-app/issues/2374 - return; - } + if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + window.addEventListener("load", () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - if (isLocalhost) { - // This is running on localhost. Let's check if a service worker still exists or not. - checkValidServiceWorker(swUrl, config); + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); - // Add some additional logging to localhost, pointing developers to the - // service worker/PWA documentation. - navigator.serviceWorker.ready.then(() => { - console.log( - 'This web app is being served cache-first by a service ' + - 'worker. To learn more, visit https://bit.ly/CRA-PWA' - ); + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + "This web app is being served cache-first by a service " + + "worker. To learn more, visit https://bit.ly/CRA-PWA" + ); + }); + } else { + // Is not localhost. Just register service worker + registerValidSW(swUrl, config); + } }); - } else { - // Is not localhost. Just register service worker - registerValidSW(swUrl, config); - } - }); - } + } } function registerValidSW(swUrl, config) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - if (installingWorker == null) { - return; - } - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the updated precached content has been fetched, - // but the previous service worker will still serve the older - // content until all client tabs are closed. - console.log( - 'New content is available and will be used when all ' + - 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' - ); + navigator.serviceWorker + .register(swUrl) + .then((registration) => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + if (installingWorker == null) { + return; + } + installingWorker.onstatechange = () => { + if (installingWorker.state === "installed") { + if (navigator.serviceWorker.controller) { + // At this point, the updated precached content has been fetched, + // but the previous service worker will still serve the older + // content until all client tabs are closed. + console.log( + "New content is available and will be used when all " + + "tabs for this page are closed. See https://bit.ly/CRA-PWA." + ); - // Execute callback - if (config && config.onUpdate) { - config.onUpdate(registration); - } - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log("Content is cached for offline use."); - // Execute callback - if (config && config.onSuccess) { - config.onSuccess(registration); - } - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); + // Execute callback + if (config && config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch((error) => { + console.error("Error during service worker registration:", error); + }); } function checkValidServiceWorker(swUrl, config) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl, { - headers: { 'Service-Worker': 'script' }, - }) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - const contentType = response.headers.get('content-type'); - if ( - response.status === 404 || - (contentType != null && contentType.indexOf('javascript') === -1) - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl, { + headers: { "Service-Worker": "script" }, + }) + .then((response) => { + // Ensure service worker exists, and that we really are getting a JS file. + const contentType = response.headers.get("content-type"); + if ( + response.status === 404 || + (contentType != null && contentType.indexOf("javascript") === -1) + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then((registration) => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log( + "No internet connection found. App is running in offline mode." + ); }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl, config); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); - }); } export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready - .then(registration => { - registration.unregister(); - }) - .catch(error => { - console.error(error.message); - }); - } -} + if ("serviceWorker" in navigator) { + navigator.serviceWorker.ready + .then((registration) => { + registration.unregister(); + }) + .catch((error) => { + console.error(error.message); + }); + } +} \ No newline at end of file diff --git a/pyrad/viewer/app/src/setupTests.js b/pyrad/viewer/app/src/setupTests.js index 74b1a275a..9b1d6d0a7 100644 --- a/pyrad/viewer/app/src/setupTests.js +++ b/pyrad/viewer/app/src/setupTests.js @@ -2,4 +2,4 @@ // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom -import '@testing-library/jest-dom/extend-expect'; +import "@testing-library/jest-dom/extend-expect"; \ No newline at end of file diff --git a/pyrad/viewer/app/src/socket.io.js b/pyrad/viewer/app/src/socket.io.js deleted file mode 100644 index f660564c5..000000000 --- a/pyrad/viewer/app/src/socket.io.js +++ /dev/null @@ -1,7915 +0,0 @@ -/*! - * Socket.IO v3.1.1 - * (c) 2014-2021 Guillermo Rauch - * Released under the MIT License. - */ -(function webpackUniversalModuleDefinition(root, factory) { - if (typeof exports === "object" && typeof module === "object") - module.exports = factory(); - else if (typeof define === "function" && define.amd) define([], factory); - else if (typeof exports === "object") exports["io"] = factory(); - else root["io"] = factory(); -})(window, function () { - return /******/ (function (modules) { - // webpackBootstrap - /******/ // The module cache - /******/ var installedModules = {}; - /******/ - /******/ // The require function - /******/ function __webpack_require__(moduleId) { - /******/ - /******/ // Check if module is in cache - /******/ if (installedModules[moduleId]) { - /******/ return installedModules[moduleId].exports; - /******/ - } - /******/ // Create a new module (and put it into the cache) - /******/ var module = (installedModules[moduleId] = { - /******/ i: moduleId, - /******/ l: false, - /******/ exports: {}, - /******/ - }); - /******/ - /******/ // Execute the module function - /******/ modules[moduleId].call( - module.exports, - module, - module.exports, - __webpack_require__ - ); - /******/ - /******/ // Flag the module as loaded - /******/ module.l = true; - /******/ - /******/ // Return the exports of the module - /******/ return module.exports; - /******/ - } - /******/ - /******/ - /******/ // expose the modules object (__webpack_modules__) - /******/ __webpack_require__.m = modules; - /******/ - /******/ // expose the module cache - /******/ __webpack_require__.c = installedModules; - /******/ - /******/ // define getter function for harmony exports - /******/ __webpack_require__.d = function (exports, name, getter) { - /******/ if (!__webpack_require__.o(exports, name)) { - /******/ Object.defineProperty(exports, name, { - enumerable: true, - get: getter, - }); - /******/ - } - /******/ - }; - /******/ - /******/ // define __esModule on exports - /******/ __webpack_require__.r = function (exports) { - /******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) { - /******/ Object.defineProperty(exports, Symbol.toStringTag, { - value: "Module", - }); - /******/ - } - /******/ Object.defineProperty(exports, "__esModule", { value: true }); - /******/ - }; - /******/ - /******/ // create a fake namespace object - /******/ // mode & 1: value is a module id, require it - /******/ // mode & 2: merge all properties of value into the ns - /******/ // mode & 4: return value when already ns object - /******/ // mode & 8|1: behave like require - /******/ __webpack_require__.t = function (value, mode) { - /******/ if (mode & 1) value = __webpack_require__(value); - /******/ if (mode & 8) return value; - /******/ if ( - mode & 4 && - typeof value === "object" && - value && - value.__esModule - ) - return value; - /******/ var ns = Object.create(null); - /******/ __webpack_require__.r(ns); - /******/ Object.defineProperty(ns, "default", { - enumerable: true, - value: value, - }); - /******/ if (mode & 2 && typeof value != "string") - for (var key in value) - __webpack_require__.d( - ns, - key, - function (key) { - return value[key]; - }.bind(null, key) - ); - /******/ return ns; - /******/ - }; - /******/ - /******/ // getDefaultExport function for compatibility with non-harmony modules - /******/ __webpack_require__.n = function (module) { - /******/ var getter = - module && module.__esModule - ? /******/ function getDefault() { - return module["default"]; - } - : /******/ function getModuleExports() { - return module; - }; - /******/ __webpack_require__.d(getter, "a", getter); - /******/ return getter; - /******/ - }; - /******/ - /******/ // Object.prototype.hasOwnProperty.call - /******/ __webpack_require__.o = function (object, property) { - return Object.prototype.hasOwnProperty.call(object, property); - }; - /******/ - /******/ // __webpack_public_path__ - /******/ __webpack_require__.p = ""; - /******/ - /******/ - /******/ // Load entry module and return exports - /******/ return __webpack_require__( - (__webpack_require__.s = "./build/index.js") - ); - /******/ - })( - /************************************************************************/ - /******/ { - /***/ "./build/index.js": - /*!************************!*\ - !*** ./build/index.js ***! - \************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - "use strict"; - - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.Socket = - exports.io = - exports.Manager = - exports.protocol = - void 0; - - var url_1 = __webpack_require__(/*! ./url */ "./build/url.js"); - - var manager_1 = __webpack_require__( - /*! ./manager */ "./build/manager.js" - ); - - var socket_1 = __webpack_require__( - /*! ./socket */ "./build/socket.js" - ); - - Object.defineProperty(exports, "Socket", { - enumerable: true, - get: function get() { - return socket_1.Socket; - }, - }); - - var debug = __webpack_require__( - /*! debug */ "./node_modules/debug/src/browser.js" - )("socket.io-client"); - /** - * Module exports. - */ - - module.exports = exports = lookup; - /** - * Managers cache. - */ - - var cache = (exports.managers = {}); - - function lookup(uri, opts) { - if (_typeof(uri) === "object") { - opts = uri; - uri = undefined; - } - - opts = opts || {}; - var parsed = url_1.url(uri, opts.path); - var source = parsed.source; - var id = parsed.id; - var path = parsed.path; - var sameNamespace = cache[id] && path in cache[id]["nsps"]; - var newConnection = - opts.forceNew || - opts["force new connection"] || - false === opts.multiplex || - sameNamespace; - var io; - - if (newConnection) { - debug("ignoring socket cache for %s", source); - io = new manager_1.Manager(source, opts); - } else { - if (!cache[id]) { - debug("new io instance for %s", source); - cache[id] = new manager_1.Manager(source, opts); - } - - io = cache[id]; - } - - if (parsed.query && !opts.query) { - opts.query = parsed.queryKey; - } - - return io.socket(parsed.path, opts); - } - - exports.io = lookup; - /** - * Protocol version. - * - * @public - */ - - var socket_io_parser_1 = __webpack_require__( - /*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js" - ); - - Object.defineProperty(exports, "protocol", { - enumerable: true, - get: function get() { - return socket_io_parser_1.protocol; - }, - }); - /** - * `connect`. - * - * @param {String} uri - * @public - */ - - exports.connect = lookup; - /** - * Expose constructors for standalone build. - * - * @public - */ - - var manager_2 = __webpack_require__( - /*! ./manager */ "./build/manager.js" - ); - - Object.defineProperty(exports, "Manager", { - enumerable: true, - get: function get() { - return manager_2.Manager; - }, - }); - - /***/ - }, - - /***/ "./build/manager.js": - /*!**************************!*\ - !*** ./build/manager.js ***! - \**************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - "use strict"; - - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - if (desc.get) { - return desc.get.call(receiver); - } - return desc.value; - }; - } - return _get(target, property, receiver || target); - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - return object; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function" - ); - } - subClass.prototype = Object.create( - superClass && superClass.prototype, - { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - } - ); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - - function _possibleConstructorReturn(self, call) { - if ( - call && - (_typeof(call) === "object" || typeof call === "function") - ) { - return call; - } - return _assertThisInitialized(self); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return self; - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) - ); - return true; - } catch (e) { - return false; - } - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.Manager = void 0; - - var eio = __webpack_require__( - /*! engine.io-client */ "./node_modules/engine.io-client/lib/index.js" - ); - - var socket_1 = __webpack_require__( - /*! ./socket */ "./build/socket.js" - ); - - var Emitter = __webpack_require__( - /*! component-emitter */ "./node_modules/component-emitter/index.js" - ); - - var parser = __webpack_require__( - /*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js" - ); - - var on_1 = __webpack_require__(/*! ./on */ "./build/on.js"); - - var Backoff = __webpack_require__( - /*! backo2 */ "./node_modules/backo2/index.js" - ); - - var debug = __webpack_require__( - /*! debug */ "./node_modules/debug/src/browser.js" - )("socket.io-client:manager"); - - var Manager = /*#__PURE__*/ (function (_Emitter) { - _inherits(Manager, _Emitter); - - var _super = _createSuper(Manager); - - function Manager(uri, opts) { - var _this; - - _classCallCheck(this, Manager); - - _this = _super.call(this); - _this.nsps = {}; - _this.subs = []; - - if (uri && "object" === _typeof(uri)) { - opts = uri; - uri = undefined; - } - - opts = opts || {}; - opts.path = opts.path || "/socket.io"; - _this.opts = opts; - - _this.reconnection(opts.reconnection !== false); - - _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - - _this.reconnectionDelay(opts.reconnectionDelay || 1000); - - _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - - _this.randomizationFactor(opts.randomizationFactor || 0.5); - - _this.backoff = new Backoff({ - min: _this.reconnectionDelay(), - max: _this.reconnectionDelayMax(), - jitter: _this.randomizationFactor(), - }); - - _this.timeout(null == opts.timeout ? 20000 : opts.timeout); - - _this._readyState = "closed"; - _this.uri = uri; - - var _parser = opts.parser || parser; - - _this.encoder = new _parser.Encoder(); - _this.decoder = new _parser.Decoder(); - _this._autoConnect = opts.autoConnect !== false; - if (_this._autoConnect) _this.open(); - return _this; - } - - _createClass(Manager, [ - { - key: "reconnection", - value: function reconnection(v) { - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; - }, - }, - { - key: "reconnectionAttempts", - value: function reconnectionAttempts(v) { - if (v === undefined) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; - }, - }, - { - key: "reconnectionDelay", - value: function reconnectionDelay(v) { - var _a; - - if (v === undefined) return this._reconnectionDelay; - this._reconnectionDelay = v; - (_a = this.backoff) === null || _a === void 0 - ? void 0 - : _a.setMin(v); - return this; - }, - }, - { - key: "randomizationFactor", - value: function randomizationFactor(v) { - var _a; - - if (v === undefined) return this._randomizationFactor; - this._randomizationFactor = v; - (_a = this.backoff) === null || _a === void 0 - ? void 0 - : _a.setJitter(v); - return this; - }, - }, - { - key: "reconnectionDelayMax", - value: function reconnectionDelayMax(v) { - var _a; - - if (v === undefined) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - (_a = this.backoff) === null || _a === void 0 - ? void 0 - : _a.setMax(v); - return this; - }, - }, - { - key: "timeout", - value: function timeout(v) { - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; - }, - /** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @private - */ - }, - { - key: "maybeReconnectOnOpen", - value: function maybeReconnectOnOpen() { - // Only try to reconnect if it's the first time we're connecting - if ( - !this._reconnecting && - this._reconnection && - this.backoff.attempts === 0 - ) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } - }, - /** - * Sets the current transport `socket`. - * - * @param {Function} fn - optional, callback - * @return self - * @public - */ - }, - { - key: "open", - value: function open(fn) { - var _this2 = this; - - debug("readyState %s", this._readyState); - if (~this._readyState.indexOf("open")) return this; - debug("opening %s", this.uri); - this.engine = eio(this.uri, this.opts); - var socket = this.engine; - var self = this; - this._readyState = "opening"; - this.skipReconnect = false; // emit `open` - - var openSubDestroy = on_1.on(socket, "open", function () { - self.onopen(); - fn && fn(); - }); // emit `error` - - var errorSub = on_1.on(socket, "error", function (err) { - debug("error"); - self.cleanup(); - self._readyState = "closed"; - - _get( - _getPrototypeOf(Manager.prototype), - "emit", - _this2 - ).call(_this2, "error", err); - - if (fn) { - fn(err); - } else { - // Only do this if there is no fn to handle the error - self.maybeReconnectOnOpen(); - } - }); - - if (false !== this._timeout) { - var timeout = this._timeout; - debug("connect attempt will timeout after %d", timeout); - - if (timeout === 0) { - openSubDestroy(); // prevents a race condition with the 'open' event - } // set timer - - var timer = setTimeout(function () { - debug("connect attempt timed out after %d", timeout); - openSubDestroy(); - socket.close(); - socket.emit("error", new Error("timeout")); - }, timeout); - this.subs.push(function subDestroy() { - clearTimeout(timer); - }); - } - - this.subs.push(openSubDestroy); - this.subs.push(errorSub); - return this; - }, - /** - * Alias for open() - * - * @return self - * @public - */ - }, - { - key: "connect", - value: function connect(fn) { - return this.open(fn); - }, - /** - * Called upon transport open. - * - * @private - */ - }, - { - key: "onopen", - value: function onopen() { - debug("open"); // clear old subs - - this.cleanup(); // mark as open - - this._readyState = "open"; - - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "open" - ); // add new subs - - var socket = this.engine; - this.subs.push( - on_1.on(socket, "ping", this.onping.bind(this)), - on_1.on(socket, "data", this.ondata.bind(this)), - on_1.on(socket, "error", this.onerror.bind(this)), - on_1.on(socket, "close", this.onclose.bind(this)), - on_1.on(this.decoder, "decoded", this.ondecoded.bind(this)) - ); - }, - /** - * Called upon a ping. - * - * @private - */ - }, - { - key: "onping", - value: function onping() { - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "ping" - ); - }, - /** - * Called with data. - * - * @private - */ - }, - { - key: "ondata", - value: function ondata(data) { - this.decoder.add(data); - }, - /** - * Called when parser fully decodes a packet. - * - * @private - */ - }, - { - key: "ondecoded", - value: function ondecoded(packet) { - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "packet", - packet - ); - }, - /** - * Called upon socket error. - * - * @private - */ - }, - { - key: "onerror", - value: function onerror(err) { - debug("error", err); - - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "error", - err - ); - }, - /** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @public - */ - }, - { - key: "socket", - value: function socket(nsp, opts) { - var socket = this.nsps[nsp]; - - if (!socket) { - socket = new socket_1.Socket(this, nsp, opts); - this.nsps[nsp] = socket; - } - - return socket; - }, - /** - * Called upon a socket close. - * - * @param socket - * @private - */ - }, - { - key: "_destroy", - value: function _destroy(socket) { - var nsps = Object.keys(this.nsps); - - for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) { - var nsp = _nsps[_i]; - var _socket = this.nsps[nsp]; - - if (_socket.active) { - debug("socket %s is still active, skipping close", nsp); - return; - } - } - - this._close(); - }, - /** - * Writes a packet. - * - * @param packet - * @private - */ - }, - { - key: "_packet", - value: function _packet(packet) { - debug("writing packet %j", packet); - var encodedPackets = this.encoder.encode(packet); - - for (var i = 0; i < encodedPackets.length; i++) { - this.engine.write(encodedPackets[i], packet.options); - } - }, - /** - * Clean up transport subscriptions and packet buffer. - * - * @private - */ - }, - { - key: "cleanup", - value: function cleanup() { - debug("cleanup"); - this.subs.forEach(function (subDestroy) { - return subDestroy(); - }); - this.subs.length = 0; - this.decoder.destroy(); - }, - /** - * Close the current socket. - * - * @private - */ - }, - { - key: "_close", - value: function _close() { - debug("disconnect"); - this.skipReconnect = true; - this._reconnecting = false; - - if ("opening" === this._readyState) { - // `onclose` will not fire because - // an open event never happened - this.cleanup(); - } - - this.backoff.reset(); - this._readyState = "closed"; - if (this.engine) this.engine.close(); - }, - /** - * Alias for close() - * - * @private - */ - }, - { - key: "disconnect", - value: function disconnect() { - return this._close(); - }, - /** - * Called upon engine close. - * - * @private - */ - }, - { - key: "onclose", - value: function onclose(reason) { - debug("onclose"); - this.cleanup(); - this.backoff.reset(); - this._readyState = "closed"; - - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "close", - reason - ); - - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } - }, - /** - * Attempt a reconnection. - * - * @private - */ - }, - { - key: "reconnect", - value: function reconnect() { - var _this3 = this; - - if (this._reconnecting || this.skipReconnect) return this; - var self = this; - - if (this.backoff.attempts >= this._reconnectionAttempts) { - debug("reconnect failed"); - this.backoff.reset(); - - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "reconnect_failed" - ); - - this._reconnecting = false; - } else { - var delay = this.backoff.duration(); - debug("will wait %dms before reconnect attempt", delay); - this._reconnecting = true; - var timer = setTimeout(function () { - if (self.skipReconnect) return; - debug("attempting reconnect"); - - _get( - _getPrototypeOf(Manager.prototype), - "emit", - _this3 - ).call( - _this3, - "reconnect_attempt", - self.backoff.attempts - ); // check again for the case socket closed in above events - - if (self.skipReconnect) return; - self.open(function (err) { - if (err) { - debug("reconnect attempt error"); - self._reconnecting = false; - self.reconnect(); - - _get( - _getPrototypeOf(Manager.prototype), - "emit", - _this3 - ).call(_this3, "reconnect_error", err); - } else { - debug("reconnect success"); - self.onreconnect(); - } - }); - }, delay); - this.subs.push(function subDestroy() { - clearTimeout(timer); - }); - } - }, - /** - * Called upon successful reconnect. - * - * @private - */ - }, - { - key: "onreconnect", - value: function onreconnect() { - var attempt = this.backoff.attempts; - this._reconnecting = false; - this.backoff.reset(); - - _get(_getPrototypeOf(Manager.prototype), "emit", this).call( - this, - "reconnect", - attempt - ); - }, - }, - ]); - - return Manager; - })(Emitter); - - exports.Manager = Manager; - - /***/ - }, - - /***/ "./build/on.js": - /*!*********************!*\ - !*** ./build/on.js ***! - \*********************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.on = void 0; - - function on(obj, ev, fn) { - obj.on(ev, fn); - return function subDestroy() { - obj.off(ev, fn); - }; - } - - exports.on = on; - - /***/ - }, - - /***/ "./build/socket.js": - /*!*************************!*\ - !*** ./build/socket.js ***! - \*************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - "use strict"; - - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - function _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; - } - }, - }; - } - - function _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); - } - - function _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; - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - if (desc.get) { - return desc.get.call(receiver); - } - return desc.value; - }; - } - return _get(target, property, receiver || target); - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - return object; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function" - ); - } - subClass.prototype = Object.create( - superClass && superClass.prototype, - { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - } - ); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - - function _possibleConstructorReturn(self, call) { - if ( - call && - (_typeof(call) === "object" || typeof call === "function") - ) { - return call; - } - return _assertThisInitialized(self); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return self; - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) - ); - return true; - } catch (e) { - return false; - } - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.Socket = void 0; - - var socket_io_parser_1 = __webpack_require__( - /*! socket.io-parser */ "./node_modules/socket.io-parser/dist/index.js" - ); - - var Emitter = __webpack_require__( - /*! component-emitter */ "./node_modules/component-emitter/index.js" - ); - - var on_1 = __webpack_require__(/*! ./on */ "./build/on.js"); - - var debug = __webpack_require__( - /*! debug */ "./node_modules/debug/src/browser.js" - )("socket.io-client:socket"); - /** - * Internal events. - * These events can't be emitted by the user. - */ - - var RESERVED_EVENTS = Object.freeze({ - connect: 1, - connect_error: 1, - disconnect: 1, - disconnecting: 1, - // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener - newListener: 1, - removeListener: 1, - }); - - var Socket = /*#__PURE__*/ (function (_Emitter) { - _inherits(Socket, _Emitter); - - var _super = _createSuper(Socket); - - /** - * `Socket` constructor. - * - * @public - */ - function Socket(io, nsp, opts) { - var _this; - - _classCallCheck(this, Socket); - - _this = _super.call(this); - _this.receiveBuffer = []; - _this.sendBuffer = []; - _this.ids = 0; - _this.acks = {}; - _this.flags = {}; - _this.io = io; - _this.nsp = nsp; - _this.ids = 0; - _this.acks = {}; - _this.receiveBuffer = []; - _this.sendBuffer = []; - _this.connected = false; - _this.disconnected = true; - _this.flags = {}; - - if (opts && opts.auth) { - _this.auth = opts.auth; - } - - if (_this.io._autoConnect) _this.open(); - return _this; - } - /** - * Subscribe to open, close and packet events - * - * @private - */ - - _createClass(Socket, [ - { - key: "subEvents", - value: function subEvents() { - if (this.subs) return; - var io = this.io; - this.subs = [ - on_1.on(io, "open", this.onopen.bind(this)), - on_1.on(io, "packet", this.onpacket.bind(this)), - on_1.on(io, "error", this.onerror.bind(this)), - on_1.on(io, "close", this.onclose.bind(this)), - ]; - }, - /** - * Whether the Socket will try to reconnect when its Manager connects or reconnects - */ - }, - { - key: "connect", - - /** - * "Opens" the socket. - * - * @public - */ - value: function connect() { - if (this.connected) return this; - this.subEvents(); - if (!this.io["_reconnecting"]) this.io.open(); // ensure open - - if ("open" === this.io._readyState) this.onopen(); - return this; - }, - /** - * Alias for connect() - */ - }, - { - key: "open", - value: function open() { - return this.connect(); - }, - /** - * Sends a `message` event. - * - * @return self - * @public - */ - }, - { - key: "send", - value: function send() { - for ( - var _len = arguments.length, - args = new Array(_len), - _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key]; - } - - args.unshift("message"); - this.emit.apply(this, args); - return this; - }, - /** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @param ev - event name - * @return self - * @public - */ - }, - { - key: "emit", - value: function emit(ev) { - if (RESERVED_EVENTS.hasOwnProperty(ev)) { - throw new Error('"' + ev + '" is a reserved event name'); - } - - for ( - var _len2 = arguments.length, - args = new Array(_len2 > 1 ? _len2 - 1 : 0), - _key2 = 1; - _key2 < _len2; - _key2++ - ) { - args[_key2 - 1] = arguments[_key2]; - } - - args.unshift(ev); - var packet = { - type: socket_io_parser_1.PacketType.EVENT, - data: args, - }; - packet.options = {}; - packet.options.compress = this.flags.compress !== false; // event ack callback - - if ("function" === typeof args[args.length - 1]) { - debug("emitting packet with ack id %d", this.ids); - this.acks[this.ids] = args.pop(); - packet.id = this.ids++; - } - - var isTransportWritable = - this.io.engine && - this.io.engine.transport && - this.io.engine.transport.writable; - var discardPacket = - this.flags["volatile"] && - (!isTransportWritable || !this.connected); - - if (discardPacket) { - debug( - "discard packet as the transport is not currently writable" - ); - } else if (this.connected) { - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - - this.flags = {}; - return this; - }, - /** - * Sends a packet. - * - * @param packet - * @private - */ - }, - { - key: "packet", - value: function packet(_packet) { - _packet.nsp = this.nsp; - - this.io._packet(_packet); - }, - /** - * Called upon engine `open`. - * - * @private - */ - }, - { - key: "onopen", - value: function onopen() { - var _this2 = this; - - debug("transport is open - connecting"); - - if (typeof this.auth == "function") { - this.auth(function (data) { - _this2.packet({ - type: socket_io_parser_1.PacketType.CONNECT, - data: data, - }); - }); - } else { - this.packet({ - type: socket_io_parser_1.PacketType.CONNECT, - data: this.auth, - }); - } - }, - /** - * Called upon engine or manager `error`. - * - * @param err - * @private - */ - }, - { - key: "onerror", - value: function onerror(err) { - if (!this.connected) { - _get(_getPrototypeOf(Socket.prototype), "emit", this).call( - this, - "connect_error", - err - ); - } - }, - /** - * Called upon engine `close`. - * - * @param reason - * @private - */ - }, - { - key: "onclose", - value: function onclose(reason) { - debug("close (%s)", reason); - this.connected = false; - this.disconnected = true; - delete this.id; - - _get(_getPrototypeOf(Socket.prototype), "emit", this).call( - this, - "disconnect", - reason - ); - }, - /** - * Called with socket packet. - * - * @param packet - * @private - */ - }, - { - key: "onpacket", - value: function onpacket(packet) { - var sameNamespace = packet.nsp === this.nsp; - if (!sameNamespace) return; - - switch (packet.type) { - case socket_io_parser_1.PacketType.CONNECT: - if (packet.data && packet.data.sid) { - var id = packet.data.sid; - this.onconnect(id); - } else { - _get( - _getPrototypeOf(Socket.prototype), - "emit", - this - ).call( - this, - "connect_error", - new Error( - "It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)" - ) - ); - } - - break; - - case socket_io_parser_1.PacketType.EVENT: - this.onevent(packet); - break; - - case socket_io_parser_1.PacketType.BINARY_EVENT: - this.onevent(packet); - break; - - case socket_io_parser_1.PacketType.ACK: - this.onack(packet); - break; - - case socket_io_parser_1.PacketType.BINARY_ACK: - this.onack(packet); - break; - - case socket_io_parser_1.PacketType.DISCONNECT: - this.ondisconnect(); - break; - - case socket_io_parser_1.PacketType.CONNECT_ERROR: - var err = new Error(packet.data.message); // @ts-ignore - - err.data = packet.data.data; - - _get( - _getPrototypeOf(Socket.prototype), - "emit", - this - ).call(this, "connect_error", err); - - break; - } - }, - /** - * Called upon a server event. - * - * @param packet - * @private - */ - }, - { - key: "onevent", - value: function onevent(packet) { - var args = packet.data || []; - debug("emitting event %j", args); - - if (null != packet.id) { - debug("attaching ack callback to event"); - args.push(this.ack(packet.id)); - } - - if (this.connected) { - this.emitEvent(args); - } else { - this.receiveBuffer.push(Object.freeze(args)); - } - }, - }, - { - key: "emitEvent", - value: function emitEvent(args) { - if (this._anyListeners && this._anyListeners.length) { - var listeners = this._anyListeners.slice(); - - var _iterator = _createForOfIteratorHelper(listeners), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done; ) { - var listener = _step.value; - listener.apply(this, args); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - - _get(_getPrototypeOf(Socket.prototype), "emit", this).apply( - this, - args - ); - }, - /** - * Produces an ack callback to emit with an event. - * - * @private - */ - }, - { - key: "ack", - value: function ack(id) { - var self = this; - var sent = false; - return function () { - // prevent double callbacks - if (sent) return; - sent = true; - - for ( - var _len3 = arguments.length, - args = new Array(_len3), - _key3 = 0; - _key3 < _len3; - _key3++ - ) { - args[_key3] = arguments[_key3]; - } - - debug("sending ack %j", args); - self.packet({ - type: socket_io_parser_1.PacketType.ACK, - id: id, - data: args, - }); - }; - }, - /** - * Called upon a server acknowlegement. - * - * @param packet - * @private - */ - }, - { - key: "onack", - value: function onack(packet) { - var ack = this.acks[packet.id]; - - if ("function" === typeof ack) { - debug("calling ack %s with %j", packet.id, packet.data); - ack.apply(this, packet.data); - delete this.acks[packet.id]; - } else { - debug("bad ack %s", packet.id); - } - }, - /** - * Called upon server connect. - * - * @private - */ - }, - { - key: "onconnect", - value: function onconnect(id) { - debug("socket connected with id %s", id); - this.id = id; - this.connected = true; - this.disconnected = false; - - _get(_getPrototypeOf(Socket.prototype), "emit", this).call( - this, - "connect" - ); - - this.emitBuffered(); - }, - /** - * Emit buffered events (received and emitted). - * - * @private - */ - }, - { - key: "emitBuffered", - value: function emitBuffered() { - var _this3 = this; - - this.receiveBuffer.forEach(function (args) { - return _this3.emitEvent(args); - }); - this.receiveBuffer = []; - this.sendBuffer.forEach(function (packet) { - return _this3.packet(packet); - }); - this.sendBuffer = []; - }, - /** - * Called upon server disconnect. - * - * @private - */ - }, - { - key: "ondisconnect", - value: function ondisconnect() { - debug("server disconnect (%s)", this.nsp); - this.destroy(); - this.onclose("io server disconnect"); - }, - /** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @private - */ - }, - { - key: "destroy", - value: function destroy() { - if (this.subs) { - // clean subscriptions to avoid reconnections - this.subs.forEach(function (subDestroy) { - return subDestroy(); - }); - this.subs = undefined; - } - - this.io["_destroy"](this); - }, - /** - * Disconnects the socket manually. - * - * @return self - * @public - */ - }, - { - key: "disconnect", - value: function disconnect() { - if (this.connected) { - debug("performing disconnect (%s)", this.nsp); - this.packet({ - type: socket_io_parser_1.PacketType.DISCONNECT, - }); - } // remove socket from pool - - this.destroy(); - - if (this.connected) { - // fire events - this.onclose("io client disconnect"); - } - - return this; - }, - /** - * Alias for disconnect() - * - * @return self - * @public - */ - }, - { - key: "close", - value: function close() { - return this.disconnect(); - }, - /** - * Sets the compress flag. - * - * @param compress - if `true`, compresses the sending data - * @return self - * @public - */ - }, - { - key: "compress", - value: function compress(_compress) { - this.flags.compress = _compress; - return this; - }, - /** - * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not - * ready to send messages. - * - * @returns self - * @public - */ - }, - { - key: "onAny", - - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. - * - * @param listener - * @public - */ - value: function onAny(listener) { - this._anyListeners = this._anyListeners || []; - - this._anyListeners.push(listener); - - return this; - }, - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. The listener is added to the beginning of the listeners array. - * - * @param listener - * @public - */ - }, - { - key: "prependAny", - value: function prependAny(listener) { - this._anyListeners = this._anyListeners || []; - - this._anyListeners.unshift(listener); - - return this; - }, - /** - * Removes the listener that will be fired when any event is emitted. - * - * @param listener - * @public - */ - }, - { - key: "offAny", - value: function offAny(listener) { - if (!this._anyListeners) { - return this; - } - - if (listener) { - var listeners = this._anyListeners; - - for (var i = 0; i < listeners.length; i++) { - if (listener === listeners[i]) { - listeners.splice(i, 1); - return this; - } - } - } else { - this._anyListeners = []; - } - - return this; - }, - /** - * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, - * e.g. to remove listeners. - * - * @public - */ - }, - { - key: "listenersAny", - value: function listenersAny() { - return this._anyListeners || []; - }, - }, - { - key: "active", - get: function get() { - return !!this.subs; - }, - }, - { - key: "volatile", - get: function get() { - this.flags["volatile"] = true; - return this; - }, - }, - ]); - - return Socket; - })(Emitter); - - exports.Socket = Socket; - - /***/ - }, - - /***/ "./build/url.js": - /*!**********************!*\ - !*** ./build/url.js ***! - \**********************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true, - }); - exports.url = void 0; - - var parseuri = __webpack_require__( - /*! parseuri */ "./node_modules/parseuri/index.js" - ); - - var debug = __webpack_require__( - /*! debug */ "./node_modules/debug/src/browser.js" - )("socket.io-client:url"); - /** - * URL parser. - * - * @param uri - url - * @param path - the request path of the connection - * @param loc - An object meant to mimic window.location. - * Defaults to window.location. - * @public - */ - - function url(uri) { - var path = - arguments.length > 1 && arguments[1] !== undefined - ? arguments[1] - : ""; - var loc = arguments.length > 2 ? arguments[2] : undefined; - var obj = uri; // default to window.location - - loc = loc || (typeof location !== "undefined" && location); - if (null == uri) uri = loc.protocol + "//" + loc.host; // relative path support - - if (typeof uri === "string") { - if ("/" === uri.charAt(0)) { - if ("/" === uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.host + uri; - } - } - - if (!/^(https?|wss?):\/\//.test(uri)) { - debug("protocol-less url %s", uri); - - if ("undefined" !== typeof loc) { - uri = loc.protocol + "//" + uri; - } else { - uri = "https://" + uri; - } - } // parse - - debug("parse %s", uri); - obj = parseuri(uri); - } // make sure we treat `localhost:80` and `localhost` equally - - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = "80"; - } else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = "443"; - } - } - - obj.path = obj.path || "/"; - var ipv6 = obj.host.indexOf(":") !== -1; - var host = ipv6 ? "[" + obj.host + "]" : obj.host; // define unique id - - obj.id = obj.protocol + "://" + host + ":" + obj.port + path; // define href - - obj.href = - obj.protocol + - "://" + - host + - (loc && loc.port === obj.port ? "" : ":" + obj.port); - return obj; - } - - exports.url = url; - - /***/ - }, - - /***/ "./node_modules/backo2/index.js": - /*!**************************************!*\ - !*** ./node_modules/backo2/index.js ***! - \**************************************/ - /*! no static exports found */ - /***/ function (module, exports) { - /** - * Expose `Backoff`. - */ - module.exports = Backoff; - /** - * Initialize backoff timer with `opts`. - * - * - `min` initial timeout in milliseconds [100] - * - `max` max timeout [10000] - * - `jitter` [0] - * - `factor` [2] - * - * @param {Object} opts - * @api public - */ - - function Backoff(opts) { - opts = opts || {}; - this.ms = opts.min || 100; - this.max = opts.max || 10000; - this.factor = opts.factor || 2; - this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; - this.attempts = 0; - } - /** - * Return the backoff duration. - * - * @return {Number} - * @api public - */ - - Backoff.prototype.duration = function () { - var ms = this.ms * Math.pow(this.factor, this.attempts++); - - if (this.jitter) { - var rand = Math.random(); - var deviation = Math.floor(rand * this.jitter * ms); - ms = - (Math.floor(rand * 10) & 1) == 0 - ? ms - deviation - : ms + deviation; - } - - return Math.min(ms, this.max) | 0; - }; - /** - * Reset the number of attempts. - * - * @api public - */ - - Backoff.prototype.reset = function () { - this.attempts = 0; - }; - /** - * Set the minimum duration - * - * @api public - */ - - Backoff.prototype.setMin = function (min) { - this.ms = min; - }; - /** - * Set the maximum duration - * - * @api public - */ - - Backoff.prototype.setMax = function (max) { - this.max = max; - }; - /** - * Set the jitter - * - * @api public - */ - - Backoff.prototype.setJitter = function (jitter) { - this.jitter = jitter; - }; - - /***/ - }, - - /***/ "./node_modules/component-emitter/index.js": - /*!*************************************************!*\ - !*** ./node_modules/component-emitter/index.js ***! - \*************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - /** - * Expose `Emitter`. - */ - if (true) { - module.exports = Emitter; - } - /** - * Initialize a new `Emitter`. - * - * @api public - */ - - function Emitter(obj) { - if (obj) return mixin(obj); - } - - /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - - return obj; - } - /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.on = Emitter.prototype.addEventListener = function ( - event, - fn - ) { - this._callbacks = this._callbacks || {}; - (this._callbacks["$" + event] = - this._callbacks["$" + event] || []).push(fn); - return this; - }; - /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.once = function (event, fn) { - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - - on.fn = fn; - this.on(event, on); - return this; - }; - /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.off = - Emitter.prototype.removeListener = - Emitter.prototype.removeAllListeners = - Emitter.prototype.removeEventListener = - function (event, fn) { - this._callbacks = this._callbacks || {}; // all - - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } // specific event - - var callbacks = this._callbacks["$" + event]; - if (!callbacks) return this; // remove all handlers - - if (1 == arguments.length) { - delete this._callbacks["$" + event]; - return this; - } // remove specific handler - - var cb; - - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } // Remove event specific arrays for event types that no - // one is subscribed for to avoid memory leak. - - if (callbacks.length === 0) { - delete this._callbacks["$" + event]; - } - - return this; - }; - /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - - Emitter.prototype.emit = function (event) { - this._callbacks = this._callbacks || {}; - var args = new Array(arguments.length - 1), - callbacks = this._callbacks["$" + event]; - - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - - if (callbacks) { - callbacks = callbacks.slice(0); - - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - - return this; - }; - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - - Emitter.prototype.listeners = function (event) { - this._callbacks = this._callbacks || {}; - return this._callbacks["$" + event] || []; - }; - /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - - Emitter.prototype.hasListeners = function (event) { - return !!this.listeners(event).length; - }; - - /***/ - }, - - /***/ "./node_modules/debug/src/browser.js": - /*!*******************************************!*\ - !*** ./node_modules/debug/src/browser.js ***! - \*******************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - /* eslint-env browser */ - - /** - * This is the web browser implementation of `debug()`. - */ - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = localstorage(); - - exports.destroy = (function () { - var warned = false; - return function () { - if (!warned) { - warned = true; - console.warn( - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - } - }; - })(); - /** - * Colors. - */ - - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33", - ]; - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - // eslint-disable-next-line complexity - - function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if ( - typeof window !== "undefined" && - window.process && - (window.process.type === "renderer" || window.process.__nwjs) - ) { - return true; - } // Internet Explorer and Edge do not support colors. - - if ( - typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) - ) { - return false; - } // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - - return ( - (typeof document !== "undefined" && - document.documentElement && - document.documentElement.style && - document.documentElement.style.WebkitAppearance) || // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== "undefined" && - window.console && - (window.console.firebug || - (window.console.exception && window.console.table))) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && - parseInt(RegExp.$1, 10) >= 31) || // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== "undefined" && - navigator.userAgent && - navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)) - ); - } - /** - * Colorize log arguments if enabled. - * - * @api public - */ - - function formatArgs(args) { - args[0] = - (this.useColors ? "%c" : "") + - this.namespace + - (this.useColors ? " %c" : " ") + - args[0] + - (this.useColors ? "%c " : " ") + - "+" + - module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - var c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function (match) { - if (match === "%%") { - return; - } - - index++; - - if (match === "%c") { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - args.splice(lastC, 0, c); - } - /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ - - exports.log = console.debug || console.log || function () {}; - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); - } else { - exports.storage.removeItem("debug"); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - } - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - - function load() { - var r; - - try { - r = exports.storage.getItem("debug"); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - - if (!r && typeof process !== "undefined" && "env" in process) { - r = process.env.DEBUG; - } - - return r; - } - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - - function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - } - - module.exports = __webpack_require__( - /*! ./common */ "./node_modules/debug/src/common.js" - )(exports); - var formatters = module.exports.formatters; - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - - formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; - - /***/ - }, - - /***/ "./node_modules/debug/src/common.js": - /*!******************************************!*\ - !*** ./node_modules/debug/src/common.js ***! - \******************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - function _toConsumableArray(arr) { - return ( - _arrayWithoutHoles(arr) || - _iterableToArray(arr) || - _unsupportedIterableToArray(arr) || - _nonIterableSpread() - ); - } - - function _nonIterableSpread() { - throw new TypeError( - "Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method." - ); - } - - function _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); - } - - function _iterableToArray(iter) { - if ( - typeof Symbol !== "undefined" && - Symbol.iterator in Object(iter) - ) - return Array.from(iter); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _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; - } - - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - function setup(env) { - createDebug.debug = createDebug; - createDebug["default"] = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __webpack_require__( - /*! ms */ "./node_modules/ms/index.js" - ); - createDebug.destroy = destroy; - Object.keys(env).forEach(function (key) { - createDebug[key] = env[key]; - }); - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - - createDebug.formatters = {}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - - function selectColor(namespace) { - var hash = 0; - - for (var i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[ - Math.abs(hash) % createDebug.colors.length - ]; - } - - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - - function createDebug(namespace) { - var prevTime; - var enableOverride = null; - - function debug() { - for ( - var _len = arguments.length, args = new Array(_len), _key = 0; - _key < _len; - _key++ - ) { - args[_key] = arguments[_key]; - } - - // Disabled? - if (!debug.enabled) { - return; - } - - var self = debug; // Set `diff` timestamp - - var curr = Number(new Date()); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== "string") { - // Anything else let's inspect with %O - args.unshift("%O"); - } // Apply any `formatters` transformations - - var index = 0; - args[0] = args[0].replace( - /%([a-zA-Z%])/g, - function (match, format) { - // If we encounter an escaped % then don't increase the array index - if (match === "%%") { - return "%"; - } - - index++; - var formatter = createDebug.formatters[format]; - - if (typeof formatter === "function") { - var val = args[index]; - match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` - - args.splice(index, 1); - index--; - } - - return match; - } - ); // Apply env-specific formatting (colors, etc.) - - createDebug.formatArgs.call(self, args); - var logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, "enabled", { - enumerable: true, - configurable: false, - get: function get() { - return enableOverride === null - ? createDebug.enabled(namespace) - : enableOverride; - }, - set: function set(v) { - enableOverride = v; - }, - }); // Env-specific initialization logic for debug instances - - if (typeof createDebug.init === "function") { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - var newDebug = createDebug( - this.namespace + - (typeof delimiter === "undefined" ? ":" : delimiter) + - namespace - ); - newDebug.log = this.log; - return newDebug; - } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.names = []; - createDebug.skips = []; - var i; - var split = ( - typeof namespaces === "string" ? namespaces : "" - ).split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, ".*?"); - - if (namespaces[0] === "-") { - createDebug.skips.push( - new RegExp("^" + namespaces.substr(1) + "$") - ); - } else { - createDebug.names.push(new RegExp("^" + namespaces + "$")); - } - } - } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - - function disable() { - var namespaces = [] - .concat( - _toConsumableArray(createDebug.names.map(toNamespace)), - _toConsumableArray( - createDebug.skips - .map(toNamespace) - .map(function (namespace) { - return "-" + namespace; - }) - ) - ) - .join(","); - createDebug.enable(""); - return namespaces; - } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - - function enabled(name) { - if (name[name.length - 1] === "*") { - return true; - } - - var i; - var len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - - function toNamespace(regexp) { - return regexp - .toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, "*"); - } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - - return val; - } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - - function destroy() { - console.warn( - "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." - ); - } - - createDebug.enable(createDebug.load()); - return createDebug; - } - - module.exports = setup; - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/globalThis.browser.js": - /*!*****************************************************************!*\ - !*** ./node_modules/engine.io-client/lib/globalThis.browser.js ***! - \*****************************************************************/ - /*! no static exports found */ - /***/ function (module, exports) { - module.exports = (function () { - if (typeof self !== "undefined") { - return self; - } else if (typeof window !== "undefined") { - return window; - } else { - return Function("return this")(); - } - })(); - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/index.js": - /*!****************************************************!*\ - !*** ./node_modules/engine.io-client/lib/index.js ***! - \****************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - var Socket = __webpack_require__( - /*! ./socket */ "./node_modules/engine.io-client/lib/socket.js" - ); - - module.exports = function (uri, opts) { - return new Socket(uri, opts); - }; - /** - * Expose deps for legacy compatibility - * and standalone browser access. - */ - - module.exports.Socket = Socket; - module.exports.protocol = Socket.protocol; // this is an int - - module.exports.Transport = __webpack_require__( - /*! ./transport */ "./node_modules/engine.io-client/lib/transport.js" - ); - module.exports.transports = __webpack_require__( - /*! ./transports/index */ "./node_modules/engine.io-client/lib/transports/index.js" - ); - module.exports.parser = __webpack_require__( - /*! engine.io-parser */ "./node_modules/engine.io-parser/lib/index.js" - ); - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/socket.js": - /*!*****************************************************!*\ - !*** ./node_modules/engine.io-client/lib/socket.js ***! - \*****************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - function _extends() { - _extends = - Object.assign || - function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); - } - - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function" - ); - } - subClass.prototype = Object.create( - superClass && superClass.prototype, - { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - } - ); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - - function _possibleConstructorReturn(self, call) { - if ( - call && - (_typeof(call) === "object" || typeof call === "function") - ) { - return call; - } - return _assertThisInitialized(self); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return self; - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) - ); - return true; - } catch (e) { - return false; - } - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - var transports = __webpack_require__( - /*! ./transports/index */ "./node_modules/engine.io-client/lib/transports/index.js" - ); - - var Emitter = __webpack_require__( - /*! component-emitter */ "./node_modules/component-emitter/index.js" - ); - - var debug = __webpack_require__( - /*! debug */ "./node_modules/debug/src/browser.js" - )("engine.io-client:socket"); - - var parser = __webpack_require__( - /*! engine.io-parser */ "./node_modules/engine.io-parser/lib/index.js" - ); - - var parseuri = __webpack_require__( - /*! parseuri */ "./node_modules/parseuri/index.js" - ); - - var parseqs = __webpack_require__( - /*! parseqs */ "./node_modules/parseqs/index.js" - ); - - var Socket = /*#__PURE__*/ (function (_Emitter) { - _inherits(Socket, _Emitter); - - var _super = _createSuper(Socket); - - /** - * Socket constructor. - * - * @param {String|Object} uri or options - * @param {Object} options - * @api public - */ - function Socket(uri) { - var _this; - - var opts = - arguments.length > 1 && arguments[1] !== undefined - ? arguments[1] - : {}; - - _classCallCheck(this, Socket); - - _this = _super.call(this); - - if (uri && "object" === _typeof(uri)) { - opts = uri; - uri = null; - } - - if (uri) { - uri = parseuri(uri); - opts.hostname = uri.host; - opts.secure = - uri.protocol === "https" || uri.protocol === "wss"; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parseuri(opts.host).host; - } - - _this.secure = - null != opts.secure - ? opts.secure - : typeof location !== "undefined" && - "https:" === location.protocol; - - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = _this.secure ? "443" : "80"; - } - - _this.hostname = - opts.hostname || - (typeof location !== "undefined" - ? location.hostname - : "localhost"); - _this.port = - opts.port || - (typeof location !== "undefined" && location.port - ? location.port - : _this.secure - ? 443 - : 80); - _this.transports = opts.transports || ["polling", "websocket"]; - _this.readyState = ""; - _this.writeBuffer = []; - _this.prevBufferLen = 0; - _this.opts = _extends( - { - path: "/engine.io", - agent: false, - withCredentials: false, - upgrade: true, - jsonp: true, - timestampParam: "t", - rememberUpgrade: false, - rejectUnauthorized: true, - perMessageDeflate: { - threshold: 1024, - }, - transportOptions: {}, - }, - opts - ); - _this.opts.path = _this.opts.path.replace(/\/$/, "") + "/"; - - if (typeof _this.opts.query === "string") { - _this.opts.query = parseqs.decode(_this.opts.query); - } // set on handshake - - _this.id = null; - _this.upgrades = null; - _this.pingInterval = null; - _this.pingTimeout = null; // set on heartbeat - - _this.pingTimeoutTimer = null; - - _this.open(); - - return _this; - } - /** - * Creates transport of the given type. - * - * @param {String} transport name - * @return {Transport} - * @api private - */ - - _createClass(Socket, [ - { - key: "createTransport", - value: function createTransport(name) { - debug('creating transport "%s"', name); - var query = clone(this.opts.query); // append engine.io protocol identifier - - query.EIO = parser.protocol; // transport name - - query.transport = name; // session id if we already have one - - if (this.id) query.sid = this.id; - - var opts = _extends( - {}, - this.opts.transportOptions[name], - this.opts, - { - query: query, - socket: this, - hostname: this.hostname, - secure: this.secure, - port: this.port, - } - ); - - debug("options: %j", opts); - return new transports[name](opts); - }, - /** - * Initializes transport to use and starts probe. - * - * @api private - */ - }, - { - key: "open", - value: function open() { - var transport; - - if ( - this.opts.rememberUpgrade && - Socket.priorWebsocketSuccess && - this.transports.indexOf("websocket") !== -1 - ) { - transport = "websocket"; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - var self = this; - setTimeout(function () { - self.emit("error", "No transports available"); - }, 0); - return; - } else { - transport = this.transports[0]; - } - - this.readyState = "opening"; // Retry with the next transport if the transport is disabled (jsonp: false) - - try { - transport = this.createTransport(transport); - } catch (e) { - debug("error while creating transport: %s", e); - this.transports.shift(); - this.open(); - return; - } - - transport.open(); - this.setTransport(transport); - }, - /** - * Sets the current transport. Disables the existing one (if any). - * - * @api private - */ - }, - { - key: "setTransport", - value: function setTransport(transport) { - debug("setting transport %s", transport.name); - var self = this; - - if (this.transport) { - debug( - "clearing existing transport %s", - this.transport.name - ); - this.transport.removeAllListeners(); - } // set up transport - - this.transport = transport; // set up transport listeners - - transport - .on("drain", function () { - self.onDrain(); - }) - .on("packet", function (packet) { - self.onPacket(packet); - }) - .on("error", function (e) { - self.onError(e); - }) - .on("close", function () { - self.onClose("transport close"); - }); - }, - /** - * Probes a transport. - * - * @param {String} transport name - * @api private - */ - }, - { - key: "probe", - value: function probe(name) { - debug('probing transport "%s"', name); - var transport = this.createTransport(name, { - probe: 1, - }); - var failed = false; - var self = this; - Socket.priorWebsocketSuccess = false; - - function onTransportOpen() { - if (self.onlyBinaryUpgrades) { - var upgradeLosesBinary = - !this.supportsBinary && self.transport.supportsBinary; - failed = failed || upgradeLosesBinary; - } - - if (failed) return; - debug('probe transport "%s" opened', name); - transport.send([ - { - type: "ping", - data: "probe", - }, - ]); - transport.once("packet", function (msg) { - if (failed) return; - - if ("pong" === msg.type && "probe" === msg.data) { - debug('probe transport "%s" pong', name); - self.upgrading = true; - self.emit("upgrading", transport); - if (!transport) return; - Socket.priorWebsocketSuccess = - "websocket" === transport.name; - debug( - 'pausing current transport "%s"', - self.transport.name - ); - self.transport.pause(function () { - if (failed) return; - if ("closed" === self.readyState) return; - debug( - "changing transport and sending upgrade packet" - ); - cleanup(); - self.setTransport(transport); - transport.send([ - { - type: "upgrade", - }, - ]); - self.emit("upgrade", transport); - transport = null; - self.upgrading = false; - self.flush(); - }); - } else { - debug('probe transport "%s" failed', name); - var err = new Error("probe error"); - err.transport = transport.name; - self.emit("upgradeError", err); - } - }); - } - - function freezeTransport() { - if (failed) return; // Any callback called by transport should be ignored since now - - failed = true; - cleanup(); - transport.close(); - transport = null; - } // Handle any error that happens while probing - - function onerror(err) { - var error = new Error("probe error: " + err); - error.transport = transport.name; - freezeTransport(); - debug( - 'probe transport "%s" failed because of error: %s', - name, - err - ); - self.emit("upgradeError", error); - } - - function onTransportClose() { - onerror("transport closed"); - } // When the socket is closed while we're probing - - function onclose() { - onerror("socket closed"); - } // When the socket is upgraded while we're probing - - function onupgrade(to) { - if (transport && to.name !== transport.name) { - debug( - '"%s" works - aborting "%s"', - to.name, - transport.name - ); - freezeTransport(); - } - } // Remove all listeners on the transport and on self - - function cleanup() { - transport.removeListener("open", onTransportOpen); - transport.removeListener("error", onerror); - transport.removeListener("close", onTransportClose); - self.removeListener("close", onclose); - self.removeListener("upgrading", onupgrade); - } - - transport.once("open", onTransportOpen); - transport.once("error", onerror); - transport.once("close", onTransportClose); - this.once("close", onclose); - this.once("upgrading", onupgrade); - transport.open(); - }, - /** - * Called when connection is deemed open. - * - * @api public - */ - }, - { - key: "onOpen", - value: function onOpen() { - debug("socket open"); - this.readyState = "open"; - Socket.priorWebsocketSuccess = - "websocket" === this.transport.name; - this.emit("open"); - this.flush(); // we check for `readyState` in case an `open` - // listener already closed the socket - - if ( - "open" === this.readyState && - this.opts.upgrade && - this.transport.pause - ) { - debug("starting upgrade probes"); - var i = 0; - var l = this.upgrades.length; - - for (; i < l; i++) { - this.probe(this.upgrades[i]); - } - } - }, - /** - * Handles a packet. - * - * @api private - */ - }, - { - key: "onPacket", - value: function onPacket(packet) { - if ( - "opening" === this.readyState || - "open" === this.readyState || - "closing" === this.readyState - ) { - debug( - 'socket receive: type "%s", data "%s"', - packet.type, - packet.data - ); - this.emit("packet", packet); // Socket is live - any packet counts - - this.emit("heartbeat"); - - switch (packet.type) { - case "open": - this.onHandshake(JSON.parse(packet.data)); - break; - - case "ping": - this.resetPingTimeout(); - this.sendPacket("pong"); - this.emit("pong"); - break; - - case "error": - var err = new Error("server error"); - err.code = packet.data; - this.onError(err); - break; - - case "message": - this.emit("data", packet.data); - this.emit("message", packet.data); - break; - } - } else { - debug( - 'packet received with socket readyState "%s"', - this.readyState - ); - } - }, - /** - * Called upon handshake completion. - * - * @param {Object} handshake obj - * @api private - */ - }, - { - key: "onHandshake", - value: function onHandshake(data) { - this.emit("handshake", data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.onOpen(); // In case open handler closes socket - - if ("closed" === this.readyState) return; - this.resetPingTimeout(); - }, - /** - * Sets and resets ping timeout timer based on server pings. - * - * @api private - */ - }, - { - key: "resetPingTimeout", - value: function resetPingTimeout() { - var _this2 = this; - - clearTimeout(this.pingTimeoutTimer); - this.pingTimeoutTimer = setTimeout(function () { - _this2.onClose("ping timeout"); - }, this.pingInterval + this.pingTimeout); - }, - /** - * Called on `drain` event - * - * @api private - */ - }, - { - key: "onDrain", - value: function onDrain() { - this.writeBuffer.splice(0, this.prevBufferLen); // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - - this.prevBufferLen = 0; - - if (0 === this.writeBuffer.length) { - this.emit("drain"); - } else { - this.flush(); - } - }, - /** - * Flush write buffers. - * - * @api private - */ - }, - { - key: "flush", - value: function flush() { - if ( - "closed" !== this.readyState && - this.transport.writable && - !this.upgrading && - this.writeBuffer.length - ) { - debug( - "flushing %d packets in socket", - this.writeBuffer.length - ); - this.transport.send(this.writeBuffer); // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - - this.prevBufferLen = this.writeBuffer.length; - this.emit("flush"); - } - }, - /** - * Sends a message. - * - * @param {String} message. - * @param {Function} callback function. - * @param {Object} options. - * @return {Socket} for chaining. - * @api public - */ - }, - { - key: "write", - value: function write(msg, options, fn) { - this.sendPacket("message", msg, options, fn); - return this; - }, - }, - { - key: "send", - value: function send(msg, options, fn) { - this.sendPacket("message", msg, options, fn); - return this; - }, - /** - * Sends a packet. - * - * @param {String} packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} callback function. - * @api private - */ - }, - { - key: "sendPacket", - value: function sendPacket(type, data, options, fn) { - if ("function" === typeof data) { - fn = data; - data = undefined; - } - - if ("function" === typeof options) { - fn = options; - options = null; - } - - if ( - "closing" === this.readyState || - "closed" === this.readyState - ) { - return; - } - - options = options || {}; - options.compress = false !== options.compress; - var packet = { - type: type, - data: data, - options: options, - }; - this.emit("packetCreate", packet); - this.writeBuffer.push(packet); - if (fn) this.once("flush", fn); - this.flush(); - }, - /** - * Closes the connection. - * - * @api private - */ - }, - { - key: "close", - value: function close() { - var self = this; - - if ( - "opening" === this.readyState || - "open" === this.readyState - ) { - this.readyState = "closing"; - - if (this.writeBuffer.length) { - this.once("drain", function () { - if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - } - - function close() { - self.onClose("forced close"); - debug("socket closing - telling transport to close"); - self.transport.close(); - } - - function cleanupAndClose() { - self.removeListener("upgrade", cleanupAndClose); - self.removeListener("upgradeError", cleanupAndClose); - close(); - } - - function waitForUpgrade() { - // wait for upgrade to finish since we can't send packets while pausing a transport - self.once("upgrade", cleanupAndClose); - self.once("upgradeError", cleanupAndClose); - } - - return this; - }, - /** - * Called upon transport error - * - * @api private - */ - }, - { - key: "onError", - value: function onError(err) { - debug("socket error %j", err); - Socket.priorWebsocketSuccess = false; - this.emit("error", err); - this.onClose("transport error", err); - }, - /** - * Called upon transport close. - * - * @api private - */ - }, - { - key: "onClose", - value: function onClose(reason, desc) { - if ( - "opening" === this.readyState || - "open" === this.readyState || - "closing" === this.readyState - ) { - debug('socket close with reason: "%s"', reason); - var self = this; // clear timers - - clearTimeout(this.pingIntervalTimer); - clearTimeout(this.pingTimeoutTimer); // stop event from firing again for transport - - this.transport.removeAllListeners("close"); // ensure transport won't stay open - - this.transport.close(); // ignore further transport communication - - this.transport.removeAllListeners(); // set ready state - - this.readyState = "closed"; // clear session id - - this.id = null; // emit close event - - this.emit("close", reason, desc); // clean buffers after, so users can still - // grab the buffers on `close` event - - self.writeBuffer = []; - self.prevBufferLen = 0; - } - }, - /** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} server upgrades - * @api private - * - */ - }, - { - key: "filterUpgrades", - value: function filterUpgrades(upgrades) { - var filteredUpgrades = []; - var i = 0; - var j = upgrades.length; - - for (; i < j; i++) { - if (~this.transports.indexOf(upgrades[i])) - filteredUpgrades.push(upgrades[i]); - } - - return filteredUpgrades; - }, - }, - ]); - - return Socket; - })(Emitter); - - Socket.priorWebsocketSuccess = false; - /** - * Protocol version. - * - * @api public - */ - - Socket.protocol = parser.protocol; // this is an int - - function clone(obj) { - var o = {}; - - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - o[i] = obj[i]; - } - } - - return o; - } - - module.exports = Socket; - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/transport.js": - /*!********************************************************!*\ - !*** ./node_modules/engine.io-client/lib/transport.js ***! - \********************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function" - ); - } - subClass.prototype = Object.create( - superClass && superClass.prototype, - { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - } - ); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - - function _possibleConstructorReturn(self, call) { - if ( - call && - (_typeof(call) === "object" || typeof call === "function") - ) { - return call; - } - return _assertThisInitialized(self); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return self; - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) - ); - return true; - } catch (e) { - return false; - } - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - var parser = __webpack_require__( - /*! engine.io-parser */ "./node_modules/engine.io-parser/lib/index.js" - ); - - var Emitter = __webpack_require__( - /*! component-emitter */ "./node_modules/component-emitter/index.js" - ); - - var Transport = /*#__PURE__*/ (function (_Emitter) { - _inherits(Transport, _Emitter); - - var _super = _createSuper(Transport); - - /** - * Transport abstract constructor. - * - * @param {Object} options. - * @api private - */ - function Transport(opts) { - var _this; - - _classCallCheck(this, Transport); - - _this = _super.call(this); - _this.opts = opts; - _this.query = opts.query; - _this.readyState = ""; - _this.socket = opts.socket; - return _this; - } - /** - * Emits an error. - * - * @param {String} str - * @return {Transport} for chaining - * @api public - */ - - _createClass(Transport, [ - { - key: "onError", - value: function onError(msg, desc) { - var err = new Error(msg); - err.type = "TransportError"; - err.description = desc; - this.emit("error", err); - return this; - }, - /** - * Opens the transport. - * - * @api public - */ - }, - { - key: "open", - value: function open() { - if ("closed" === this.readyState || "" === this.readyState) { - this.readyState = "opening"; - this.doOpen(); - } - - return this; - }, - /** - * Closes the transport. - * - * @api private - */ - }, - { - key: "close", - value: function close() { - if ( - "opening" === this.readyState || - "open" === this.readyState - ) { - this.doClose(); - this.onClose(); - } - - return this; - }, - /** - * Sends multiple packets. - * - * @param {Array} packets - * @api private - */ - }, - { - key: "send", - value: function send(packets) { - if ("open" === this.readyState) { - this.write(packets); - } else { - throw new Error("Transport not open"); - } - }, - /** - * Called upon open - * - * @api private - */ - }, - { - key: "onOpen", - value: function onOpen() { - this.readyState = "open"; - this.writable = true; - this.emit("open"); - }, - /** - * Called with data. - * - * @param {String} data - * @api private - */ - }, - { - key: "onData", - value: function onData(data) { - var packet = parser.decodePacket( - data, - this.socket.binaryType - ); - this.onPacket(packet); - }, - /** - * Called with a decoded packet. - */ - }, - { - key: "onPacket", - value: function onPacket(packet) { - this.emit("packet", packet); - }, - /** - * Called upon close. - * - * @api private - */ - }, - { - key: "onClose", - value: function onClose() { - this.readyState = "closed"; - this.emit("close"); - }, - }, - ]); - - return Transport; - })(Emitter); - - module.exports = Transport; - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/transports/index.js": - /*!***************************************************************!*\ - !*** ./node_modules/engine.io-client/lib/transports/index.js ***! - \***************************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - var XMLHttpRequest = __webpack_require__( - /*! xmlhttprequest-ssl */ "./node_modules/engine.io-client/lib/xmlhttprequest.js" - ); - - var XHR = __webpack_require__( - /*! ./polling-xhr */ "./node_modules/engine.io-client/lib/transports/polling-xhr.js" - ); - - var JSONP = __webpack_require__( - /*! ./polling-jsonp */ "./node_modules/engine.io-client/lib/transports/polling-jsonp.js" - ); - - var websocket = __webpack_require__( - /*! ./websocket */ "./node_modules/engine.io-client/lib/transports/websocket.js" - ); - - exports.polling = polling; - exports.websocket = websocket; - /** - * Polling transport polymorphic constructor. - * Decides on xhr vs jsonp based on feature detection. - * - * @api private - */ - - function polling(opts) { - var xhr; - var xd = false; - var xs = false; - var jsonp = false !== opts.jsonp; - - if (typeof location !== "undefined") { - var isSSL = "https:" === location.protocol; - var port = location.port; // some user agents have empty `location.port` - - if (!port) { - port = isSSL ? 443 : 80; - } - - xd = opts.hostname !== location.hostname || port !== opts.port; - xs = opts.secure !== isSSL; - } - - opts.xdomain = xd; - opts.xscheme = xs; - xhr = new XMLHttpRequest(opts); - - if ("open" in xhr && !opts.forceJSONP) { - return new XHR(opts); - } else { - if (!jsonp) throw new Error("JSONP disabled"); - return new JSONP(opts); - } - } - - /***/ - }, - - /***/ "./node_modules/engine.io-client/lib/transports/polling-jsonp.js": - /*!***********************************************************************!*\ - !*** ./node_modules/engine.io-client/lib/transports/polling-jsonp.js ***! - \***********************************************************************/ - /*! no static exports found */ - /***/ function (module, exports, __webpack_require__) { - function _typeof(obj) { - "@babel/helpers - typeof"; - if ( - typeof Symbol === "function" && - typeof Symbol.iterator === "symbol" - ) { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && - typeof Symbol === "function" && - obj.constructor === Symbol && - obj !== Symbol.prototype - ? "symbol" - : typeof obj; - }; - } - return _typeof(obj); - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) - _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get; - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - if (desc.get) { - return desc.get.call(receiver); - } - return desc.value; - }; - } - return _get(target, property, receiver || target); - } - - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - return object; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError( - "Super expression must either be null or a function" - ); - } - subClass.prototype = Object.create( - superClass && superClass.prototype, - { - constructor: { - value: subClass, - writable: true, - configurable: true, - }, - } - ); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = - Object.setPrototypeOf || - function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - - function _possibleConstructorReturn(self, call) { - if ( - call && - (_typeof(call) === "object" || typeof call === "function") - ) { - return call; - } - return _assertThisInitialized(self); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError( - "this hasn't been initialised - super() hasn't been called" - ); - } - return self; - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) - return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Date.prototype.toString.call( - Reflect.construct(Date, [], function () {}) - ); - return true; - } catch (e) { - return false; - } - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf - ? Object.getPrototypeOf - : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - var Polling = __webpack_require__( - /*! ./polling */ "./node_modules/engine.io-client/lib/transports/polling.js" - ); - - var globalThis = __webpack_require__( - /*! ../globalThis */ "./node_modules/engine.io-client/lib/globalThis.browser.js" - ); - - var rNewline = /\n/g; - var rEscapedNewline = /\\n/g; - /** - * Global JSONP callbacks. - */ - - var callbacks; - /** - * Noop. - */ - - function empty() {} - - var JSONPPolling = /*#__PURE__*/ (function (_Polling) { - _inherits(JSONPPolling, _Polling); - - var _super = _createSuper(JSONPPolling); - - /** - * JSONP Polling constructor. - * - * @param {Object} opts. - * @api public - */ - function JSONPPolling(opts) { - var _this; - - _classCallCheck(this, JSONPPolling); - - _this = _super.call(this, opts); - _this.query = _this.query || {}; // define global callbacks array if not present - // we do this here (lazily) to avoid unneeded global pollution - - if (!callbacks) { - // we need to consider multiple engines in the same page - callbacks = globalThis.___eio = globalThis.___eio || []; - } // callback identifier - - _this.index = callbacks.length; // add callback to jsonp global - - var self = _assertThisInitialized(_this); - - callbacks.push(function (msg) { - self.onData(msg); - }); // append to query string - - _this.query.j = _this.index; // prevent spurious errors from being emitted when the window is unloaded - - if (typeof addEventListener === "function") { - addEventListener( - "beforeunload", - function () { - if (self.script) self.script.onerror = empty; - }, - false - ); - } - - return _this; - } - /** - * JSONP only supports binary as base64 encoded strings - */ - - _createClass(JSONPPolling, [ - { - key: "doClose", - - /** - * Closes the socket. - * - * @api private - */ - value: function doClose() { - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; - } - - if (this.form) { - this.form.parentNode.removeChild(this.form); - this.form = null; - this.iframe = null; - } - - _get( - _getPrototypeOf(JSONPPolling.prototype), - "doClose", - this - ).call(this); - }, - /** - * Starts a poll cycle. - * - * @api private - */ - }, - { - key: "doPoll", - value: function doPoll() { - var self = this; - var script = document.createElement("script"); - - if (this.script) { - this.script.parentNode.removeChild(this.script); - this.script = null; - } - - script.async = true; - script.src = this.uri(); - - script.onerror = function (e) { - self.onError("jsonp poll error", e); - }; - - var insertAt = document.getElementsByTagName("script")[0]; - - if (insertAt) { - insertAt.parentNode.insertBefore(script, insertAt); - } else { - (document.head || document.body).appendChild(script); - } - - this.script = script; - var isUAgecko = - "undefined" !== typeof navigator && - /gecko/i.test(navigator.userAgent); - - if (isUAgecko) { - setTimeout(function () { - var iframe = document.createElement("iframe"); - document.body.appendChild(iframe); - document.body.removeChild(iframe); - }, 100); - } - }, - /** - * Writes with a hidden iframe. - * - * @param {String} data to send - * @param {Function} called upon flush. - * @api private - */ - }, - { - key: "doWrite", - value: function doWrite(data, fn) { - var self = this; - var iframe; - - if (!this.form) { - var form = document.createElement("form"); - var area = document.createElement("textarea"); - var id = (this.iframeId = "eio_iframe_" + this.index); - form.className = "socketio"; - form.style.position = "absolute"; - form.style.top = "-1000px"; - form.style.left = "-1000px"; - form.target = id; - form.method = "POST"; - form.setAttribute("accept-charset", "utf-8"); - area.name = "d"; - form.appendChild(area); - document.body.appendChild(form); - this.form = form; - this.area = area; - } - - this.form.action = this.uri(); - - function complete() { - initIframe(); - fn(); - } - - function initIframe() { - if (self.iframe) { - try { - self.form.removeChild(self.iframe); - } catch (e) { - self.onError("jsonp polling iframe removal error", e); - } - } - - try { - // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) - var html = - '