UNPKG

kiite

Version:

super basic longpolling sockets

1 lines 19.1 kB
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).kiite=e()}}(function(){return function(){function e(t,o,n){function r(i,a){if(!o[i]){if(!t[i]){var l="function"==typeof require&&require;if(!a&&l)return l(i,!0);if(s)return s(i,!0);var c=new Error("Cannot find module '"+i+"'");throw c.code="MODULE_NOT_FOUND",c}var u=o[i]={exports:{}};t[i][0].call(u.exports,function(e){return r(t[i][1][e]||e)},u,u.exports,e,t,o,n)}return o[i].exports}for(var s="function"==typeof require&&require,i=0;i<n.length;i++)r(n[i]);return r}return e}()({1:[function(e,t,o){!function(o){"use strict";var n=0,r=Math.pow(36,4),s=function(e,t){var o="000000000"+e;return o.substr(o.length-t)},i=function(){return s((Math.random()*r<<0).toString(36),4)},a=function(){return n=n<r?n:0,++n-1},l=function(){var e,t=(new Date).getTime().toString(36),o=l.fingerprint(),n=i()+i();return e=s(a().toString(36),4),"c"+t+e+o+n};l.slug=function(){var e,t=(new Date).getTime().toString(36),o=l.fingerprint().slice(0,1)+l.fingerprint().slice(-1),n=i().slice(-2);return e=a().toString(36).slice(-4),t.slice(-2)+e+o+n},l.fingerprint=function(){var t=e("os"),o=s(process.pid.toString(36),2),n=t.hostname(),r=n.length;return o+s(n.split("").reduce(function(e,t){return+e+t.charCodeAt(0)},+r+36).toString(36),2)},o.register?o.register("cuid",l):void 0!==t?t.exports=l:o.cuid=l}(this.applitude||this)},{os:void 0}],2:[function(e,t,o){!function(e,t){t()}(0,function(){"use strict";function o(e,t,o){s._mode="browser";var n=new window.XMLHttpRequest;if(!window)throw new Error('no global browser "window" object found.');if(!window.location)throw new Error('no global browser "window.location" object found.');e.protocol=e.protocol||window.location.protocol||"http",":"!==e.protocol[e.protocol.length-1]&&(e.protocol+=":"),e.hostname=e.hostname||e.host||window.location.hostname;var r=80;e.protocol&&(r=-1!==e.protocol.indexOf("https")?443:80);var i=e.hostname.toLowerCase().trim(),a=window.location.hostname.toLowerCase().trim();-1!==i.indexOf(a)&&(r=window.location.port||r),e.port=e.port||r;var l=e.protocol+"//"+e.hostname+(e.port?":"+e.port:""),c=l+e.path;s.debug&&console.log("dasu: url ["+c+"]"),s.debug&&(console.log("--- dasu opts ---"),console.log(e),console.log()),n.open(e.method,c,!0),n.onload=function(){o(null,n,n.responseText)},n.onerror=function(){var r=(e.method||"get").toUpperCase()+" "+c,s={name:"NetworkError",message:n.responseText||"NetworkError: XMLHttpRequest ("+r+")",desc:r,url:c,opts:e,data:t,origin:l,responseText:n.responseText};s.toString=function(){return s.message+"\n"+JSON.stringify(e,null,2).split(",")},s.message=s.toString(),o(s)};for(var u=Object.keys(e.headers),d=0;d<u.length;d++){var p=u[d].toLowerCase(),f=e.headers[p];n.setRequestHeader(p,f)}try{n.send(t)}catch(n){var g=(e.method||"get").toUpperCase()+" "+c;n.desc=g,n.url=c,n.opts=e,n.data=t,n.origin=l,n.toString=function(){return n.message+"\n"+JSON.stringify(e,null,2).split(",")},o(n)}return{abort:function(){n.abort()}}}function n(e,t,o){s._mode="node";var n=i("http"),r=i("https"),a=i("zlib");(e=e||{}).hostname=e.hostname||e.host,e.protocol=e.protocol||"http";var l=n;e.protocol&&-1!==e.protocol.indexOf("https")&&(l=r),":"!==e.protocol[e.protocol.length-1]&&(e.protocol+=":"),s.debug&&(console.log("--- dasu opts ---"),console.log(e),console.log());var c=l.request(e,function(e){var t=[],n=e;if(a.createBrotliDecompress&&"br"===e.headers["content-encoding"]){var r=a.createBrotliDecompress();n=r,e.pipe(r)}if(a.createGunzip&&"gzip"===e.headers["content-encoding"]){var s=a.createGunzip();n=s,e.pipe(s)}if(a.createDeflate&&"deflate"===e.headers["content-encoding"]){var i=a.createDeflate();n=i,e.pipe(i)}var l=e.headers["content-type"];l&&l.indexOf("text/")>=0?l.indexOf("ascii")>=0?n.setEncoding("ascii"):n.setEncoding("utf8"):n.setEncoding("binary"),n.on("data",function(e){t.push(e)}),n.on("end",function(){var n=t.join("");e.responseText=e.responseText||n,o(null,e,n)})});return c.on("error",function(n){var r=e.protocol+"//"+e.hostname+(e.port?":"+e.port:""),s=r+e.path,i=(e.method||"get").toUpperCase()+" "+s;n.desc=i,n.url=s,n.opts=e,n.data=t,n.origin=r,n.toString=function(){return n.message+"\n"+JSON.stringify(e,null,2).split(",")},n.message=n.toString(),o(n)}),s.debug&&(console.log("dasu typeof dataString: "+typeof t),t&&t.length>=0&&console.log("dasu sending length: "+t.length)),c.write(t),c.end(),{abort:function(){c.abort()}}}function r(e,t){function r(o,n,c){if(o||void 0===n)t(o);else{if(!n.getResponseHeader&&n.headers&&(n.getResponseHeader=function(e){return n.headers[e]}),n.getAllResponseHeaders&&!n.headers&&(n.headers=n.getAllResponseHeaders()),!n.getAllResponseHeaders&&n.headers&&(n.getAllResponseHeaders=function(){return n.headers}),void 0===n.status?n.status=n.statusCode:n.statusCode=n.status,s.debug&&(s.log+="\n-------------\n",s.log+=new Date,s.log+="headers:\n"+JSON.stringify(n.headers,null,2)+"\n\n",s.log+="body:\n"+c+"\n"),s.follow&&n.status>=300&&n.status<400&&n.headers.location&&m<v){m++;var u=n.headers.location;if("//"===u.slice(0,2)&&(u=e.protocol+":"+u),"/"===u[0])return h.path=u,a(h,p,r);var d;if("undefined"!=typeof URL?d=new URL(u):"node"===l&&(d=i("url").parse(u)),s.debug)if("node"===l)try{i("fs").writeFileSync("debug.dasu-response.log",s.log,"utf8")}catch(o){}else console.log(s.log);if(d){Object.keys(h).forEach(function(e){h[e]=d[e]}),h.protocol=d.protocol,h.host=d.host,h.hostname=d.hostname,h.port=d.port;var f=(d.path||d.pathname||"")+(d.search||"");return h.path=f,h.pathname=f,a(h,p,r)}}t(void 0,n,c)}}var l;if("browser"===s.mode||"node"!==s.mode&&"undefined"!=typeof window&&void 0!==window.XMLHttpRequest?(l="browser",a=o):(l="node",a=n),"string"==typeof e){var c;if("object"!=typeof(c="undefined"!=typeof URL?new URL(e):i("url").parse(e)))throw new Error("failed to parse params shorthand: "+e);(e={}).method="GET",e.protocol=c.protocol,e.host=c.host,e.hostname=c.hostname,e.port=c.port,e.path=c.path||c.pathname}var u="",d=e.data||e.json||"",p="";switch(typeof d){case"object":d.toString==={}.toString?(p=JSON.stringify(d),u="application/json"):(s.debug&&console.log("dasu: complex object data"),p=d,u="application/octet-stream");break;case"string":if(d.length>1&&("{"===d[0]||"["===d[0]))try{JSON.parse(d),console&&console.warn?console.warn("[WARNING] dasu: Sending data that may be JSON as text/plain"):console.log("[WARNING] dasu: Sending data that may be JSON as text/plain")}catch(e){}p=d,u="text/plain";break;default:p=""+d,u="text/plain"}delete(e=Object.assign({},e)).data,u&&(e.headers=Object.assign({},{"content-type":u},e.headers||{}),"application/octet-stream"===u&&p&&p.length&&(e.headers=Object.assign({},{"content-length":p.length},e.headers||{}))),e.method=e.method||"GET",e.path=e.path||"/","/"!==e.path[0]&&(e.path="/"+e.path);var f="http";if(e.port){var g=Number(e.port);String(g)===e.port&&(e.port=g),443===e.port&&(f="https")}e.protocol||(e.protocol=f);var h={protocol:e.protocol,host:e.host,hostname:e.hostname,port:e.port,path:e.path,method:e.method,headers:e.headers},m=0,v=3;return s.log="",a(h,p,r)}var s={follow:!0,mode:"auto",log:""},i=e,a=function(){throw new Error("dasu: no _request implementation found!")};s.xhr=function(e,t){r(e,function(e,o,n){t(e,n)})},s.req=r,t.exports=s})},{}],3:[function(e,t,o){"use strict";var n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},o=0;o<10;o++)t["_"+String.fromCharCode(o)]=o;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var o,i,a=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),l=1;l<arguments.length;l++){o=Object(arguments[l]);for(var c in o)r.call(o,c)&&(a[c]=o[c]);if(n){i=n(o);for(var u=0;u<i.length;u++)s.call(o,i[u])&&(a[i[u]]=o[i[u]])}}return a}},{}],4:[function(e,t,o){"use strict";t.exports=function(){var e={},t={};return e.on=function(e,o){var n=t[e];return n||(n=t[e]=[]),n.push(o),function(){var n=t[e],r=n.indexOf(o);if(r>=0)return n.splice(r,1)}},e.once=function(t,o){var n=e.on(t,function(e){n(),o(e)})},e.emit=function(e,o){var n=t[e];if(n)for(var r=0;r<n.length;++r)n[r](o)},e.removeListeners=function(e){e?delete e[e]:Object.keys(t).forEach(function(e){delete t[e]})},e.listeners=function(e){if(e)return t[e];var o=[];return Object.keys(t).forEach(function(e){var n=t[e];o.concat(n)}),o},e}},{}],5:[function(e,t,o){"use strict";Object.assign=e("object-assign");var n=e("./kiite.js"),r=e("./kiite-client.js");n.connect=r,t.exports=n},{"./kiite-client.js":6,"./kiite.js":7,"object-assign":3}],6:[function(e,t,o){"use strict";function n(){("object"===("undefined"==typeof window?"undefined":s(window))&&window._debug_kiite||"object"===("undefined"==typeof process?"undefined":s(process))&&process.env&&process.env.DEBUG_KIITE)&&console.log.apply(this,arguments)}function r(){("object"===("undefined"==typeof window?"undefined":s(window))&&(window._debug_kiite||window._verbose_kiite)||"object"===("undefined"==typeof process?"undefined":s(process))&&process.env&&process.env.DEBUG_KIITE)&&console.log.apply(this,arguments)}var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i=e("dasu").req,a=e("./ee.js");t.exports=function(e){function t(e){if(clearTimeout(p),w.length>0){var t=Date.now();e||t-O>y?(l(),O=Date.now()):p=setTimeout(function(){l(),O=Date.now()},b)}}function o(e,t){var o=t||{};return Object.keys(e).forEach(function(t){null==o[t]&&(o[t]=e[t])}),o}function l(){var t=o(e);t.data={ID:f,evt:"messages",messages:w},w=[],n("flushing"),i(t,function(e,t,o){n(e?"emit error":200===t.status?"emit success":"res.status error: "+t.status)})}function c(){n("scheduling poll in: "+m+" ms"),clearTimeout(D),D=setTimeout(u,m)}function u(){function t(){r("poll error, trying again in 1 sec"),v.emit("disconnect"),v.emit("disconnected"),r("disconnected by server"),setTimeout(function(){d()},1e3)}if(!_&&!T){T=!0;var s=o(e);s.data={ID:f,evt:"longpoll",count:j++};var a=!1;h=setTimeout(function(){a=!0,T=!1,n("longpolling timed out"),d()},g),n("longpolling"),i(s,function(e,o,s){if(n(e?"longpolling error response":"longpolling response"),!a)if(clearTimeout(h),T=!1,e)t();else if(200===o.status){var i;try{i=JSON.parse(s)}catch(e){return n("kiite: bad JSON response from server"),n(e),t()}switch(n("received longpoll evt: "+i.evt),i.uprd&&(m=i.uprd),i.evt){case"renew":c();break;case"messages":n("got buffer.length: "+i.messages.length),i.messages.forEach(function(e){v.emit(e.evt,e.data)}),c();break;case"duplicate":n("got duplicate, stopping this one.");break;default:c()}}else{switch(n("res.status error: "+o.status),o.status){case 444:v.emit("disconnect"),v.emit("disconnected"),r("disconnected by server");break;case 404:r("unkown user or unknown event")}setTimeout(function(){d()},1e3)}})}}function d(){function t(){r("connection error, trying again in 1 sec"),function(){x+=150;var e=2e3,t=!1;"object"===("undefined"==typeof document?"undefined":s(document))&&(t=!!(document.hidden||document.msHidden||document.webkitHidden)),t&&(e=3e3),x>e&&(x=e)}(),setTimeout(function(){d()},x)}if(!_){f=void 0;var a=o(e);a.data={evt:"connect"},n("connecting"),i(a,function(e,o,s){if(e)t();else{if(200!==o.status)return n("unknown res.status: "+o.status),n(s),t();var i;try{i=JSON.parse(s)}catch(e){return n("kiite: failed to connect to server"),n(e),t()}"connected"===i.evt&&i.ID&&i.ID.length>5?(x=1500,i.uprd&&(m=i.uprd),n(i),f=i.ID,v.emit("connect"),v.emit("connected"),r("connected"),c()):(n("unknown connect response"),n(s))}})}}e=e||{};var p,f,g=32500,h=void 0,m=0,v=a(),w=[],b=16,y=100,O=Date.now(),_=!1,j=0,S={on:v.on,emit:function(e,o){w.push({evt:e,data:o}),t()},clients:{},close:function(){t(!0),_=!0,function(){var t=o(e);t.data={ID:f,evt:"disconnect"},f=void 0,n("disconnecting"),i(t,function(e,t,o){})}()}};if("object"!==(void 0===e?"undefined":s(e))){throw new Error('kiite-client connect options must be of type "object"\neg: io({ host: "localhost", port: 3000 })\ndefault to window.location.hostname and window.location.port\nor localhost:80\n')}if("object"===("undefined"==typeof window?"undefined":s(window))){var C={};"object"===s(window.location)&&(C=window.location);var k=80;C.protocol&&C.protocol.indexOf("https")>=0&&(k=443),e.host=e.host||C.hostname||"localhost",e.port=e.port||C.port||k}e.path="/kiite.io",e.method="POST",d();var D=void 0,T=!1,x=1500;return S}},{"./ee.js":4,dasu:2}],7:[function(e,t,o){"use strict";function n(){"object"===("undefined"==typeof process?"undefined":r(process))&&process.env.DEBUG_KIITE&&console.log.apply(this,arguments)}var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=e("./ee.js"),i=e("cuid"),a=25e3,l=3e3,c=25e3,u=0,d=3e4;t.exports=function(t,o){function r(){if(o.enableCC){var e=o.user_delay(O);e<u&&(e=u),e>c&&(e=c),v.user_polling_renew_delay=e,n("updated CC.user_polling_renew_delay: "+v.user_polling_renew_delay);var t=o.renew_interval(O);t<l&&(t=l),t>a&&(t=a),v.longpoll_renew_interval=t,n("updated CC.longpoll_renew_interval: "+v.longpoll_renew_interval)}}function p(e,t,o){n("emitting all");Object.keys(y.clients).forEach(function(r){if(r!==o){var s=y.clients[r];s.buffer.push({evt:e,data:t}),h(s)}else n("exceptID: "+o)})}function f(e,t){var o={};o["Access-Control-Allow-Origin"]="*",o["Access-Control-Allow-Methods"]="POST, GET, PUT, DELETE, OPTIONS",o["Access-Control-Allow-Credentials"]=!1,o["Access-Control-Max-Age"]="86400",o["Access-Control-Allow-Headers"]="X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept",t.writeHead(200,o),t.end()}function g(e,t){e.statusCode=200,e.write(JSON.stringify(t)),e.end()}function h(e){if(e.buffer.length>0)if(e.longpollResponse){var t=e.buffer;e.buffer=[],n("flushing buffer.length: "+t.length+", for client.ID: "+e.ID),clearTimeout(e.longpollResponseTimeout),g(e.longpollResponse,{evt:"messages",messages:t,uprd:v.user_polling_renew_delay}),delete e.longpollResponse}else n("wanted to flush but no longpoll available");else n("wanted to flush but buffer is empty")}function m(e,t){clearTimeout(e.DCTimeout);var o=(t||d)+v.user_polling_renew_delay;e.DCTimeout=setTimeout(function(){e.longpollResponse&&(n("warning! old longpoll rsponse left unhandled, client ID: "+e.ID),e.longpollResponseDC&&e.longpollResponse.removeListener("close",e.longpollResponseDC),e.longpollResponse.statusCode=444,e.longpollResponse.write("444 Disconnected by server."),e.longpollResponse.end(),delete e.longpollResponse),clearTimeout(e.longpollResponseTimeout),n(" >>> client disconnected: "+e.ID),y.clientsConnected=--O,delete y.clients[e.ID],r(),e.socket.emit("disconnect")},o)}var v={user_polling_renew_delay:0,longpoll_renew_interval:a};(o=o||{}).enableCC=o.enableCC||!1,o.user_delay||(o.user_delay=function(e){if(e<20)return u;return 10*Math.floor(Math.pow(e,1.15))}),o.renew_interval||(o.renew_interval=function(e){if(e<20)return a;var t=10*Math.floor(Math.pow(e,1.15));return a-t});var w=e("fs");e("path");!function(e){if("function"==typeof e)throw new Error('You are probably trying to attach kiite.io to an expressmiddleware function. Pass in a http.Server instance.\n\n example: \n var app = require( "express" )()\n var srv = require( "http" ).createServer( app )\n var kiite = require( "kiite" )( srv )\n');var t=e.listeners("request").slice(0);e.removeAllListeners("request"),e.on("request",function(o,a){if(0===o.url.indexOf("/kiite.js")||0===o.url.indexOf("/kiite.min.js"))"OPTIONS"===o.method?f(0,a):(a.setHeader("Access-Control-Allow-Origin","*"),w.readFile(__filename,function(e,t){a.statusCode=200,a.setHeader("Content-Type","text/html"),a.setHeader("Content-Length",t.length),a.write(t),a.end()}));else if(0===o.url.indexOf("/kiite.io"))"OPTIONS"===o.method?f(0,a):(a.setHeader("Access-Control-Allow-Origin","*"),function(e,t){n("[middle], method: "+e.method);var o=0,a=[];e.on("error",function(e){console.error(e.stack)}),e.on("data",function(e){o+=e.length,a.push(e)}),e.on("end",function(){a=Buffer.concat(a).toString("utf8"),function(e,t,o){try{var a=JSON.parse(o),l=e.connection.remoteAddress,c=e.headers["user-agent"];"127.0.0.1"===l.slice(-"127.0.0.1".length)&&e.headers["x-forwarded-for"]&&(l=e.headers["x-forwarded-for"]);var u=a.ID;n(a);var d;if("string"==typeof u?d=y.clients[a.ID]:n("ID was not a string"),d)switch(d.ip!==l&&n("ip mismatch"),d.ua!==c&&n("ua mismatch"),m(d),d.longpollResponseDC=function(){delete d.longpollResponseDC,n(" CLOSE -- response stream closed unexpectedly "),"longpoll"===a.evt&&m(d,1500)},t.on("close",d.longpollResponseDC),n("existing client [ "+u+" ], evt: "+a.evt),d.last_message_time=Date.now(),a.evt){case"disconnect":n("disconnect evt "),m(d,1);break;case"longpoll":if(n("longpoll evt "),d.longpollResponse)return n("duplicate longpolls received from the same client"),g(t,{evt:"stop"});clearTimeout(d.longpollResponseTimeout),d.longpollResponse=t,d.longpollResponseTimeout=setTimeout(function(){n("requesting renew longpoll"),d.longpollResponseDC&&d.longpollResponse.removeListener("close",d.longpollResponseDC),g(d.longpollResponse,{evt:"renew",uprd:v.user_polling_renew_delay}),delete d.longpollResponse},v.longpoll_renew_interval),n("flushing"),h(d);break;case"messages":n("messages evt "),function(e,t,o){t.statusCode=200,t.end();for(var n=0;n<o.length;++n)e.socket.emit(o[n].evt,o[n].data)}(d,t,a.messages);break;default:n("unknown event: "+a.evt),n(o),t.statusCode=404,t.end()}else if("connect"===a.evt){n("new client [ "+(u=i())+" ]"),n("new client ip: "+l),m(d={ID:u,ip:l,ua:c,last_message_time:Date.now(),buffer:[],request:e}),y.clients[u]=d,g(t,{evt:"connected",ID:u,uprd:v.user_polling_renew_delay});var f=s();d.socket=f;var w={ID:d.ID,on:f.on,emit:function(e,t){!function(e,t,o){e.buffer.push({evt:t,data:o}),h(e)}(d,e,t)},broadcast:function(e,t){p(e,t,d.ID)},request:e};y.clientsConnected=++O,r(),b.emit("connect",w),b.emit("connection",w)}else n("404 unknown user, unknown request data format (JSON error?)"),n(o),t.statusCode=404,t.end()}catch(e){console.error(e.stack),n("sending 400 Bad Request (JSON error?)"),t.statusCode=400,t.write("400 Bad Request"),t.end()}}(e,t,a)})}(o,a));else for(var l=0;l<t.length;++l)t[l].call(e,o,a)})}(t);var b=s(),y={on:b.on,emit:function(e,t){p(e,t)},clients:{}};y.broadcast=y.emit;var O=0;return y}},{"./ee.js":4,cuid:1,fs:void 0,path:void 0}]},{},[5])(5)});