From 5b620e279fb4e52e18d1b8c003cacc036f4ffcc7 Mon Sep 17 00:00:00 2001 From: icon Date: Tue, 30 Aug 2022 06:34:34 +0400 Subject: [PATCH] premier commit --- autostart | 22 + node.yml | 47 + readme.md | 80 + serveurNfcNodeJsVma405/chromium_env.exemple | 16 + serveurNfcNodeJsVma405/package.json | 18 + serveurNfcNodeJsVma405/serveur_nfc.js | 659 ++ serveurNfcNodeJsVma405/vma405.js | 65 + .../www/css/clavier_virtuel.css | 43 + serveurNfcNodeJsVma405/www/css/index.css | 280 + serveurNfcNodeJsVma405/www/index.html | 39 + .../www/js/clavier_virtuel.js | 379 + serveurNfcNodeJsVma405/www/js/index.js | 234 + serveurNfcNodeJsVma405/www/js/socket.io.js | 7417 +++++++++++++++++ splash.png | Bin 0 -> 115094 bytes vma405.jpg | Bin 0 -> 606598 bytes vma405.js | 65 + 16 files changed, 9364 insertions(+) create mode 100755 autostart create mode 100755 node.yml create mode 100755 readme.md create mode 100644 serveurNfcNodeJsVma405/chromium_env.exemple create mode 100755 serveurNfcNodeJsVma405/package.json create mode 100755 serveurNfcNodeJsVma405/serveur_nfc.js create mode 100755 serveurNfcNodeJsVma405/vma405.js create mode 100755 serveurNfcNodeJsVma405/www/css/clavier_virtuel.css create mode 100755 serveurNfcNodeJsVma405/www/css/index.css create mode 100755 serveurNfcNodeJsVma405/www/index.html create mode 100755 serveurNfcNodeJsVma405/www/js/clavier_virtuel.js create mode 100755 serveurNfcNodeJsVma405/www/js/index.js create mode 100755 serveurNfcNodeJsVma405/www/js/socket.io.js create mode 100755 splash.png create mode 100755 vma405.jpg create mode 100755 vma405.js diff --git a/autostart b/autostart new file mode 100755 index 0000000..1672291 --- /dev/null +++ b/autostart @@ -0,0 +1,22 @@ +#/etc/xdg/openbox/ +DISPLAY=:0 xdotool getactivewindow key F5 + +# stop veille/économie dénergie +xset dpms 0 0 0 && xset s noblank && xset s off + +#Touches pour sortir du serveur X => CTRL-ATL-Backspace +setxkbmap -option terminate:ctrl_alt_bksp + +sed -i 's/"exited_cleanly":false/"exited_cleanly":true/' ~/.config/chromium/Default/Preferences +sed -i 's/"exit_type":"Crashed"/"exit_type":"Normal"/' ~/.config/chromium/Default/Preferences + +# vidage du cache chromium +rm -fr /home/sysop/.cache/chromium +rm -fr /home/sysop/.config/chromium/Default/ + +# orientation de l'écran +xrandr --output DSI-1 --rotate right + +# lance chromium avec un user agent spécifique hostname,password,periph,ip (provenant en partie de .chromium_env) +cd /home/sysop/serveurNfcNodeJs/ +node serveur_nfc.js diff --git a/node.yml b/node.yml new file mode 100755 index 0000000..b6351cd --- /dev/null +++ b/node.yml @@ -0,0 +1,47 @@ +--- +- hosts: testDsiPi + remote_user: sysop + become: yes + tasks: + + - name: install "splash screen" + apt: + name: rpd-plym-splash + state: present + + - name: Active SPI + shell: + cmd: echo "dtparam=spi=on" >> /boot/config.txt + + - name: Ajout du dépot nodes js + shell: curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - + + - name: install "nodejs" + apt: + name: nodejs + state: present + + - name: Pour nodejs, installation de "gcc" pour la compilation + apt: + name: gcc + state: present + + - name: Pour nodejs, installation de "g++" pour la compilation + apt: + name: g++ + state: present + + - name: Pour nodejs, installation de "make" pour la compilation + apt: + name: make + state: present + + - name: Pour nodejs, installation de "apt-transport-https" pour la compilation + apt: + name: apt-transport-https + state: present + + - name: Installation des modules node js + shell: + cmd: npm i + chdir: /home/sysop/nodeJsVma405/ diff --git a/readme.md b/readme.md new file mode 100755 index 0000000..6c72ab5 --- /dev/null +++ b/readme.md @@ -0,0 +1,80 @@ +# VMA 405 +côté usb, | 39 | 37 | 35 | 33 | 31 | 29 | 27 | 25 | 23 | 21 | 19 | 17 | 15 | 13 | 11 | 9 | 7 | 5 | 3 | 1 | côté sdcar +reseau | 40 | 38 | 36 | 34 | 32 | 30 | 28 | 26 | 24 | 22 | 20 | 18 | 16 | 14 | 12 | 10 | 8 | 6 | 4 | 2 | + + + | 39 | 37 | 35 | 33 | 31 | 29 | 27 | 25 | SCK|MISO|MOSI| 17 | 15 | 13 | 11 | GND| 7 | 5 | 3 | vcc| + | 40 | 38 | 36 | 34 | 32 | 30 | 28 | 26 | NSS| RST| 20 | 18 | 16 | 14 | 12 | 10 | 8 | 6 | 4 | 2 | + + +|VMA405 |PI 3 B+ | | +|VCC | 1 | marron | +|RST 22 rouge +GND 9 orange +MISO 21 jaune +MOSI 19 vert +SCK 23 bleu +NSS 24 violet +IRQ pas utilisé + + +# splash screen +``` +sudo cp splash.png /usr/share/plymouth/themes/pix/splash.png +sudo cp splash.png /usr/share/plymouth/themes/pix/splash.png +``` + +- sudo nano /boot/config.txt +disable splash=1 + +- sudo nano /boot/cmdline.txt +consoleblank=0 loglevel=1 quiet logo.nologo + + +-Pour afficher l'image +sudo apt install fbi + +- Créer un service +sudo nano /etc/systemd/system/splashscreen.service +``` +[Unit] +Description=Splash screen +DefaultDependencies=no +After=local-fs.target +[Service] +ExecStart=/usr/bin/fbi -d /dev/fb0 --noverbose -a /home/sysop/splash.png +StandardInput=tty +StandardOutput=tty +[Install] +WantedBy=sysinit.target +``` +- active le service +sudo systemctl enable splashscreen.service +sudo systemctl start splashscreen.service + +# /ext/xdg/openbox/autostart +``` +#/etc/xdg/openbox/ +DISPLAY=:0 xdotool getactivewindow key F5 + +# stop veille/économie dénergie +xset dpms 0 0 0 && xset s noblank && xset s off + +#Touches pour sortir du serveur X => CTRL-ATL-Backspace +setxkbmap -option terminate:ctrl_alt_bksp + +sed -i 's/"exited_cleanly":false/"exited_cleanly":true/' ~/.config/chromium/Default/Preferences +sed -i 's/"exit_type":"Crashed"/"exit_type":"Normal"/' ~/.config/chromium/Default/Preferences + +# vidage du cache chromium +rm -fr /home/sysop/.cache/chromium +rm -fr /home/sysop/.config/chromium/Default/ + +# orientation de l'écran +xrandr --output DSI-1 --rotate right + +# lance chromium avec un user agent spécifique hostname,password,periph,ip (provenant en partie de .chromium_env) +cd /home/sysop/serveurNfcNodeJs/ +node serveur_nfc.js + +``` diff --git a/serveurNfcNodeJsVma405/chromium_env.exemple b/serveurNfcNodeJsVma405/chromium_env.exemple new file mode 100644 index 0000000..2acded4 --- /dev/null +++ b/serveurNfcNodeJsVma405/chromium_env.exemple @@ -0,0 +1,16 @@ +#cp chromium_env.exemple .chromium_env + +#utilisateur +hostname = testDsiPi + +#front +front_type = FPI + +#url du serveur +url = https://django-local.org:8501/wv/login_hardware + +#mode_nfc = NFCMO +mode_nfc = NFCLO + +password = xxxxxxxxxxxxxxxxxxxxx +token = xxxxxxxxxxxxxxxxxx diff --git a/serveurNfcNodeJsVma405/package.json b/serveurNfcNodeJsVma405/package.json new file mode 100755 index 0000000..6d4cbf3 --- /dev/null +++ b/serveurNfcNodeJsVma405/package.json @@ -0,0 +1,18 @@ +{ + "name": "nfc", + "version": "1.5.0", + "description": "", + "main": "serveur_nfc.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "filaos974", + "license": "ISC", + "dependencies": { + "ip": "^1.1.5", + "socket.io": "^3.0.4", + "mfrc522-rpi": "^2.1.3", + "rpi-softspi": "^1.0.5", + "rpio": "^2.4.2" + } +} diff --git a/serveurNfcNodeJsVma405/serveur_nfc.js b/serveurNfcNodeJsVma405/serveur_nfc.js new file mode 100755 index 0000000..4c68f28 --- /dev/null +++ b/serveurNfcNodeJsVma405/serveur_nfc.js @@ -0,0 +1,659 @@ +// pour "configurer" le lecteur nfc +// ouvrir le fichier: sudo nano /usr/lib/pcsc/drivers/ifd-ccid.bundle/Contents/Info.plist (pour pi) +// localiser la ligne ifdDriverOptions, +// la ligne suivante vaux 0x0000, +// modifier la 0x0001, +// sauvegarder le fichier et redémarer pcscd(sudo service pcscd restart) +// même action pour le fichier sudo nano /usr/lib/pcsc/drivers/ifd-acsccid.bundle/Contents/Info.plist (pour desktop) + +let script, ip, memSudoMdp = '', etatUrl = 0 +let TAB = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '!', '#', '$', '%', '&', '?','0','1','2','3','4','5','6','7','8','9']; +let max_TAB = TAB.length - 1 +let donneesFichierConfiguration = {} +// type de lecteur nfc +const typeLecteurNfc = 'vma405' +// dev = 1 = mode développement +let dev = 1 + +// nfc +const vma405Emitter = require('./vma405.js') + +const os = require('os') +const hostname= os.hostname() + +const { spawn, exec } = require('child_process') +const IP = require('ip') +const path = require('path') +const fs = require('fs') +// serveur http +const http = require('http') +// const ADR = '192.168.1.32' +const ADR = '127.0.0.1' +const PORT = 3000 +const TOKEN = '$a;b2yuM5454@4!cd' +// retour = null = aucune demande de lecture de carte nfc +let retour = null +let client_globale = null +let fichier = '', contentType = '' + +/** + * retourne l'ip + * @param {string|'public'|'private'} typeReseau + * @param {String|'ipv4'|'ipv6'} famille + * @returns {string} + */ +function obtenirIp(typeReseau, famille){ + ip = IP.address(typeReseau, famille) + let retour = "erreur" + if (ip !== "127.0.0.1" && ip !== "0.0.0.0") { + retour = ip + } + return retour +} + +// --- nfc --- +vma405Emitter.on('tagId', (tagId) => { + if (retour !== null){ + retour['tagId'] = tagId.toUpperCase() + client_globale.emit('envoieTagId',retour) + console.log('--> demande carte, envoi tag id = ' + tagId.toUpperCase()) + retour = null + } else { + // console.log('-> Aucune demande, carte :' + card.uid.toString().toUpperCase()) + console.log('-> Aucune demande, carte :' + tagId.toUpperCase()) + if (client_globale !== null) { + client_globale.emit('infosTagId', tagId.toUpperCase()) + } + } +}) + +vma405Emitter.on('msgVma405', (msg) => { + console.log('msgVma405 =', msg) +}) + + + +// --- commandes système --- +/** @function + * Obtenir ip extérieur (wan/box) + */ +function obtenirIpWan() { + const prog = spawn('curl', ['ifconfig.me']) + prog.stdout.on('data', (data) => { + prog.resultatRequete = data.toString() + }) + + prog.on('close', (code) => { + if (code === 0 ){ + // ok: ip = prog.resultatRequete + } else { + // erreur + } + }) +} + +/** + * Obtenir des données de configuration d'un fichier (.chromium_env) + * @param {Array} rechercher - liste des varaibles à rechercher ddans le fichier + * @param {String} fichier - nom du fichier à lire + * @returns {{msg, erreur: number}|{valeurs: {}, erreur: number}} + */ +function obtenirConfigurationDunFichier(rechercher,fichier) { + try { + const fic = fs.readFileSync(fichier, {encoding:'utf8', flag:'r'}).split('\n') + let obj = {} + for (let index = 0; index < fic.length; index++) { + let ligne = fic[index].toString() + if (ligne.length > 0 && ligne[0] !== '#' && ligne.indexOf('=') !== -1) { + let tab = ligne.split('=') + for ( let im in rechercher) { + mot = rechercher[im] + if (mot === (tab[0].trim())) { + obj[tab[0].trim()] = tab[1].trim() + } + } + } + } + return {erreur: 0, valeurs: obj} + } catch (error) { + return {erreur:1 , msg: error} + } +} + +function afficherInfoServeur(donnees){ + // console.log('-> fonction afficherInfoServeur !') + // console.log('donnees = ', donnees) + if (donnees.erreur === 0) { + let bruteUrl = donnees.valeurs.url + let posDeuxSlashs = bruteUrl.indexOf('//') + 2 + let posFinDomaine = bruteUrl.indexOf('/wv/login_hardware') + let domaine = bruteUrl.substring(posDeuxSlashs,posFinDomaine) + let onclique = '' + if (donnees.valeurs.front_type === "FPI") { + onclique = `onclick="clavierVirtuel.obtPosition('serveur');clavierVirtuel.afficher('serveur', 'alpahMin')"` + } + let fronts = ['FPI', 'FOR'] + let options = '' + for (let i = 0; i < fronts.length; i++) { + let sel = '' + console.log(`${ i} -> ${ fronts[i] } -- ${ donnees.valeurs.front_type }`) + if (fronts[i] === donnees.valeurs.front_type) { + sel = 'selected' + } + options += `` + } + return ` +
Serveur: ${ domaine }
+ +
+
+
Tester Serveur
+
+
+ +
+
+
Modifier Serveur
+
+
+
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
Valider
+
+
+ ` + } else { + return ` +
Erreur
+
donnees.msg
+ ` + } +} + +/** @function + * Teste l'url avec curl + * @param {Sring} url - url à tester + * @param {Number} nbMaxStderr - nombre maxi d'évènement Stderr avant de sortir de la fonction + */ +function testUrl(url, nbMaxStderr) { + console.log(`-> fonction testUrl, url = ->${ url }<-`) + const prog = spawn('curl', ['-I', url]) + prog.nbMaxStderr = nbMaxStderr + prog.nbStderr = 0 + prog.resultatRequete = "404" + etatUrl = 0 + prog.stdout.on('data', (data) => { + let premiereLigne = data.toString().split('\n')[0] + prog.resultatRequete = premiereLigne.split(' ')[1] + }) + + prog.stderr.on('data', (data) => { + prog.nbStderr ++ + if(prog.nbStderr === prog.nbMaxStderr) { + prog.kill() + } + }) + + prog.on('close', (code) => { + // header 307 = redirection temporaire + // header 308 = redirection permanente + console.log('réponse test serveur = ', prog.resultatRequete) + if(prog.resultatRequete === '200' || prog.resultatRequete === '307' || prog.resultatRequete === '308') { + etatUrl = 1 + } + client_globale.emit('etatUrlServeur', prog.resultatRequete) + }) +} + + +function modifierConfigurationWifi(data) { + console.log('-> fonction modifierConfigurationWifi !') + console.log('data = ', data) + let template = `country=FR +ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev +update_config=1 +network={ + ssid="${ data.essid }" + psk="${ data.passePhrase }" + scan_ssid=1 +} +` + try { + fs.writeFileSync("/etc/wpa_supplicant/wpa_supplicant.conf", template, {flag: "w"}) + client_globale.emit('modificationWifi', { + erreur: 0, + msg: ` +
+

Modification wifi effectuée,

+

réseau = ${ data.essid }

+

Redémmarer l'appareil !

+
+ ` + }) + } catch (erreur) { + client_globale.emit('modificationWifi', { + erreur: 1, + msg: ` +

Erreur configuration wifi

+

${ erreur }

+ ` + }) + } +} + +function afficherInfosWifi() { + // console.log('-> fonction afficherInfosWifi !') + const prog = spawn('iwconfig', []) + prog.stdout.on('data', (data) => { + let lignes = data.toString().split('\n') + for (let i = 0; i < lignes.length; i++) { + let ligne = lignes[i] + if (ligne.indexOf('ESSID') !== -1) { + let tmpData = ligne.split(':') + let etatWifi = 'on' + let essid = '' + if (tmpData[1].includes('off')){ + etatWifi = 'off' + } else { + essid = tmpData[1].trim().replace(/"/g, '') + } + let tmpData2 = ligne.split(' ') + prog.resultat = {interface: tmpData2[0], etat: etatWifi, essid: essid} + break + } + } + }) + + prog.on('close', (code) => { + if (code === 0) { + // wifi actif + // if (prog.resultat.etat === 'on' && donneesFichierConfiguration.erreur === 0) { + // uniquement sur pi + if (donneesFichierConfiguration.valeurs.front_type === "FPI") { + let onclique = '' + // if (donneesFichierConfiguration.valeurs.front_type === "FPI") { + oncliqueEssid = `onclick="clavierVirtuel.obtPosition('essid');clavierVirtuel.afficher('essid', 'alpahMin')"` + oncliquePasse = `onclick="clavierVirtuel.obtPosition('pp');clavierVirtuel.afficher('pp', 'alpahMin')"` + // } + + let fragHtml = ` +
Ssid: ${ prog.resultat.essid }
+
+
+
Modifier Wifi
+
+
+
+
+
+ + +
+
+ + +
+
+
Valider
+
+
+ ` + client_globale.emit('retourInfosWifi', fragHtml) + } + // } + } + }) +} + +/** + * Lancer chromium + * @param {Number|1|2} - etape + */ +function lancerChromium(etape, dataFichier) { + console.log('-> fonction lancerChromium !') + + let optionsChromium = [], msgErreur = '' + console.log('dataFichier = ', dataFichier) + if (dataFichier.erreur === 0) { + data = dataFichier.valeurs + } else { + msgErreur = dataFichier.msg + } + + if (msgErreur === '') { + if (etape === 1) { + // dev + if (dev === 1) { + optionsChromium = ['--disable-features=Translate', '--disable-pinch', '--remote-debugging-port=9222', '--noerrdialogs', '--disable-infobars', '--check-for-update-interval=31536000', 'http://127.0.0.1:3000'] + } else { + // prod + optionsChromium = ['--disable-features=Translate', '--disable-pinch', '--noerrdialogs', '--disable-infobars', '--check-for-update-interval=31536000', 'http://127.0.0.1:3000'] + } + } else { + // dev + console.log('-> etape 2, url = ', data.url) + if (dev === 1) { + optionsChromium = ['--disable-features=Translate', '--disable-pinch', '--remote-debugging-port=9222', '--noerrdialogs', '--disable-infobars', '--check-for-update-interval=31536000', data.url] + } else { + // prod + optionsChromium = ['--disable-features=Translate', '--disable-pinch', '--noerrdialogs', '--disable-infobars', '--check-for-update-interval=31536000', data.url] + } + + } + + // mode kiosk uniquement pi + if (data.front_type === "FPI") { + optionsChromium.push('--kiosk') + } + + if (msgErreur === '') { + const userAgent = `{"hostname":"${data.hostname}", "token": "${data.token}", "password":"${data.password}","modeNfc":"${data.mode_nfc}","front":"${data.front_type}","ip":"${obtenirIp('public', 'ipv4')}"}` + console.log('userAgent = ', userAgent) + + optionsChromium.push(`--user-agent=${userAgent}`) + console.log('optionsChromium = ', optionsChromium) + + // Lance chromium + const demChromium = spawn('chromium-browser', optionsChromium) + + demChromium.stdout.on('data', (data) => { + console.log(`demChromium - stdout: ${data}`) + }); + + demChromium.stderr.on('data', (data) => { + console.error(`demChromium - stderr: ${data}`) + }) + + demChromium.on('close', (code) => { + console.log(`demChromium - child process exited with code ${code}`) + if (code === 0) { + console.log('--> Chromium démarrer !') + } + }) + } + } else { + console.log('Erreur: ', msgErreur) + } +} + +function lancerApplication(){ + console.log('-> fonction lancerApplication !') + const dataConf = obtenirConfigurationDunFichier(['hostname', 'token', 'password', 'front_type', 'url', 'mode_nfc'], './.chromium_env') + if (dataConf.erreur === 0) { + let prog + if (dataConf.valeurs.front_type === "FPI") { + prog = spawn('pkill', ['chromium']) + } else { + prog = spawn('pkill', ['chrome']) + } + + prog.stdout.on('data', (data) => { + console.log('stdout: ', data.toString()) + }) + + prog.stderr.on('data', (data) => { + console.log('stderr: ', data.toString()) + }) + + prog.on('close', (code) => { + if (code === 0) { + console.log('--> Chromium arrêter !') + const dataFichier = obtenirConfigurationDunFichier(['hostname', 'token', 'password', 'front_type', 'url', 'mode_nfc'], './.chromium_env') + lancerChromium(2, dataFichier) + } + }) + } else { + console.log('Erreur: ', dataConf.msg) + } +} + +function afficherFrontType() { + console.log('-> fonction afficherFrontType !') + console.log('donneesFichierConfiguration = ', donneesFichierConfiguration) + if (donneesFichierConfiguration.erreur === 0) { + return donneesFichierConfiguration.valeurs.front_type + } else { + return 'inconnu' + } +} +function rnd(min, max) { + return Math.round(Math.random() * ((max+1) - min) + min,0); +} + +function generer_mot_de_passe(longueur) { + let mot = ''; + let lettre = TAB[rnd(0,max_TAB)]; + for(let i=0;i<(longueur);i++){ + + while (mot.indexOf(lettre)!=-1) { + lettre = TAB[rnd(0,59)]; + } + mot += lettre; + } + return mot +} + +function modifierConfigurationServeur(data) { + // console.log('-> fonction modifierConfigurationServeur !') + let proto = 'https' + // Développement serveur = "#serveur.com#", donne un protocol http et serveur = "serveur.com" + let serveur = data.serveurDomaine.toString() + // console.log('0 = ',serveur[0], ' -- dernier = ',serveur[(serveur.length-1)]) + if (serveur[0] === '#' && serveur[(serveur.length-1)] === '#') { + proto = 'http' + serveur = data.serveurDomaine.toString().substring(1,(serveur.length-1)) + } + + donnees = obtenirConfigurationDunFichier(['hostname', 'token', 'password', 'front_type', 'url', 'mode_nfc'], './.chromium_env') + if (donnees.erreur === 0) { + let motDePasse = generer_mot_de_passe(16) + if (data.genererMotDePasse === false) { + motDePasse = donnees.valeurs.password + } + + let template = `#utilisateur +hostname = ${data.user} + +#front +front_type = ${data.typeFront} + +#url du serveur +#url = http://django-local.org:8001/wv/login_hardware +url = ${proto}://${serveur}/wv/login_hardware + +#mode_nfc = NFCMO +mode_nfc = ${ donnees.valeurs.mode_nfc } + +password = ${ motDePasse } +token = ${ donnees.valeurs.token } +` + try { + fs.writeFileSync(".chromium_env", template) + client_globale.emit('modificationServeur', {erreur: 0, serveurDomaine: serveur}) + testUrl(serveur, 14) + redemarrerChromium() + } catch (error) { + client_globale.emit('modificationServeur', {erreur: 1}) + } + } else { + client_globale.emit('modificationServeur', {erreur: 1}) + } +} + +// --- serveur http --- +let typeMime = { + "aac":"audio/aac","abw":"application/x-abiword","arc":"application/octet-stream","avi":"video/x-msvideo","azw":"application/vnd.amazon.ebook", + "bin":"application/octet-stream","bz":"application/x-bzip","bz2":"application/x-bzip2","csh":"application/x-csh","css":"text/css","csv":"text/csv", + "doc":"application/msword","docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document","eot":"application/vnd.ms-fontobject", + "epub":"application/epub+zip","gif":"image/gif","htm":"text/html","html":"text/html","ico":"image/x-icon","ics":"text/calendar","jar":"application/java-archive", + "jpeg":"image/jpeg","jpeg":"image/jpeg","js":"application/javascript","json":"application/json","mid":"audio/midi","midi":"audio/midi","mpeg":"video/mpeg", + "mpkg":"application/vnd.apple.installer+xml","odp":"application/vnd.oasis.opendocument.presentation","ods":"application/vnd.oasis.opendocument.spreadsheet", + "odt":"application/vnd.oasis.opendocument.text","oga":"audio/ogg","ogv":"video/ogg","ogx":"application/ogg","otf":"font/otf","png":"image/png","pdf":"application/pdf", + "ppt":"application/vnd.ms-powerpoint","pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation","rar":"application/x-rar-compressed", + "rtf":"application/rtf","sh":"application/x-sh","svg":"image/svg+xml","swf":"application/x-shockwave-flash","tar":"application/x-tar","tif":"image/tiff", + "tiff":"image/tiff","ts":"application/typescript","ttf":"font/ttf","vsd":"application/vnd.visio","wav":"audio/x-wav","weba":"audio/webm","webm":"video/webm", + "webp":"image/webp","woff":"font/woff","woff2":"font/woff2","xhtml":"application/xhtml+xml","xls":"application/vnd.ms-excel", + "xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","xml":"application/xml","xul":"application/vnd.mozilla.xul+xml","zip":"application/zip", + "3gp":"video/3gpp audio/3gpp","3g2":"video/3gpp2 audio/3gpp2", + "7z":"application/x-7z-compressed" +} + +let www = process.cwd() + '/www/' +console.log('www = ', www) + +function retour404(res){ + res.writeHead(404, {'Content-Type': 'text/html'}); + res.write('Page inconnue !'); + res.end(); +} + +function renderHtml(contenu, ctx) { + // let contenuTp1, contenuTp2, contenuTp3, contenuTp4 + contenu = contenu.toString() + let rendu = contenu.toString().replace(/{{\s*[\w\.]+\s*}}/g, function(match, token) { + let clef = match.replace(/ /g,'').replace('{{','').replace('}}','') + console.log('-> match = ', match, ' -- clef = ', clef) + return ctx[clef] + }) + contenu = {} + return rendu +} + +// lire la conf. dans le fichier .chromium_env +donneesFichierConfiguration = obtenirConfigurationDunFichier(['hostname', 'token', 'password', 'front_type', 'url', 'mode_nfc'], './.chromium_env') + +const serveur = http.createServer(function(req, res){ + let url = req.url; + + // routes + let ctx = {} + if(url=='/') { + url = 'index.html' + ctx = { + fontType: afficherFrontType(), + nomAppareil: os.hostname(), + afficherInfoServeur: afficherInfoServeur(donneesFichierConfiguration), + urlServeur: donneesFichierConfiguration.url, + ip: obtenirIp('public','ipv4'), + typeLecteurNfc: typeLecteurNfc, + typeserveurNfc: 'nodejs' + } + } + + if(url=='/favicon.ico') url = 'img/favicon2.ico' + + fichier = www + url.substring(0,url.length); + + //assets + let posDerPoint = url.lastIndexOf('.') + let extention = '' + if(posDerPoint != -1){ + extention = url.substring(posDerPoint+1,url.length); + if(extention.toLowerCase() == 'css') contentType = 'text/css'; + contentType = typeMime[extention.toLowerCase()]; + } + + try { + let contenuFichier = fs.readFileSync(fichier) + + // rendre du html + if (extention === 'html') { + contenuFichier = renderHtml(contenuFichier, ctx) + } + + res.writeHead(200, {"Content-Type": contentType}) + res.write(contenuFichier) + res.end(); + console.log('-> url = '+url+' -- fichier :'+fichier+' -- contentType = '+contentType+' -> chargé !'); + } catch (err) { + console.log('-> url = ' + url + ' -- Erreur: ' + err) + retour404(res); + } + +}) + +// --- socket.io --- +const options = { + // allowEIO3: true, + cors: { + origin: "*", + methods: ["PUT", "GET", "POST"] + } +} +const IO = require('socket.io')(serveur,options) +// middleware + +IO.use(function(socket, next){ + let token = socket.handshake.query.token + // console.log('token reçu = '+token+' -- TOKEN = '+TOKEN) + if (token === TOKEN){ + return next() + } else { + next(new Error("ERREUR d'autentification !")) + } +}) + +IO.on('connection', client => { + client_globale = client; + client_globale.on('demandeTagId', (data) => { + retour = data; + console.log('-> demandeTagIdg = '+JSON.stringify(retour)) + }) + + client_globale.on('AnnuleDemandeTagId', () => { + retour = null + }) + + client_globale.on('disconnect', () => { + console.log('Client déconnecté !!') + }) + + client_globale.on('validerModifierWifi', (data) => { + modifierConfigurationWifi(data) + }) + + client_globale.on('validerModifierServeur', (data) => { + modifierConfigurationServeur(data) + }) + + + client_globale.on('testerUrlServeur', (urlATester) => { + console.log('-> test url serveur = ',urlATester) + testUrl(urlATester, 12) + }) + + client_globale.on('donnerInfosWifi', () => { + afficherInfosWifi() + }) + + client_globale.on('lancerApplication', () => { + lancerApplication() + }) + +}) + +// lancement serveur http +serveur.listen(PORT, ADR, () => { + console.log(`le serveur écoute http://localhost:${PORT}`) +}) + +const dataConf = obtenirConfigurationDunFichier(['hostname', 'token', 'password', 'front_type', 'url', 'mode_nfc'], './.chromium_env') +lancerChromium(1,dataConf) diff --git a/serveurNfcNodeJsVma405/vma405.js b/serveurNfcNodeJsVma405/vma405.js new file mode 100755 index 0000000..61d80fc --- /dev/null +++ b/serveurNfcNodeJsVma405/vma405.js @@ -0,0 +1,65 @@ +// si problême de droit +// sudo chown root:gpio /dev/gpiomem +// sudo chmod g+rw /dev/gpiomem +// sudo chmod g+rw /dev/gpiomem +// sudo usermod -a -G gpio $USER +// sudo usermod -a -G spi $USER +// sudo usermod -a -G netdev $USER + +"use strict" +// const event = require('events') +const EventEmitter = require('node:events') +const Mfrc522 = require("mfrc522-rpi") +const SoftSPI = require("rpi-softspi") + +const vma405Emitter = new EventEmitter() +vma405Emitter.emit('msgVma405', 'scanning...') + +const softSPI = new SoftSPI({ + clock: 23, // pin number of SCLK + mosi: 19, // pin number of MOSI + miso: 21, // pin number of MISO + client: 24 // pin number of CS +}); + +// GPIO 24 can be used for buzzer bin (PIN 18), Reset pin is (PIN 22). +// const mfrc522 = new Mfrc522(softSPI).setResetPin(22).setBuzzerPin(18); +const mfrc522 = new Mfrc522(softSPI).setResetPin(22) + +setInterval(function() { + //# reset card + mfrc522.reset(); + + // Scan for cards + let response = mfrc522.findCard(); + if (!response.status) { + // console.log("No Card"); + return; + } + + // Get the UID of the card + response = mfrc522.getUid(); + if (!response.status) { + vma405Emitter.emit('msgVma405', 'UID Scan Erro') + return; + } + + // If we have the UID, continue + const uid = response.data; + let resultat = '' + for(let i=0; i < 4; i++){ + let lettre = uid[i].toString(16).toUpperCase() + if(uid[i].toString(16).length === 1) { + resultat += '0' + lettre + } else { + resultat += lettre + } + } + // resultat + vma405Emitter.emit('tagId',resultat) + + // Stop + mfrc522.stopCrypto(); +}, 500); + +module.exports = vma405Emitter diff --git a/serveurNfcNodeJsVma405/www/css/clavier_virtuel.css b/serveurNfcNodeJsVma405/www/css/clavier_virtuel.css new file mode 100755 index 0000000..80b2ee8 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/css/clavier_virtuel.css @@ -0,0 +1,43 @@ +/* clavier virtuel */ +#clavier-virtuel-conteneur { + position: absolute; + left: 0; + top: 0; + width: auto; + display: flex; + flex-direction: column; + overflow: hidden; + background-color: #d6dbdf; +} + +.clavier-virtuel-ligne { + width: 100%; + height: 50px; + margin: 3px 0 3px 0; + display: flex; + flex-direction: row; + justify-content: flex-start; + align-items: center; +} + +.clavier-virtuel-touche { + height: 50px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + margin: 0 4px 0 4px; + /*border: 1px solid #000;*/ + border-radius: 2px; + cursor: pointer; + box-shadow: inset 0 0 8px #bbb, 0 1px 0 #aaa, 0 4px 0 #bbb, 0 10px 30px #ddd; +} + +.clavier-virtuel-text { + font-size: 16px; + font-weight: bold; + display: flex; + flex-direction: row; + justify-content: center; + color: #000000; +} diff --git a/serveurNfcNodeJsVma405/www/css/index.css b/serveurNfcNodeJsVma405/www/css/index.css new file mode 100755 index 0000000..be75cc1 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/css/index.css @@ -0,0 +1,280 @@ +body { + font-size: 14px; + color: #000000; + width: 100%; + height: 100%; + overflow: hidden; + position: relative; + background: #18252f; + color: #fff; + height: 100vh; + width: 100vw; + margin: 0; + padding: 0; +} + +.BF-ligne { + display: flex; + flex-direction: row; + /* axe ligne - x */ + justify-content: center; + /* axe colonne - y */ + align-items: center; +} + +.BF-ligne-deb { + display: flex; + flex-direction: row; + justify-content: flex-start; + align-items: center; +} + +.BF-col { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.BF-col-deb { + display: flex; + flex-direction: column; + justify-content: center; +} + +.BF-col-haut { + display: flex; + flex-direction: column; + justify-content: flex-start; + align-items: center; +} + +/* padding x/y px */ +.p4px {padding: 4px;} +.p8px {padding: 8px;} +.p12px {padding: 12px;} +.p16px {padding: 16px;} + + +/* marges x/y px */ +.m4px {margin: 4px;} +.m8px {margin: 8px;} +.m12px {margin: 12px;} +.m16px {margin: 16px;} + +/* marges gauche px */ +.mg4px {margin-left: 4px;} +.mg8px {margin-left: 8px;} +.mg12px {margin-left: 12px;} +.mg16px {margin-left: 16px;} + +/* marges droite px */ +.md4px {margin-right: 4px;} +.md8px {margin-right: 8px;} +.md12px {margin-right: 12px;} +.md16px {margin-right: 16px;} + +/* marges basse px */ +.mb4px {margin-bottom: 4px;} +.mb8px {margin-bottom: 8px;} +.mb12px {margin-bottom: 12px;} +.mb16px {margin-bottom: 16px;} + +/* largeur % */ +.l50p { width: 50%;} +.l60p { width: 60%;} +.l99p { width: 99%; } +.l100p { width: 100%;} + +/* hauteur % */ +.h100p { height: 100%; } + +/* fonte */ +.ft-gras { font-weight: bold;} +.ft-1r { font-size: 1rem;} +.ft-1-5r { font-size: 1.5rem;} +.ft-2r { font-size: 2rem;} + +/* fonds */ +.fond-alerte { + background-color: #aa3a3a; +} +.fond-retour { + background-color: #3b567f; +} +.fond-header { + background-color: #1a1e25; +} +.fond-ok { + background-color: #339448; +} + +.fond-info { + background-color: #17a2b8; +} + +.fond-pasbon { + background-color: #a6adad; +} + +.fond-dev1 { + background-color: #040426; +} + +.fond-dev2 { + background-color: #0335b8; +} + +.fond-dev3 { + background-color: #012584; +} + +.fond-dev4 { + background-color: #011549; +} + +.fond-dev5 { + background-color: #492601; +} + +.fond-menu-cashless { + /*background-color: #b35c22;*/ + background-color: #af6c7a; +} +.fond-coul1 { + background-color: #dc6575; /* #8d1737; */ +} + +/* couleurs */ +.coulBlanc { + color: #ffffff; +} + +.coul-alerte { + color: #aa3a3a; +} + +.eff { + display: none!important; +} + +.curseur-action { + cursor: pointer; +} + + +/* Header - Menu haut */ +.navbar-horizontal { + display: flex; + flex-direction: row; + width: 100%; + border-bottom: 1px solid #303b44; + height: 60px; +} + +.navbar-img { + width: 120px; + height: 100%; +} + +.navbar-nom { + width: calc(100% - 120px); + height: 100%; +} + +#contenu { + width: 100%; + height: calc(100% - 140px); +} + +.item-info { + font-size: 18px; + font-weight: bold; + margin: 4px 0; +} + +.bt { + height: 60px; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + margin: 4px; + padding: 0 16px; + font-size: 16px; + font-weight: bold; + border: 2px solid #000000; + border-radius: 4px; +} + +.bt-250px { + width: 250px; +} + +.mod-wifi-label, .serveur-label { + width: 150px; + font-size: 16px; + font-weight: bold; +} + +.input-pour-pi { + width: calc(100% - 170px); + font-size: 24px; + font-weight: bold; + height: 60px; +} + +#modifier-wifi, #modifier-serveur{ + width: 100%; + border-radius: 4px; + border: 2px solid #000000; + padding: 4px; +} + +.mod-wifi-erreur, .mod-serveur-erreur { + width: 20px; + height: 20px; + border-radius: 10px; + background-color: #8A2400; +} + +.mod-wifi-ok, .mod-serveur-ok { + width: 20px; + height: 20px; + border-radius: 10px; + background-color: #47e005; +} + +.bt-valider { + width: 150px; +} + +#infos-plus { + background-color: #4caf50; + width: 100%; + overflow: auto; +} + +footer { + height: 80px; +} + +/* popup */ +#popup{ + position: absolute; + left: 0; + top: 0; + height: 100vh; +} + +#popup-contenu { + width: 100%; + height: calc(100% - 80px); +} + +#popup-footer { + width: 100%; + height: 80px; + font-size: 18px; + font-weight: bold; +} \ No newline at end of file diff --git a/serveurNfcNodeJsVma405/www/index.html b/serveurNfcNodeJsVma405/www/index.html new file mode 100755 index 0000000..7c68147 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/index.html @@ -0,0 +1,39 @@ + + + + + + + Tibillet + + +
+ +
+
+
Résolution: ?
+ {{ afficherInfoServeur }} +
Ip: {{ ip }}
+
+
Type serveur nfc: {{ typeserveurNfc }}
+ +
Type lecteur nfc: {{ typeLecteurNfc }}
+
tag Id:
+
+ + + + + \ No newline at end of file diff --git a/serveurNfcNodeJsVma405/www/js/clavier_virtuel.js b/serveurNfcNodeJsVma405/www/js/clavier_virtuel.js new file mode 100755 index 0000000..ef81dc1 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/js/clavier_virtuel.js @@ -0,0 +1,379 @@ +export let pos = { debSel: 0, finSel: 0} +export let ancienEtatAlpha = 'alpahMin' + +let etatsClavier = { + "alpahMin": [ + [ + {"type": "nombre", "taille": 1, "val": 97}, + {"type": "nombre", "taille": 1, "val": 122}, + {"type": "nombre", "taille": 1, "val": 101}, + {"type": "nombre", "taille": 1, "val": 114}, + {"type": "nombre", "taille": 1, "val": 116}, + {"type": "nombre", "taille": 1, "val": 121}, + {"type": "nombre", "taille": 1, "val": 117}, + {"type": "nombre", "taille": 1, "val": 105}, + {"type": "nombre", "taille": 1, "val": 111}, + {"type": "nombre", "taille": 1, "val": 112} + ], + [ + {"type": "caractere", "taille": 1, "val": 'q'}, + {"type": "caractere", "taille": 1, "val": 's'}, + {"type": "caractere", "taille": 1, "val": 'd'}, + {"type": "caractere", "taille": 1, "val": 'f'}, + {"type": "caractere", "taille": 1, "val": 'g'}, + {"type": "caractere", "taille": 1, "val": 'h'}, + {"type": "caractere", "taille": 1, "val": 'j'}, + {"type": "caractere", "taille": 1, "val": 'k'}, + {"type": "caractere", "taille": 1, "val": 'l'}, + {"type": "caractere", "taille": 1, "val": 'm'} + ], + [ + {"type": "mot", "taille": 1, "val": 'MAJ'}, + {"type": "caractere", "taille": 1, "val": 'w'}, + {"type": "caractere", "taille": 1, "val": 'x'}, + {"type": "caractere", "taille": 1, "val": 'c'}, + {"type": "caractere", "taille": 1, "val": 'v'}, + {"type": "caractere", "taille": 1, "val": 'b'}, + {"type": "caractere", "taille": 1, "val": 'n'}, + {"type": "caractere", "taille": 1, "val": '?'}, + {"type": "mot", "taille": 1, "val": "simpleGuillemet"}, + {"type": "mot", "taille": 1, "val": 'SUP'} + ], + [ + {"type": "mot", "taille": 1, "val": 'ALT'}, + {"type": "mot", "taille": 1, "val": 'NUM'}, + {"type": "caractere", "taille": 1, "val": ','}, + {"type": "mot", "taille": 2, "val": 'ESPACE'}, + {"type": "caractere", "taille": 1, "val": '.'}, + {"type": "mot", "taille": 2, "val": 'VALIDER'}, + {"type": "mot", "taille": 2, "val": 'RETOUR LIGNE'} + ], + ], + "alpahMaj": [ + [ + {"type": "caractere", "taille": 1, "val": 'A'}, + {"type": "caractere", "taille": 1, "val": 'Z'}, + {"type": "caractere", "taille": 1, "val": 'E'}, + {"type": "caractere", "taille": 1, "val": 'R'}, + {"type": "caractere", "taille": 1, "val": 'T'}, + {"type": "caractere", "taille": 1, "val": 'Y'}, + {"type": "caractere", "taille": 1, "val": 'U'}, + {"type": "caractere", "taille": 1, "val": 'I'}, + {"type": "caractere", "taille": 1, "val": 'O'}, + {"type": "caractere", "taille": 1, "val": 'P'} + ], + [ + {"type": "caractere", "taille": 1, "val": 'Q'}, + {"type": "caractere", "taille": 1, "val": 'S'}, + {"type": "caractere", "taille": 1, "val": 'D'}, + {"type": "caractere", "taille": 1, "val": 'F'}, + {"type": "caractere", "taille": 1, "val": 'G'}, + {"type": "caractere", "taille": 1, "val": 'H'}, + {"type": "caractere", "taille": 1, "val": 'J'}, + {"type": "caractere", "taille": 1, "val": 'K'}, + {"type": "caractere", "taille": 1, "val": 'L'}, + {"type": "caractere", "taille": 1, "val": 'M'} + ], + [ + {"type": "mot", "taille": 1, "val": 'MAJ'}, + {"type": "caractere", "taille": 1, "val": 'W'}, + {"type": "caractere", "taille": 1, "val": 'X'}, + {"type": "caractere", "taille": 1, "val": 'C'}, + {"type": "caractere", "taille": 1, "val": 'V'}, + {"type": "caractere", "taille": 1, "val": 'B'}, + {"type": "caractere", "taille": 1, "val": 'N'}, + {"type": "mot", "taille": 1, "val": "simpleGuillemet"}, + {"type": "mot", "taille": 2, "val": 'SUP'}, + ], + [ + {"type": "mot", "taille": 2, "val": 'NUM'}, + {"type": "caractere", "taille": 1, "val": ','}, + {"type": "mot", "taille": 4, "val": 'ESPACE'}, + {"type": "caractere", "taille": 1, "val": '.'}, + {"type": "mot", "taille": 2, "val": 'RETOUR LIGNE'} + ], + ], + "num": [ + [ + {"type": "caractere", "taille": 1, "val": '1'}, + {"type": "caractere", "taille": 1, "val": '2'}, + {"type": "caractere", "taille": 1, "val": '3'}, + {"type": "caractere", "taille": 1, "val": '4'}, + {"type": "caractere", "taille": 1, "val": '5'}, + {"type": "caractere", "taille": 1, "val": '6'}, + {"type": "caractere", "taille": 1, "val": '7'}, + {"type": "caractere", "taille": 1, "val": '8'}, + {"type": "caractere", "taille": 1, "val": '9'}, + {"type": "caractere", "taille": 1, "val": '0'} + ], + [ + {"type": "caractere", "taille": 1, "val": '@'}, + {"type": "caractere", "taille": 1, "val": '#'}, + {"type": "caractere", "taille": 1, "val": '$'}, + {"type": "caractere", "taille": 1, "val": '%'}, + {"type": "caractere", "taille": 1, "val": '&'}, + {"type": "caractere", "taille": 1, "val": '*'}, + {"type": "caractere", "taille": 1, "val": '_'}, + {"type": "caractere", "taille": 1, "val": '+'}, + {"type": "caractere", "taille": 1, "val": '('}, + {"type": "caractere", "taille": 1, "val": ')'}, + ], + [ + {"type": "caractere", "taille": 1, "val": '-'}, + {"type": "caractere", "taille": 1, "val": '['}, + {"type": "caractere", "taille": 1, "val": ']'}, + {"type": "caractere", "taille": 1, "val": '!'}, + {"type": "caractere", "taille": 1, "val": '"'}, + {"type": "mot", "taille": 1, "val": "simpleGuillemet"}, + {"type": "caractere", "taille": 1, "val": ':'}, + {"type": "caractere", "taille": 1, "val": ';'}, + {"type": "caractere", "taille": 1, "val": '/'}, + {"type": "caractere", "taille": 1, "val": '?'} + ], + [ + {"type": "mot", "taille": 2, "val": 'ABC'}, + {"type": "mot", "taille": 1, "val": 'ALT'}, + {"type": "mot", "taille": 4, "val": 'ESPACE'}, + {"type": "caractere", "taille": 1, "val": '.'}, + {"type": "mot", "taille": 2, "val": 'RETOUR LIGNE'} + ], + ], + "alt": [ + [ + {"type": "caractere", "taille": 1, "val": '~'}, + {"type": "caractere", "taille": 1, "val": '`'}, + {"type": "caractere", "taille": 1, "val": '|'}, + {"type": "caractere", "taille": 1, "val": '.'}, + {"type": "caractere", "taille": 1, "val": 'x'}, + {"type": "caractere", "taille": 1, "val": '{'}, + {"type": "caractere", "taille": 1, "val": '}'}, + {"type": "caractere", "taille": 1, "val": '€'}, + {"type": "caractere", "taille": 1, "val": '°'}, + {"type": "caractere", "taille": 1, "val": '^'}, + ], + [ + {"type": "mot", "taille": 2, "val": 'NUM'}, + {"type": "caractere", "taille": 1, "val": '_'}, + {"type": "caractere", "taille": 1, "val": '='}, + {"type": "caractere", "taille": 1, "val": '['}, + {"type": "caractere", "taille": 1, "val": ']'}, + {"type": "caractere", "taille": 1, "val": '<'}, + {"type": "caractere", "taille": 1, "val": '>'}, + {"type": "mot", "taille": 1, "val": 'antiSlash'}, + {"type": "caractere", "taille": 1, "val": '"'} + ], + [ + {"type": "mot", "taille": 2, "val": 'ABC'}, + {"type": "mot", "taille": 4, "val": 'ESPACE'}, + {"type": "mot", "taille": 2, "val": 'VALIDER'}, + {"type": "mot", "taille": 2, "val": 'RETOUR LIGNE'} + ], + ], + "numSolo": [ + [ + {"type": "caractere", "taille": 1, "val": '1'}, + {"type": "caractere", "taille": 1, "val": '2'}, + {"type": "caractere", "taille": 1, "val": '3'}, + {"type": "caractere", "taille": 1, "val": '4'} + ], + [ + {"type": "caractere", "taille": 1, "val": '5'}, + {"type": "caractere", "taille": 1, "val": '6'}, + {"type": "caractere", "taille": 1, "val": '7'}, + {"type": "caractere", "taille": 1, "val": '8'} + ], + [ + {"type": "caractere", "taille": 1, "val": '9'}, + {"type": "caractere", "taille": 1, "val": '0'}, + {"type": "caractere", "taille": 1, "val": '.'}, + {"type": "mot", "taille": 1, "val": 'C'} + ], + [ + {"type": "mot", "taille": 2, "val": 'SUP'}, + {"type": "mot", "taille": 2, "val": 'VALIDER'} + ] + ] +} + + +function obtEtatSelection (cible){ + let element = document.getElementById(cible) + // plage de sélection + let debSel = element.selectionStart + let finSel = element.selectionEnd + return { debSel: debSel, finSel: finSel } +} + +export function simule(touche, typeTouche, cible) { + let etat + let element = document.getElementById(cible) + + // ajout de cartères qui induisent des erreurs de d'interprétation du code html/javascript + if (touche === 'simpleGuillemet') { + touche = "'" + typeTouche = 'caractere' + } + + if (touche === 'antiSlash') { + touche = "\\" + typeTouche = 'caractere' + } + + if (touche === 'ESPACE') { + touche = ' ' + typeTouche = 'caractere' + } + + if (touche === 'RETOUR LIGNE') { + touche = '\n' + typeTouche = 'caractere' + } + + // entrée clavier + if (typeTouche !== 'mot') { + let texte = element.value + // tout le texte avant le début de sélection + let texteAvant = texte.substring(0, pos.debSel) + // tout le texte après la fin de sélection + let texteApres = texte.substring(pos.finSel, texte.length) + // nouveau texte + element.value = texteAvant + touche + texteApres + // maj position curseur + pos.debSel += 1 + pos.finSel = pos.debSel + } + + // état du clavier + if (touche === 'MAJ') { + if (etat === 'alpahMaj' ){ + etat = 'alpahMin' + ancienEtatAlpha = 'alpahMin' + } else { + etat = 'alpahMaj' + ancienEtatAlpha = 'alpahMaj' + } + afficher(cible, etat) + } + + if (touche === 'NUM') { + etat = 'num' + afficher(cible, etat) + } + + if (touche === 'ABC') { + etat = ancienEtatAlpha + afficher(cible, etat) + } + + if (touche === 'ALT') { + etat = 'alt' + afficher(cible, etat) + } + + // touche supprimer + if (touche === 'SUP') { + let texteAvant, texteApres + let texte = element.value + + // selection ? + let sel = obtEtatSelection(cible) + if (sel.debSel !== sel.finSel) { + pos.debSel = sel.debSel + pos.finSel = sel.finSel + } + + if (sel.debSel === sel.finSel) { // pas de sélection + texteAvant = texte.substring(0, pos.debSel-1) + pos.debSel -= 1 + } else { // sélection + texteAvant = texte.substring(0, pos.debSel) + } + texteApres = texte.substring(pos.finSel, texte.length) + pos.finSel = pos.debSel + element.value = texteAvant + texteApres + } + + //Vider l'entréé + if (touche === 'C') { + document.querySelector('#' + cible).value = '' + } + + // validation + if (touche === 'VALIDER') { + let eleSup = document.querySelector('#clavier-virtuel-conteneur') + eleSup.parentNode.removeChild(eleSup) + } +} + +export function obtPosition(cible){ + let element = document.getElementById(cible) + pos = { debSel: element.selectionStart, finSel: element.selectionEnd} +} + +export function afficher(cible, etat) { + let largeurTouche = 50 + try { + // supprime un ancien clavier virtuel et son évènement + let eleSup = document.querySelector('#clavier-virtuel-conteneur') + eleSup.parentNode.removeChild(eleSup) + } catch (error) { + console.log("info: l'élément clavier n'existait pas !") + } + + let touches = etatsClavier[etat] + + let clavierFrag = ` +
+ ` + for (let i = 0; i < touches.length; i++) { + let ligne = touches[i] + clavierFrag += ` +
+ ` + for (let j = 0; j < ligne.length; j++) { + let typeData = ligne[j].type + let taille = ligne[j].taille + let val = ligne[j].val + let retour, goutiere = 0 + if (typeData === 'nombre') { + retour = String.fromCharCode(val) + } else { + retour = val + } + + if (taille > 1) { + goutiere = (taille-1) * 8 + } + + // console.log('-> typeData = ' + typeData + ' -- taille = ' + taille + ' -- val = ' + val + ' -- retour = ' + retour) + clavierFrag += ` +
+ ` + if (typeData === 'nombre' || typeData === 'caractere' || typeData === 'caractereSpecial') { + clavierFrag += `
${ retour }
` + } + + if (typeData === 'mot') { + if (val === 'simpleGuillemet') { + clavierFrag += `
'
` + } + + if (val === 'antiSlash') { + clavierFrag += `
\\
` + } + + if (val !== 'simpleGuillemet' && val !== 'antiSlash') { + let text = val.split(' ') + for (let k = 0; k < text.length; k++) { + clavierFrag += `
${text[k]}
` + } + } + } + clavierFrag += `
` + } + clavierFrag += `
` + } + clavierFrag += '
' + document.querySelector('body').insertAdjacentHTML('beforeend', clavierFrag) +} \ No newline at end of file diff --git a/serveurNfcNodeJsVma405/www/js/index.js b/serveurNfcNodeJsVma405/www/js/index.js new file mode 100755 index 0000000..b8426c2 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/js/index.js @@ -0,0 +1,234 @@ +// initialisation +window.store = {} +const TOKEN = '$a;b2yuM5454@4!cd' +let socket = io('http://localhost:3000',{ query: { token: TOKEN} }) +let etatServeur = 0 + +import * as ClavierVirtuel from "./clavier_virtuel.js" +window.clavierVirtuel = ClavierVirtuel + +function popup(data) { + let fondPopup = 'fond-header' + if (data.typeMessage === 'alerte') { + fondPopup = 'fond-alerte' + } + if (data.typeMessage === 'succes') { + fondPopup = 'fond-ok' + } + let frag = ` + + ` + let elePopup = document.querySelector('#popup') + if (elePopup !== null) { + elePopup.parentNode.removeChild(elePopup) + document.body.insertAdjacentHTML('afterbegin', frag) + } else { + document.body.insertAdjacentHTML('afterbegin', frag) + } +} + + +// messages divers +socket.on('afficherMsg', (retour) => { + // exemple, retour = { contenu: retour, typeMessage: 'succes' } + popup(retour) +}) + + +// Réception tagId +socket.on('afficherMsgErreur', (retour) => { + let data = { + contenu: retour, + typeMessage: 'alerte' + } + popup(data) +}) + +// Retour infos wifi +socket.on('retourInfosWifi', (fragmentHtml) => { + // console.log('-> retourInfosWifi !!!') + document.querySelector('#rep-info-reseau').insertAdjacentHTML('afterend', fragmentHtml) + + document.querySelector('#bt-modifier-wifi').addEventListener('click', function () { + let contenuClass = document.querySelector('#modifier-wifi').classList.value + if (contenuClass.indexOf('eff') !== -1 ) { + cacherContenuFormSauf('modifier-wifi') + } else { + document.querySelector('#modifier-wifi').classList.add('eff') + } + }) + + document.querySelector('#bt-valider-modifier-wifi').addEventListener('click', function () { + let essid = document.querySelector('#essid').value + let passePhrase = document.querySelector('#pp').value + // console.log('essid = ',essid, ' -- passePhrase = ', passePhrase) + socket.emit('validerModifierWifi', {essid: essid, passePhrase: passePhrase}) + effacerClavierVirtuel() + }) +}) + +socket.on('etatUrlServeur', (retourTestUrl) => { + // header 307 = redirection temporaire + // header 308 = redirection permanente + if(retourTestUrl === '200' || retourTestUrl === '307' || retourTestUrl === '308') { + document.querySelector('#info-serveur').style.color = "#00FF00" + // bt lancer l'application + etatServeur = 1 + document.querySelector('#bt-lancer-application').classList.remove('fond-pasbon') + document.querySelector('#bt-lancer-application').classList.add('fond-ok') + } else { + document.querySelector('#info-serveur').style.color = "#FF0000" + // bt lancer l'application + etatServeur = 0 + document.querySelector('#bt-lancer-application').classList.remove('fond-ok') + document.querySelector('#bt-lancer-application').classList.add('fond-pasbon') + } +}) + +socket.on('infosTagId', (retour) => { + document.querySelector('#nfc').innerHTML = retour +}) + +// message modification wifi +socket.on('modificationWifi', (retour) => { + console.log('wifi: ',retour) + let data = {} + if (retour.erreur === 0) { + document.querySelector('#etat-modifier-wifi').classList.remove('mod-wifi-erreur') + document.querySelector('#etat-modifier-wifi').classList.add('mod-wifi-ok') + data = { contenu: retour.msg, typeMessage: 'succes' } + } else { + document.querySelector('#etat-modifier-wifi').classList.remove('mod-wifi-ok') + document.querySelector('#etat-modifier-wifi').classList.add('mod-wifi-erreur') + document.querySelector('#modifier-wifi').classList.toggle('eff') + data = { contenu: retour.msg, typeMessage: 'alerte' } + } + popup(data) + cacherContenuFormTous() +}) + +// modification serveur +socket.on('modificationServeur', (retour) => { + console.log('serveur: ',retour) + let data = {} + if (retour.erreur === 0) { + document.querySelector('#etat-modifier-serveur').classList.remove('mod-serveur-erreur') + document.querySelector('#etat-modifier-serveur').classList.add('mod-serveur-ok') + data = { + contenu: ` +
+

Modification du serveur effectuée :

+

serveur = ${ retour.serveurDomaine} .

+

Vous devez redémmarer l'appareil

+

pour prendre en compte le nouveau serveur .

+
+ `, + typeMessage: 'succes' + } + document.querySelector('#info-serveur').innerHTML = `Serveur: ${ retour.serveurDomaine }` + } else { + document.querySelector('#etat-modifier-serveur').classList.remove('mod-serveur-ok') + document.querySelector('#etat-modifier-serveur').classList.add('mod-serveur-erreur') + document.querySelector('#modifier-serveur').classList.toggle('eff') + data = { + contenu: ` +

Erreur modification serveur !

+ `, + typeMessage: 'alerte' + } + } + popup(data) + cacherContenuFormTous() +}) + +function cacherContenuFormSauf(id) { + // console.log('-> fonction cacherContenuFormSauf, id = ', id) + let eles = document.querySelectorAll('.contenu-form') + for (let i = 0; i < eles.length; i++) { + let ele = eles[i] + let idEle = ele.id + // console.log('idEle = ', idEle) + ele.classList.add('eff') + if (id === idEle) { + ele.classList.remove('eff') + } + } +} + +function cacherContenuFormTous() { + cacherContenuFormSauf('nimportequoi') +} + +function effacerClavierVirtuel() { + let clavier = document.querySelector('#clavier-virtuel-conteneur') + if (clavier !== null) { + clavier.parentNode.removeChild(clavier) + } +} + +window.addEventListener('load',function() { + let resolution = 'Résolution: ' + document.body.clientWidth + 'x' + document.body.clientHeight + document.querySelector('#info-resolution-ecran').innerHTML = resolution + let urlATester = document.querySelector('#info-serveur').getAttribute('data-serveur') + if (urlATester !== '' && urlATester !== undefined) { + socket.emit('testerUrlServeur', urlATester) + } + let emplacementInfosReseau = document.querySelector('#rep-info-reseau') + socket.emit('donnerInfosWifi', '') + +}) + + +if (document.querySelector('#bt-modifier-serveur')) { + document.querySelector('#bt-modifier-serveur').addEventListener('click', function () { + let contenuClass = document.querySelector('#modifier-serveur').classList.value + if (contenuClass.indexOf('eff') !== -1 ) { + cacherContenuFormSauf('modifier-serveur') + effacerClavierVirtuel() + } else { + document.querySelector('#modifier-serveur').classList.add('eff') + } + + }) +} + + + + +if (document.querySelector('#bt-valider-modifier-serveur')) { + document.querySelector('#bt-valider-modifier-serveur').addEventListener('click', function () { + let serveurDomaine = document.querySelector('#serveur').value + let user = document.querySelector('#nom-appareil').value + let typeFront = document.querySelector('#type-front').value + let genererMotDePasse = document.querySelector('#passe').checked + // console.log('genererMotDePasse = ', genererMotDePasse) + socket.emit('validerModifierServeur', {serveurDomaine: serveurDomaine, user: user, typeFront: typeFront, genererMotDePasse: genererMotDePasse}) + effacerClavierVirtuel() + }) +} + +if (document.querySelector('#bt-tester-serveur')) { + document.querySelector('#bt-tester-serveur').addEventListener('click', function () { + let urlATester = document.querySelector('#info-serveur').getAttribute('data-serveur') + if (urlATester !== '' && urlATester !== undefined) { + socket.emit('testerUrlServeur', urlATester) + } + effacerClavierVirtuel() + }) +} + +document.querySelector('#bt-lancer-application').addEventListener('click',function() { + if (etatServeur === 1) { + // let urlRedirection = document.querySelector('#info-serveur').getAttribute('data-url-serveur') + // console.log(`${ new Date() } -> lancer l'application à l'url: ${ urlRedirection }`) + // console.log('agent = ', JSON.stringify(navigator.userAgent, null, '\t')) + //window.location = urlRedirection + socket.emit('lancerApplication') + } + effacerClavierVirtuel() +}) diff --git a/serveurNfcNodeJsVma405/www/js/socket.io.js b/serveurNfcNodeJsVma405/www/js/socket.io.js new file mode 100755 index 0000000..80b2af8 --- /dev/null +++ b/serveurNfcNodeJsVma405/www/js/socket.io.js @@ -0,0 +1,7417 @@ +/*! + * Socket.IO v3.0.5 + * (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/app.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); + 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.query; + } + + 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); + if (packet.query && packet.type === 0) packet.nsp += "?" + packet.query; + 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 loc - An object meant to mimic window.location. + * Defaults to window.location. + * @public + */ + + +function url(uri, loc) { + 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; // 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/app.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/app.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__) { + +/* WEBPACK VAR INJECTION */(function(process) {/* 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; + } +}; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./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/app.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/engine.io-client/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/app.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 = '