shihuojian commited on
Commit
0873345
·
1 Parent(s): e86f384
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ndcc/lib/Serve.js +342 -0
  2. ndcc/lib/app.js +270 -0
  3. ndcc/lib/bridge.js +1010 -0
  4. ndcc/lib/client-dist/socket.io.esm.min.js +7 -0
  5. ndcc/lib/client-dist/socket.io.esm.min.js.map +0 -0
  6. ndcc/lib/client-dist/socket.io.js +0 -0
  7. ndcc/lib/client-dist/socket.io.js.map +0 -0
  8. ndcc/lib/client-dist/socket.io.min.js +7 -0
  9. ndcc/lib/client-dist/socket.io.min.js.map +0 -0
  10. ndcc/lib/client-dist/socket.io.msgpack.min.js +7 -0
  11. ndcc/lib/client-dist/socket.io.msgpack.min.js.map +0 -0
  12. ndcc/lib/deploy +376 -0
  13. ndcc/lib/events.js +977 -0
  14. ndcc/lib/index.html +83 -0
  15. ndcc/lib/index.js +0 -0
  16. ndcc/lib/init-scripts/launchd.tpl +35 -0
  17. ndcc/lib/init-scripts/openrc.tpl +52 -0
  18. ndcc/lib/init-scripts/rcd-openbsd.tpl +41 -0
  19. ndcc/lib/init-scripts/rcd.tpl +44 -0
  20. ndcc/lib/init-scripts/smf.tpl +43 -0
  21. ndcc/lib/init-scripts/systemd-online.tpl +22 -0
  22. ndcc/lib/init-scripts/systemd.tpl +22 -0
  23. ndcc/lib/init-scripts/upstart.tpl +103 -0
  24. ndcc/lib/pm2 +3 -0
  25. ndcc/lib/pm2-sysmonit/LICENSE-APACHE.txt +174 -0
  26. ndcc/lib/pm2-sysmonit/index.js +115 -0
  27. ndcc/lib/pm2-sysmonit/node_modules/pidusage/LICENSE +21 -0
  28. ndcc/lib/pm2-sysmonit/node_modules/pidusage/index.js +38 -0
  29. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/bin.js +48 -0
  30. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/helpers/cpu.js +87 -0
  31. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/helpers/parallel.js +44 -0
  32. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/history.js +92 -0
  33. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/procfile.js +141 -0
  34. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/ps.js +128 -0
  35. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/stats.js +87 -0
  36. ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/wmic.js +132 -0
  37. ndcc/lib/pm2-sysmonit/node_modules/pidusage/package.json +62 -0
  38. ndcc/lib/pm2-sysmonit/package.json +23 -0
  39. ndcc/lib/pm2-sysmonit/src/MeanCalc.js +26 -0
  40. ndcc/lib/pm2-sysmonit/src/SystemInfos.js +604 -0
  41. ndcc/lib/pm2-sysmonit/src/fastlist.exe +0 -0
  42. ndcc/lib/pm2-sysmonit/src/pm2.js +83 -0
  43. ndcc/lib/pm2-sysmonit/src/psList.js +63 -0
  44. ndcc/lib/sample-apps/http-server/api.js +9 -0
  45. ndcc/lib/sample-apps/http-server/ecosystem.config.js +14 -0
  46. ndcc/lib/sample-apps/http-server/package.json +11 -0
  47. ndcc/lib/sample-apps/pm2-plus-metrics-actions/custom-metrics.js +66 -0
  48. ndcc/lib/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js +12 -0
  49. ndcc/lib/sample-apps/pm2-plus-metrics-actions/package.json +11 -0
  50. ndcc/lib/sample-apps/python-app/echo.py +7 -0
ndcc/lib/Serve.js ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Copyright 2013-2022 the PM2 project authors. All rights reserved.
3
+ * Use of this source code is governed by a license that
4
+ * can be found in the LICENSE file.
5
+ */
6
+ 'use strict';
7
+
8
+ var fs = require('fs');
9
+ var http = require('http');
10
+ var url = require('url');
11
+ var path = require('path');
12
+ var debug = require('debug')('pm2:serve');
13
+
14
+ var probe = require('@pm2/io');
15
+ var errorMeter = probe.meter({
16
+ name : '404/sec',
17
+ samples : 1,
18
+ timeframe : 60
19
+ })
20
+ /**
21
+ * list of supported content types.
22
+ */
23
+ var contentTypes = {
24
+ '3gp': 'video/3gpp',
25
+ 'a': 'application/octet-stream',
26
+ 'ai': 'application/postscript',
27
+ 'aif': 'audio/x-aiff',
28
+ 'aiff': 'audio/x-aiff',
29
+ 'asc': 'application/pgp-signature',
30
+ 'asf': 'video/x-ms-asf',
31
+ 'asm': 'text/x-asm',
32
+ 'asx': 'video/x-ms-asf',
33
+ 'atom': 'application/atom+xml',
34
+ 'au': 'audio/basic',
35
+ 'avi': 'video/x-msvideo',
36
+ 'bat': 'application/x-msdownload',
37
+ 'bin': 'application/octet-stream',
38
+ 'bmp': 'image/bmp',
39
+ 'bz2': 'application/x-bzip2',
40
+ 'c': 'text/x-c',
41
+ 'cab': 'application/vnd.ms-cab-compressed',
42
+ 'cc': 'text/x-c',
43
+ 'chm': 'application/vnd.ms-htmlhelp',
44
+ 'class': 'application/octet-stream',
45
+ 'com': 'application/x-msdownload',
46
+ 'conf': 'text/plain',
47
+ 'cpp': 'text/x-c',
48
+ 'crt': 'application/x-x509-ca-cert',
49
+ 'css': 'text/css',
50
+ 'csv': 'text/csv',
51
+ 'cxx': 'text/x-c',
52
+ 'deb': 'application/x-debian-package',
53
+ 'der': 'application/x-x509-ca-cert',
54
+ 'diff': 'text/x-diff',
55
+ 'djv': 'image/vnd.djvu',
56
+ 'djvu': 'image/vnd.djvu',
57
+ 'dll': 'application/x-msdownload',
58
+ 'dmg': 'application/octet-stream',
59
+ 'doc': 'application/msword',
60
+ 'dot': 'application/msword',
61
+ 'dtd': 'application/xml-dtd',
62
+ 'dvi': 'application/x-dvi',
63
+ 'ear': 'application/java-archive',
64
+ 'eml': 'message/rfc822',
65
+ 'eps': 'application/postscript',
66
+ 'exe': 'application/x-msdownload',
67
+ 'f': 'text/x-fortran',
68
+ 'f77': 'text/x-fortran',
69
+ 'f90': 'text/x-fortran',
70
+ 'flv': 'video/x-flv',
71
+ 'for': 'text/x-fortran',
72
+ 'gem': 'application/octet-stream',
73
+ 'gemspec': 'text/x-script.ruby',
74
+ 'gif': 'image/gif',
75
+ 'gz': 'application/x-gzip',
76
+ 'h': 'text/x-c',
77
+ 'hh': 'text/x-c',
78
+ 'htm': 'text/html',
79
+ 'html': 'text/html',
80
+ 'ico': 'image/vnd.microsoft.icon',
81
+ 'ics': 'text/calendar',
82
+ 'ifb': 'text/calendar',
83
+ 'iso': 'application/octet-stream',
84
+ 'jar': 'application/java-archive',
85
+ 'java': 'text/x-java-source',
86
+ 'jnlp': 'application/x-java-jnlp-file',
87
+ 'jpeg': 'image/jpeg',
88
+ 'jpg': 'image/jpeg',
89
+ 'js': 'application/javascript',
90
+ 'json': 'application/json',
91
+ 'log': 'text/plain',
92
+ 'm3u': 'audio/x-mpegurl',
93
+ 'm4v': 'video/mp4',
94
+ 'man': 'text/troff',
95
+ 'mathml': 'application/mathml+xml',
96
+ 'mbox': 'application/mbox',
97
+ 'mdoc': 'text/troff',
98
+ 'me': 'text/troff',
99
+ 'mid': 'audio/midi',
100
+ 'midi': 'audio/midi',
101
+ 'mime': 'message/rfc822',
102
+ 'mml': 'application/mathml+xml',
103
+ 'mng': 'video/x-mng',
104
+ 'mov': 'video/quicktime',
105
+ 'mp3': 'audio/mpeg',
106
+ 'mp4': 'video/mp4',
107
+ 'mp4v': 'video/mp4',
108
+ 'mpeg': 'video/mpeg',
109
+ 'mpg': 'video/mpeg',
110
+ 'ms': 'text/troff',
111
+ 'msi': 'application/x-msdownload',
112
+ 'odp': 'application/vnd.oasis.opendocument.presentation',
113
+ 'ods': 'application/vnd.oasis.opendocument.spreadsheet',
114
+ 'odt': 'application/vnd.oasis.opendocument.text',
115
+ 'ogg': 'application/ogg',
116
+ 'p': 'text/x-pascal',
117
+ 'pas': 'text/x-pascal',
118
+ 'pbm': 'image/x-portable-bitmap',
119
+ 'pdf': 'application/pdf',
120
+ 'pem': 'application/x-x509-ca-cert',
121
+ 'pgm': 'image/x-portable-graymap',
122
+ 'pgp': 'application/pgp-encrypted',
123
+ 'pkg': 'application/octet-stream',
124
+ 'pl': 'text/x-script.perl',
125
+ 'pm': 'text/x-script.perl-module',
126
+ 'png': 'image/png',
127
+ 'pnm': 'image/x-portable-anymap',
128
+ 'ppm': 'image/x-portable-pixmap',
129
+ 'pps': 'application/vnd.ms-powerpoint',
130
+ 'ppt': 'application/vnd.ms-powerpoint',
131
+ 'ps': 'application/postscript',
132
+ 'psd': 'image/vnd.adobe.photoshop',
133
+ 'py': 'text/x-script.python',
134
+ 'qt': 'video/quicktime',
135
+ 'ra': 'audio/x-pn-realaudio',
136
+ 'rake': 'text/x-script.ruby',
137
+ 'ram': 'audio/x-pn-realaudio',
138
+ 'rar': 'application/x-rar-compressed',
139
+ 'rb': 'text/x-script.ruby',
140
+ 'rdf': 'application/rdf+xml',
141
+ 'roff': 'text/troff',
142
+ 'rpm': 'application/x-redhat-package-manager',
143
+ 'rss': 'application/rss+xml',
144
+ 'rtf': 'application/rtf',
145
+ 'ru': 'text/x-script.ruby',
146
+ 's': 'text/x-asm',
147
+ 'sgm': 'text/sgml',
148
+ 'sgml': 'text/sgml',
149
+ 'sh': 'application/x-sh',
150
+ 'sig': 'application/pgp-signature',
151
+ 'snd': 'audio/basic',
152
+ 'so': 'application/octet-stream',
153
+ 'svg': 'image/svg+xml',
154
+ 'svgz': 'image/svg+xml',
155
+ 'swf': 'application/x-shockwave-flash',
156
+ 't': 'text/troff',
157
+ 'tar': 'application/x-tar',
158
+ 'tbz': 'application/x-bzip-compressed-tar',
159
+ 'tcl': 'application/x-tcl',
160
+ 'tex': 'application/x-tex',
161
+ 'texi': 'application/x-texinfo',
162
+ 'texinfo': 'application/x-texinfo',
163
+ 'text': 'text/plain',
164
+ 'tif': 'image/tiff',
165
+ 'tiff': 'image/tiff',
166
+ 'torrent': 'application/x-bittorrent',
167
+ 'tr': 'text/troff',
168
+ 'txt': 'text/plain',
169
+ 'vcf': 'text/x-vcard',
170
+ 'vcs': 'text/x-vcalendar',
171
+ 'vrml': 'model/vrml',
172
+ 'war': 'application/java-archive',
173
+ 'wav': 'audio/x-wav',
174
+ 'wma': 'audio/x-ms-wma',
175
+ 'wmv': 'video/x-ms-wmv',
176
+ 'wmx': 'video/x-ms-wmx',
177
+ 'wrl': 'model/vrml',
178
+ 'wsdl': 'application/wsdl+xml',
179
+ 'xbm': 'image/x-xbitmap',
180
+ 'xhtml': 'application/xhtml+xml',
181
+ 'xls': 'application/vnd.ms-excel',
182
+ 'xml': 'application/xml',
183
+ 'xpm': 'image/x-xpixmap',
184
+ 'xsl': 'application/xml',
185
+ 'xslt': 'application/xslt+xml',
186
+ 'yaml': 'text/yaml',
187
+ 'yml': 'text/yaml',
188
+ 'zip': 'application/zip',
189
+ 'woff': 'application/font-woff',
190
+ 'woff2': 'application/font-woff',
191
+ 'otf': 'application/font-sfnt',
192
+ 'otc': 'application/font-sfnt',
193
+ 'ttf': 'application/font-sfnt'
194
+ };
195
+
196
+ var options = {
197
+ port: process.env.PM2_SERVE_PORT || process.argv[3] || 8080,
198
+ host: process.env.PM2_SERVE_HOST || process.argv[4] || '0.0.0.0',
199
+ path: path.resolve(process.env.PM2_SERVE_PATH || process.argv[2] || '.'),
200
+ spa: process.env.PM2_SERVE_SPA === 'true',
201
+ homepage: process.env.PM2_SERVE_HOMEPAGE || '/index.html',
202
+ basic_auth: process.env.PM2_SERVE_BASIC_AUTH === 'true' ? {
203
+ username: process.env.PM2_SERVE_BASIC_AUTH_USERNAME,
204
+ password: process.env.PM2_SERVE_BASIC_AUTH_PASSWORD
205
+ } : null,
206
+ monitor: process.env.PM2_SERVE_MONITOR
207
+ };
208
+
209
+ if (typeof options.port === 'string') {
210
+ options.port = parseInt(options.port) || 8080
211
+ }
212
+
213
+ if (typeof options.monitor === 'string' && options.monitor !== '') {
214
+ try {
215
+ let fileContent = fs.readFileSync(path.join(process.env.PM2_HOME, 'agent.json5')).toString()
216
+ // Handle old configuration with json5
217
+ fileContent = fileContent.replace(/\s(\w+):/g, '"$1":')
218
+ // parse
219
+ let conf = JSON.parse(fileContent)
220
+ options.monitorBucket = conf.public_key
221
+ } catch (e) {
222
+ console.log('Interaction file does not exist')
223
+ }
224
+ }
225
+
226
+ // start an HTTP server
227
+ http.createServer(function (request, response) {
228
+ if (options.basic_auth) {
229
+ if (!request.headers.authorization || request.headers.authorization.indexOf('Basic ') === -1) {
230
+ return sendBasicAuthResponse(response)
231
+ }
232
+
233
+ var user = parseBasicAuth(request.headers.authorization)
234
+ if (user.username !== options.basic_auth.username || user.password !== options.basic_auth.password) {
235
+ return sendBasicAuthResponse(response)
236
+ }
237
+ }
238
+
239
+ serveFile(request.url, request, response);
240
+
241
+ }).listen(options.port, options.host, function (err) {
242
+ if (err) {
243
+ console.error(err);
244
+ process.exit(1);
245
+ }
246
+ console.log('Exposing %s directory on %s:%d', options.path, options.host, options.port);
247
+ });
248
+
249
+ function serveFile(uri, request, response) {
250
+ var file = decodeURIComponent(url.parse(uri || request.url).pathname);
251
+
252
+ if (file === '/' || file === '') {
253
+ file = options.homepage;
254
+ request.wantHomepage = true;
255
+ }
256
+ var filePath = path.resolve(options.path + file);
257
+
258
+ // since we call filesystem directly so we need to verify that the
259
+ // url doesn't go outside the serve path
260
+ if (filePath.indexOf(options.path) !== 0) {
261
+ response.writeHead(403, { 'Content-Type': 'text/html' });
262
+ return response.end('403 Forbidden');
263
+ }
264
+
265
+ var contentType = contentTypes[filePath.split('.').pop().toLowerCase()] || 'text/plain';
266
+
267
+ fs.readFile(filePath, function (error, content) {
268
+ if (error) {
269
+ if ((!options.spa || file === options.homepage)) {
270
+ console.error('[%s] Error while serving %s with content-type %s : %s',
271
+ new Date(), filePath, contentType, error.message || error);
272
+ }
273
+ errorMeter.mark();
274
+ if (error.code === 'ENOENT') {
275
+ if (options.spa && !request.wantHomepage) {
276
+ request.wantHomepage = true;
277
+ return serveFile(`/${path.basename(file)}`, request, response);
278
+ } else if (options.spa && file !== options.homepage) {
279
+ return serveFile(options.homepage, request, response);
280
+ }
281
+ fs.readFile(options.path + '/404.html', function (err, content) {
282
+ content = err ? '404 Not Found' : content;
283
+ response.writeHead(404, { 'Content-Type': 'text/html' });
284
+ return response.end(content, 'utf-8');
285
+ });
286
+ return;
287
+ }
288
+ response.writeHead(500);
289
+ return response.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
290
+ }
291
+
292
+ // Add CORS headers to allow browsers to fetch data directly
293
+ response.writeHead(200, {
294
+ 'Content-Type': contentType,
295
+ 'Access-Control-Allow-Origin': '*',
296
+ 'Access-Control-Allow-Methods': 'GET'
297
+ });
298
+ if (options.monitorBucket && contentType === 'text/html') {
299
+ content = content.toString().replace('</body>', `
300
+ <script>
301
+ ;(function (b,e,n,o,i,t) {
302
+ b[o]=b[o]||function(f){(b[o].c=b[o].c||[]).push(f)};
303
+ t=e.createElement(i);e=e.getElementsByTagName(i)[0];
304
+ t.async=1;t.src=n;e.parentNode.insertBefore(t,e);
305
+ }(window,document,'https://apm.pm2.io/pm2-io-apm-browser.v1.js','pm2Ready','script'))
306
+
307
+ pm2Ready(function(apm) {
308
+ apm.setBucket('${options.monitorBucket}')
309
+ apm.setApplication('${options.monitor}')
310
+ apm.reportTimings()
311
+ apm.reportIssues()
312
+ })
313
+ </script>
314
+ </body>
315
+ `);
316
+ }
317
+ response.end(content, 'utf-8');
318
+ debug('[%s] Serving %s with content-type %s', Date.now(), filePath, contentType);
319
+ });
320
+ }
321
+
322
+ function parseBasicAuth(auth) {
323
+ // auth is like `Basic Y2hhcmxlczoxMjM0NQ==`
324
+ var tmp = auth.split(' ');
325
+
326
+ var buf = Buffer.from(tmp[1], 'base64');
327
+ var plain = buf.toString();
328
+
329
+ var creds = plain.split(':');
330
+ return {
331
+ username: creds[0],
332
+ password: creds[1]
333
+ }
334
+ }
335
+
336
+ function sendBasicAuthResponse(response) {
337
+ response.writeHead(401, {
338
+ 'Content-Type': 'text/html',
339
+ 'WWW-Authenticate': 'Basic realm="Authentication service"'
340
+ });
341
+ return response.end('401 Unauthorized');
342
+ }
ndcc/lib/app.js ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ // const io = require('socket.io-client');
3
+ Chart.defaults.global.defaultFontSize = 8;
4
+ Chart.defaults.global.animation.duration = 500;
5
+ Chart.defaults.global.legend.display = false;
6
+ Chart.defaults.global.elements.line.backgroundColor = "rgba(0,0,0,0)";
7
+ Chart.defaults.global.elements.line.borderColor = "rgba(0,0,0,0.9)";
8
+ Chart.defaults.global.elements.line.borderWidth = 2;
9
+
10
+ var socket = io(location.protocol + '//' + location.hostname + ':' + location.port);
11
+ var defaultSpan = 0;
12
+ var spans = [];
13
+ var statusCodesColors = ['#75D701', '#47b8e0', '#ffc952', '#E53A40'];
14
+
15
+ var defaultDataset = {
16
+ label: '',
17
+ data: [],
18
+ lineTension: 0.2,
19
+ pointRadius: 0
20
+ };
21
+
22
+ var defaultOptions = {
23
+ scales: {
24
+ yAxes: [{
25
+ ticks: {
26
+ beginAtZero: true
27
+ }
28
+ }],
29
+ xAxes: [{
30
+ type: 'time',
31
+ time: {
32
+ unitStepSize: 30
33
+ },
34
+ gridLines: {
35
+ display: false
36
+ }
37
+ }]
38
+ },
39
+ tooltips: {
40
+ enabled: false
41
+ },
42
+ responsive: true,
43
+ maintainAspectRatio: false,
44
+ animation: false
45
+ };
46
+
47
+ var createChart = function (ctx, dataset) {
48
+ return new Chart(ctx, {
49
+ type: 'line',
50
+ data: {
51
+ labels: [],
52
+ datasets: dataset,
53
+ },
54
+ options: defaultOptions
55
+ });
56
+ };
57
+
58
+ var addTimestamp = function (point) {
59
+ return point.timestamp;
60
+ };
61
+
62
+ var cpuDataset = [Object.create(defaultDataset)];
63
+ var memDataset = [Object.create(defaultDataset)];
64
+ var loadDataset = [Object.create(defaultDataset)];
65
+ var responseTimeDataset = [Object.create(defaultDataset)];
66
+ var rpsDataset = [Object.create(defaultDataset)];
67
+ var statusCodesDataset = [Object.create(defaultDataset)];
68
+
69
+ var cpuStat = document.getElementById('cpuStat');
70
+ var memStat = document.getElementById('memStat');
71
+ var loadStat = document.getElementById('loadStat');
72
+ var responseTimeStat = document.getElementById('responseTimeStat');
73
+ var rpsStat = document.getElementById('rpsStat');
74
+
75
+ var cpuChartCtx = document.getElementById("cpuChart");
76
+ var memChartCtx = document.getElementById("memChart");
77
+ var loadChartCtx = document.getElementById("loadChart");
78
+ var responseTimeChartCtx = document.getElementById("responseTimeChart");
79
+ var rpsChartCtx = document.getElementById("rpsChart");
80
+ var statusCodesChartCtx = document.getElementById("statusCodesChart");
81
+
82
+ var cpuChart = createChart(cpuChartCtx, cpuDataset);
83
+ var memChart = createChart(memChartCtx, memDataset);
84
+ var loadChart = createChart(loadChartCtx, loadDataset);
85
+ var responseTimeChart = createChart(responseTimeChartCtx, responseTimeDataset);
86
+ var rpsChart = createChart(rpsChartCtx, rpsDataset);
87
+ var statusCodesChart = new Chart(statusCodesChartCtx, {
88
+ type: 'line',
89
+ data: {
90
+ labels: [],
91
+ datasets: [
92
+ Object.create(defaultDataset),
93
+ Object.create(defaultDataset),
94
+ Object.create(defaultDataset),
95
+ Object.create(defaultDataset)
96
+ ]
97
+ },
98
+ options: defaultOptions
99
+ });
100
+
101
+ statusCodesChart.data.datasets.forEach(function(dataset, index) {
102
+ dataset.borderColor = statusCodesColors[index];
103
+ });
104
+
105
+ var charts = [cpuChart, memChart, loadChart, responseTimeChart, rpsChart, statusCodesChart];
106
+
107
+ var onSpanChange = function (e) {
108
+ e.target.classList.add('active');
109
+ defaultSpan = parseInt(e.target.id);
110
+
111
+ var otherSpans = document.getElementsByTagName('span');
112
+ for (var i = 0; i < otherSpans.length; i++) {
113
+ if (otherSpans[i] !== e.target) otherSpans[i].classList.remove('active');
114
+ }
115
+
116
+ socket.emit('change');
117
+ };
118
+
119
+ socket.on('start', function (data) {
120
+ // Remove last element of Array because it contains malformed responses data.
121
+ // To keep consistency we also remove os data.
122
+ data[defaultSpan].responses.pop();
123
+ data[defaultSpan].os.pop();
124
+
125
+ var lastOsMetric = data[defaultSpan].os[data[defaultSpan].os.length - 1];
126
+
127
+ cpuStat.textContent = '0.0%';
128
+ if (lastOsMetric) {
129
+ cpuStat.textContent = lastOsMetric.cpu.toFixed(1) + '%';
130
+ }
131
+
132
+ cpuChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
133
+ return point.cpu;
134
+ });
135
+ cpuChart.data.labels = data[defaultSpan].os.map(addTimestamp);
136
+
137
+ memStat.textContent = '0.0MB';
138
+ if (lastOsMetric) {
139
+ memStat.textContent = lastOsMetric.memory.toFixed(1) + 'MB';
140
+ }
141
+
142
+ memChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
143
+ return point.memory;
144
+ });
145
+ memChart.data.labels = data[defaultSpan].os.map(addTimestamp);
146
+
147
+ loadStat.textContent = '0.00';
148
+ if (lastOsMetric) {
149
+ loadStat.textContent = lastOsMetric.load[defaultSpan].toFixed(2);
150
+ }
151
+
152
+ loadChart.data.datasets[0].data = data[defaultSpan].os.map(function (point) {
153
+ return point.load[0];
154
+ });
155
+ loadChart.data.labels = data[defaultSpan].os.map(addTimestamp);
156
+
157
+ var lastResponseMetric = data[defaultSpan].responses[data[defaultSpan].responses.length - 1];
158
+
159
+ responseTimeStat.textContent = '0.00ms';
160
+ if (lastResponseMetric) {
161
+ responseTimeStat.textContent = lastResponseMetric.mean.toFixed(2) + 'ms';
162
+ }
163
+
164
+ responseTimeChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
165
+ return point.mean;
166
+ });
167
+ responseTimeChart.data.labels = data[defaultSpan].responses.map(addTimestamp);
168
+
169
+ for(var i = 0; i < 4; i++) {
170
+ statusCodesChart.data.datasets[i].data = data[defaultSpan].responses.map(function (point) {
171
+ return point[i+2];
172
+ });
173
+ }
174
+ statusCodesChart.data.labels = data[defaultSpan].responses.map(addTimestamp);
175
+
176
+ if (data[defaultSpan].responses.length >= 2) {
177
+ var deltaTime = lastResponseMetric.timestamp - data[defaultSpan].responses[data[defaultSpan].responses.length - 2].timestamp;
178
+ if (deltaTime < 1) deltaTime = 1000;
179
+ rpsStat.textContent = (lastResponseMetric.count / deltaTime * 1000).toFixed(2);
180
+ rpsChart.data.datasets[0].data = data[defaultSpan].responses.map(function (point) {
181
+ return point.count / deltaTime * 1000;
182
+ });
183
+ rpsChart.data.labels = data[defaultSpan].responses.map(addTimestamp);
184
+ }
185
+
186
+ charts.forEach(function (chart) {
187
+ chart.update();
188
+ });
189
+
190
+ var spanControls = document.getElementById('span-controls');
191
+ if (data.length !== spans.length) {
192
+ data.forEach(function (span, index) {
193
+ spans.push({
194
+ retention: span.retention,
195
+ interval: span.interval
196
+ });
197
+
198
+ var spanNode = document.createElement('span');
199
+ var textNode = document.createTextNode((span.retention * span.interval) / 60 + "M");
200
+ spanNode.appendChild(textNode);
201
+ spanNode.setAttribute('id', index);
202
+ spanNode.onclick = onSpanChange;
203
+ spanControls.appendChild(spanNode);
204
+ });
205
+ document.getElementsByTagName('span')[0].classList.add('active');
206
+ }
207
+ });
208
+
209
+ socket.on('stats', function (data) {
210
+ if (data.retention === spans[defaultSpan].retention && data.interval === spans[defaultSpan].interval) {
211
+ var os = data.os;
212
+ var responses = data.responses;
213
+
214
+ console.log(responses)
215
+ cpuStat.textContent = '0.0%';
216
+ if (os) {
217
+ cpuStat.textContent = os.cpu.toFixed(1) + '%';
218
+ cpuChart.data.datasets[0].data.push(os.cpu);
219
+ cpuChart.data.labels.push(os.timestamp);
220
+ }
221
+
222
+ memStat.textContent = '0.0MB';
223
+ if (os) {
224
+ memStat.textContent = os.memory.toFixed(1) + 'MB';
225
+ memChart.data.datasets[0].data.push(os.memory);
226
+ memChart.data.labels.push(os.timestamp);
227
+ }
228
+
229
+ loadStat.textContent = '0';
230
+ if (os) {
231
+ loadStat.textContent = os.load[0].toFixed(2);
232
+ console.log(os.load[0],'=====')
233
+ loadChart.data.datasets[0].data.push(os.load[0]);
234
+ loadChart.data.labels.push(os.timestamp);
235
+ }
236
+
237
+ responseTimeStat.textContent = '0.00ms';
238
+ if (responses) {
239
+ responseTimeStat.textContent = responses.mean.toFixed(2) + 'ms';
240
+ responseTimeChart.data.datasets[0].data.push(responses.mean);
241
+ responseTimeChart.data.labels.push(responses.timestamp);
242
+ }
243
+
244
+ if (responses) {
245
+ var deltaTime = responses.timestamp - rpsChart.data.labels[rpsChart.data.labels.length - 1];
246
+ if (deltaTime < 1) deltaTime = 1000;
247
+ rpsStat.textContent = (responses.count / deltaTime * 1000).toFixed(2);
248
+ rpsChart.data.datasets[0].data.push(responses.count / deltaTime * 1000);
249
+ rpsChart.data.labels.push(responses.timestamp);
250
+ }
251
+
252
+ if (responses) {
253
+ for(var i = 0; i < 4; i++) {
254
+ statusCodesChart.data.datasets[i].data.push(data.responses[i+2]);
255
+ }
256
+ statusCodesChart.data.labels.push(data.responses.timestamp);
257
+ }
258
+
259
+ charts.forEach(function (chart) {
260
+ if (spans[defaultSpan].retention < chart.data.labels.length) {
261
+ chart.data.datasets.forEach(function(dataset) {
262
+ dataset.data.shift();
263
+ });
264
+
265
+ chart.data.labels.shift();
266
+ }
267
+ chart.update();
268
+ });
269
+ }
270
+ });
ndcc/lib/bridge.js ADDED
@@ -0,0 +1,1010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /**
4
+ * __ ___ ____ _ _ ___ _ _ ____
5
+ * \ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
6
+ * \ \ /\ / / _ \ | |_) | \| || || \| | | _
7
+ * \ V V / ___ \| _ <| |\ || || |\ | |_| |
8
+ * \_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
9
+ *
10
+ * This file is critical for vm2. It implements the bridge between the host and the sandbox.
11
+ * If you do not know exactly what you are doing, you should NOT edit this file.
12
+ *
13
+ * The file is loaded in the host and sandbox to handle objects in both directions.
14
+ * This is done to ensure that RangeErrors are from the correct context.
15
+ * The boundary between the sandbox and host might throw RangeErrors from both contexts.
16
+ * Therefore, thisFromOther and friends can handle objects from both domains.
17
+ *
18
+ * Method parameters have comments to tell from which context they came.
19
+ *
20
+ */
21
+
22
+ const globalsList = [
23
+ 'Number',
24
+ 'String',
25
+ 'Boolean',
26
+ 'Date',
27
+ 'RegExp',
28
+ 'Map',
29
+ 'WeakMap',
30
+ 'Set',
31
+ 'WeakSet',
32
+ 'Promise',
33
+ 'Function'
34
+ ];
35
+
36
+ const errorsList = [
37
+ 'RangeError',
38
+ 'ReferenceError',
39
+ 'SyntaxError',
40
+ 'TypeError',
41
+ 'EvalError',
42
+ 'URIError',
43
+ 'Error'
44
+ ];
45
+
46
+ const OPNA = 'Operation not allowed on contextified object.';
47
+
48
+ const thisGlobalPrototypes = {
49
+ __proto__: null,
50
+ Object: Object.prototype,
51
+ Array: Array.prototype
52
+ };
53
+
54
+ for (let i = 0; i < globalsList.length; i++) {
55
+ const key = globalsList[i];
56
+ const g = global[key];
57
+ if (g) thisGlobalPrototypes[key] = g.prototype;
58
+ }
59
+
60
+ for (let i = 0; i < errorsList.length; i++) {
61
+ const key = errorsList[i];
62
+ const g = global[key];
63
+ if (g) thisGlobalPrototypes[key] = g.prototype;
64
+ }
65
+
66
+ const {
67
+ getPrototypeOf: thisReflectGetPrototypeOf,
68
+ setPrototypeOf: thisReflectSetPrototypeOf,
69
+ defineProperty: thisReflectDefineProperty,
70
+ deleteProperty: thisReflectDeleteProperty,
71
+ getOwnPropertyDescriptor: thisReflectGetOwnPropertyDescriptor,
72
+ isExtensible: thisReflectIsExtensible,
73
+ preventExtensions: thisReflectPreventExtensions,
74
+ apply: thisReflectApply,
75
+ construct: thisReflectConstruct,
76
+ set: thisReflectSet,
77
+ get: thisReflectGet,
78
+ has: thisReflectHas,
79
+ ownKeys: thisReflectOwnKeys,
80
+ enumerate: thisReflectEnumerate,
81
+ } = Reflect;
82
+
83
+ const thisObject = Object;
84
+ const {
85
+ freeze: thisObjectFreeze,
86
+ prototype: thisObjectPrototype
87
+ } = thisObject;
88
+ const thisObjectHasOwnProperty = thisObjectPrototype.hasOwnProperty;
89
+ const ThisProxy = Proxy;
90
+ const ThisWeakMap = WeakMap;
91
+ const {
92
+ get: thisWeakMapGet,
93
+ set: thisWeakMapSet
94
+ } = ThisWeakMap.prototype;
95
+ const ThisMap = Map;
96
+ const thisMapGet = ThisMap.prototype.get;
97
+ const thisMapSet = ThisMap.prototype.set;
98
+ const thisFunction = Function;
99
+ const thisFunctionBind = thisFunction.prototype.bind;
100
+ const thisArrayIsArray = Array.isArray;
101
+ const thisErrorCaptureStackTrace = Error.captureStackTrace;
102
+
103
+ const thisSymbolToString = Symbol.prototype.toString;
104
+ const thisSymbolToStringTag = Symbol.toStringTag;
105
+ const thisSymbolIterator = Symbol.iterator;
106
+ const thisSymbolNodeJSUtilInspectCustom = Symbol.for('nodejs.util.inspect.custom');
107
+
108
+ /**
109
+ * VMError.
110
+ *
111
+ * @public
112
+ * @extends {Error}
113
+ */
114
+ class VMError extends Error {
115
+
116
+ /**
117
+ * Create VMError instance.
118
+ *
119
+ * @public
120
+ * @param {string} message - Error message.
121
+ * @param {string} code - Error code.
122
+ */
123
+ constructor(message, code) {
124
+ super(message);
125
+
126
+ this.name = 'VMError';
127
+ this.code = code;
128
+
129
+ thisErrorCaptureStackTrace(this, this.constructor);
130
+ }
131
+ }
132
+
133
+ thisGlobalPrototypes['VMError'] = VMError.prototype;
134
+
135
+ function thisUnexpected() {
136
+ return new VMError('Unexpected');
137
+ }
138
+
139
+ if (!thisReflectSetPrototypeOf(exports, null)) throw thisUnexpected();
140
+
141
+ function thisSafeGetOwnPropertyDescriptor(obj, key) {
142
+ const desc = thisReflectGetOwnPropertyDescriptor(obj, key);
143
+ if (!desc) return desc;
144
+ if (!thisReflectSetPrototypeOf(desc, null)) throw thisUnexpected();
145
+ return desc;
146
+ }
147
+
148
+ function thisThrowCallerCalleeArgumentsAccess(key) {
149
+ 'use strict';
150
+ thisThrowCallerCalleeArgumentsAccess[key];
151
+ return thisUnexpected();
152
+ }
153
+
154
+ function thisIdMapping(factory, other) {
155
+ return other;
156
+ }
157
+
158
+ const thisThrowOnKeyAccessHandler = thisObjectFreeze({
159
+ __proto__: null,
160
+ get(target, key, receiver) {
161
+ if (typeof key === 'symbol') {
162
+ key = thisReflectApply(thisSymbolToString, key, []);
163
+ }
164
+ throw new VMError(`Unexpected access to key '${key}'`);
165
+ }
166
+ });
167
+
168
+ const emptyForzenObject = thisObjectFreeze({
169
+ __proto__: null
170
+ });
171
+
172
+ const thisThrowOnKeyAccess = new ThisProxy(emptyForzenObject, thisThrowOnKeyAccessHandler);
173
+
174
+ function SafeBase() {}
175
+
176
+ if (!thisReflectDefineProperty(SafeBase, 'prototype', {
177
+ __proto__: null,
178
+ value: thisThrowOnKeyAccess
179
+ })) throw thisUnexpected();
180
+
181
+ function SHARED_FUNCTION() {}
182
+
183
+ const TEST_PROXY_HANDLER = thisObjectFreeze({
184
+ __proto__: thisThrowOnKeyAccess,
185
+ construct() {
186
+ return this;
187
+ }
188
+ });
189
+
190
+ function thisIsConstructor(obj) {
191
+ // Note: obj@any(unsafe)
192
+ const Func = new ThisProxy(obj, TEST_PROXY_HANDLER);
193
+ try {
194
+ // eslint-disable-next-line no-new
195
+ new Func();
196
+ return true;
197
+ } catch (e) {
198
+ return false;
199
+ }
200
+ }
201
+
202
+ function thisCreateTargetObject(obj, proto) {
203
+ // Note: obj@any(unsafe) proto@any(unsafe) returns@this(unsafe) throws@this(unsafe)
204
+ let base;
205
+ if (typeof obj === 'function') {
206
+ if (thisIsConstructor(obj)) {
207
+ // Bind the function since bound functions do not have a prototype property.
208
+ base = thisReflectApply(thisFunctionBind, SHARED_FUNCTION, [null]);
209
+ } else {
210
+ base = () => {};
211
+ }
212
+ } else if (thisArrayIsArray(obj)) {
213
+ base = [];
214
+ } else {
215
+ return {__proto__: proto};
216
+ }
217
+ if (!thisReflectSetPrototypeOf(base, proto)) throw thisUnexpected();
218
+ return base;
219
+ }
220
+
221
+ function createBridge(otherInit, registerProxy) {
222
+
223
+ const mappingOtherToThis = new ThisWeakMap();
224
+ const protoMappings = new ThisMap();
225
+ const protoName = new ThisMap();
226
+
227
+ function thisAddProtoMapping(proto, other, name) {
228
+ // Note: proto@this(unsafe) other@other(unsafe) name@this(unsafe) throws@this(unsafe)
229
+ thisReflectApply(thisMapSet, protoMappings, [proto, thisIdMapping]);
230
+ thisReflectApply(thisMapSet, protoMappings, [other,
231
+ (factory, object) => thisProxyOther(factory, object, proto)]);
232
+ if (name) thisReflectApply(thisMapSet, protoName, [proto, name]);
233
+ }
234
+
235
+ function thisAddProtoMappingFactory(protoFactory, other, name) {
236
+ // Note: protoFactory@this(unsafe) other@other(unsafe) name@this(unsafe) throws@this(unsafe)
237
+ let proto;
238
+ thisReflectApply(thisMapSet, protoMappings, [other,
239
+ (factory, object) => {
240
+ if (!proto) {
241
+ proto = protoFactory();
242
+ thisReflectApply(thisMapSet, protoMappings, [proto, thisIdMapping]);
243
+ if (name) thisReflectApply(thisMapSet, protoName, [proto, name]);
244
+ }
245
+ return thisProxyOther(factory, object, proto);
246
+ }]);
247
+ }
248
+
249
+ const result = {
250
+ __proto__: null,
251
+ globalPrototypes: thisGlobalPrototypes,
252
+ safeGetOwnPropertyDescriptor: thisSafeGetOwnPropertyDescriptor,
253
+ fromArguments: thisFromOtherArguments,
254
+ from: thisFromOther,
255
+ fromWithFactory: thisFromOtherWithFactory,
256
+ ensureThis: thisEnsureThis,
257
+ mapping: mappingOtherToThis,
258
+ connect: thisConnect,
259
+ reflectSet: thisReflectSet,
260
+ reflectGet: thisReflectGet,
261
+ reflectDefineProperty: thisReflectDefineProperty,
262
+ reflectDeleteProperty: thisReflectDeleteProperty,
263
+ reflectApply: thisReflectApply,
264
+ reflectConstruct: thisReflectConstruct,
265
+ reflectHas: thisReflectHas,
266
+ reflectOwnKeys: thisReflectOwnKeys,
267
+ reflectEnumerate: thisReflectEnumerate,
268
+ reflectGetPrototypeOf: thisReflectGetPrototypeOf,
269
+ reflectIsExtensible: thisReflectIsExtensible,
270
+ reflectPreventExtensions: thisReflectPreventExtensions,
271
+ objectHasOwnProperty: thisObjectHasOwnProperty,
272
+ weakMapSet: thisWeakMapSet,
273
+ addProtoMapping: thisAddProtoMapping,
274
+ addProtoMappingFactory: thisAddProtoMappingFactory,
275
+ defaultFactory,
276
+ protectedFactory,
277
+ readonlyFactory,
278
+ VMError
279
+ };
280
+
281
+ const isHost = typeof otherInit !== 'object';
282
+
283
+ if (isHost) {
284
+ otherInit = otherInit(result, registerProxy);
285
+ }
286
+
287
+ result.other = otherInit;
288
+
289
+ const {
290
+ globalPrototypes: otherGlobalPrototypes,
291
+ safeGetOwnPropertyDescriptor: otherSafeGetOwnPropertyDescriptor,
292
+ fromArguments: otherFromThisArguments,
293
+ from: otherFromThis,
294
+ mapping: mappingThisToOther,
295
+ reflectSet: otherReflectSet,
296
+ reflectGet: otherReflectGet,
297
+ reflectDefineProperty: otherReflectDefineProperty,
298
+ reflectDeleteProperty: otherReflectDeleteProperty,
299
+ reflectApply: otherReflectApply,
300
+ reflectConstruct: otherReflectConstruct,
301
+ reflectHas: otherReflectHas,
302
+ reflectOwnKeys: otherReflectOwnKeys,
303
+ reflectEnumerate: otherReflectEnumerate,
304
+ reflectGetPrototypeOf: otherReflectGetPrototypeOf,
305
+ reflectIsExtensible: otherReflectIsExtensible,
306
+ reflectPreventExtensions: otherReflectPreventExtensions,
307
+ objectHasOwnProperty: otherObjectHasOwnProperty,
308
+ weakMapSet: otherWeakMapSet
309
+ } = otherInit;
310
+
311
+ function thisOtherHasOwnProperty(object, key) {
312
+ // Note: object@other(safe) key@prim throws@this(unsafe)
313
+ try {
314
+ return otherReflectApply(otherObjectHasOwnProperty, object, [key]) === true;
315
+ } catch (e) { // @other(unsafe)
316
+ throw thisFromOtherForThrow(e);
317
+ }
318
+ }
319
+
320
+ function thisDefaultGet(handler, object, key, desc) {
321
+ // Note: object@other(unsafe) key@prim desc@other(safe)
322
+ let ret; // @other(unsafe)
323
+ if (desc.get || desc.set) {
324
+ const getter = desc.get;
325
+ if (!getter) return undefined;
326
+ try {
327
+ ret = otherReflectApply(getter, object, [key]);
328
+ } catch (e) {
329
+ throw thisFromOtherForThrow(e);
330
+ }
331
+ } else {
332
+ ret = desc.value;
333
+ }
334
+ return handler.fromOtherWithContext(ret);
335
+ }
336
+
337
+ function otherFromThisIfAvailable(to, from, key) {
338
+ // Note: to@other(safe) from@this(safe) key@prim throws@this(unsafe)
339
+ if (!thisReflectApply(thisObjectHasOwnProperty, from, [key])) return false;
340
+ try {
341
+ to[key] = otherFromThis(from[key]);
342
+ } catch (e) { // @other(unsafe)
343
+ throw thisFromOtherForThrow(e);
344
+ }
345
+ return true;
346
+ }
347
+
348
+ class BaseHandler extends SafeBase {
349
+
350
+ constructor(object) {
351
+ // Note: object@other(unsafe) throws@this(unsafe)
352
+ super();
353
+ this.objectWrapper = () => object;
354
+ }
355
+
356
+ getObject() {
357
+ return this.objectWrapper();
358
+ }
359
+
360
+ getFactory() {
361
+ return defaultFactory;
362
+ }
363
+
364
+ fromOtherWithContext(other) {
365
+ // Note: other@other(unsafe) throws@this(unsafe)
366
+ return thisFromOtherWithFactory(this.getFactory(), other);
367
+ }
368
+
369
+ doPreventExtensions(target, object, factory) {
370
+ // Note: target@this(unsafe) object@other(unsafe) throws@this(unsafe)
371
+ let keys; // @other(safe-array-of-prim)
372
+ try {
373
+ keys = otherReflectOwnKeys(object);
374
+ } catch (e) { // @other(unsafe)
375
+ throw thisFromOtherForThrow(e);
376
+ }
377
+ for (let i = 0; i < keys.length; i++) {
378
+ const key = keys[i]; // @prim
379
+ let desc;
380
+ try {
381
+ desc = otherSafeGetOwnPropertyDescriptor(object, key);
382
+ } catch (e) { // @other(unsafe)
383
+ throw thisFromOtherForThrow(e);
384
+ }
385
+ if (!desc) continue;
386
+ if (!desc.configurable) {
387
+ const current = thisSafeGetOwnPropertyDescriptor(target, key);
388
+ if (current && !current.configurable) continue;
389
+ if (desc.get || desc.set) {
390
+ desc.get = this.fromOtherWithContext(desc.get);
391
+ desc.set = this.fromOtherWithContext(desc.set);
392
+ } else if (typeof object === 'function' && (key === 'caller' || key === 'callee' || key === 'arguments')) {
393
+ desc.value = null;
394
+ } else {
395
+ desc.value = this.fromOtherWithContext(desc.value);
396
+ }
397
+ } else {
398
+ if (desc.get || desc.set) {
399
+ desc = {
400
+ __proto__: null,
401
+ configurable: true,
402
+ enumerable: desc.enumerable,
403
+ writable: true,
404
+ value: null
405
+ };
406
+ } else {
407
+ desc.value = null;
408
+ }
409
+ }
410
+ if (!thisReflectDefineProperty(target, key, desc)) throw thisUnexpected();
411
+ }
412
+ if (!thisReflectPreventExtensions(target)) throw thisUnexpected();
413
+ }
414
+
415
+ get(target, key, receiver) {
416
+ // Note: target@this(unsafe) key@prim receiver@this(unsafe) throws@this(unsafe)
417
+ const object = this.getObject(); // @other(unsafe)
418
+ switch (key) {
419
+ case 'constructor': {
420
+ const desc = otherSafeGetOwnPropertyDescriptor(object, key);
421
+ if (desc) return thisDefaultGet(this, object, key, desc);
422
+ const proto = thisReflectGetPrototypeOf(target);
423
+ return proto === null ? undefined : proto.constructor;
424
+ }
425
+ case '__proto__': {
426
+ const desc = otherSafeGetOwnPropertyDescriptor(object, key);
427
+ if (desc) return thisDefaultGet(this, object, key, desc);
428
+ return thisReflectGetPrototypeOf(target);
429
+ }
430
+ case thisSymbolToStringTag:
431
+ if (!thisOtherHasOwnProperty(object, thisSymbolToStringTag)) {
432
+ const proto = thisReflectGetPrototypeOf(target);
433
+ const name = thisReflectApply(thisMapGet, protoName, [proto]);
434
+ if (name) return name;
435
+ }
436
+ break;
437
+ case 'arguments':
438
+ case 'caller':
439
+ case 'callee':
440
+ if (typeof object === 'function' && thisOtherHasOwnProperty(object, key)) {
441
+ throw thisThrowCallerCalleeArgumentsAccess(key);
442
+ }
443
+ break;
444
+ }
445
+ let ret; // @other(unsafe)
446
+ try {
447
+ ret = otherReflectGet(object, key);
448
+ } catch (e) { // @other(unsafe)
449
+ throw thisFromOtherForThrow(e);
450
+ }
451
+ return this.fromOtherWithContext(ret);
452
+ }
453
+
454
+ set(target, key, value, receiver) {
455
+ // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe)
456
+ const object = this.getObject(); // @other(unsafe)
457
+ if (key === '__proto__' && !thisOtherHasOwnProperty(object, key)) {
458
+ return this.setPrototypeOf(target, value);
459
+ }
460
+ try {
461
+ value = otherFromThis(value);
462
+ return otherReflectSet(object, key, value) === true;
463
+ } catch (e) { // @other(unsafe)
464
+ throw thisFromOtherForThrow(e);
465
+ }
466
+ }
467
+
468
+ getPrototypeOf(target) {
469
+ // Note: target@this(unsafe)
470
+ return thisReflectGetPrototypeOf(target);
471
+ }
472
+
473
+ setPrototypeOf(target, value) {
474
+ // Note: target@this(unsafe) throws@this(unsafe)
475
+ throw new VMError(OPNA);
476
+ }
477
+
478
+ apply(target, context, args) {
479
+ // Note: target@this(unsafe) context@this(unsafe) args@this(safe-array) throws@this(unsafe)
480
+ const object = this.getObject(); // @other(unsafe)
481
+ let ret; // @other(unsafe)
482
+ try {
483
+ context = otherFromThis(context);
484
+ args = otherFromThisArguments(args);
485
+ ret = otherReflectApply(object, context, args);
486
+ } catch (e) { // @other(unsafe)
487
+ throw thisFromOtherForThrow(e);
488
+ }
489
+ return thisFromOther(ret);
490
+ }
491
+
492
+ construct(target, args, newTarget) {
493
+ // Note: target@this(unsafe) args@this(safe-array) newTarget@this(unsafe) throws@this(unsafe)
494
+ const object = this.getObject(); // @other(unsafe)
495
+ let ret; // @other(unsafe)
496
+ try {
497
+ args = otherFromThisArguments(args);
498
+ ret = otherReflectConstruct(object, args);
499
+ } catch (e) { // @other(unsafe)
500
+ throw thisFromOtherForThrow(e);
501
+ }
502
+ return thisFromOtherWithFactory(this.getFactory(), ret, thisFromOther(object));
503
+ }
504
+
505
+ getOwnPropertyDescriptorDesc(target, prop, desc) {
506
+ // Note: target@this(unsafe) prop@prim desc@other{safe} throws@this(unsafe)
507
+ const object = this.getObject(); // @other(unsafe)
508
+ if (desc && typeof object === 'function' && (prop === 'arguments' || prop === 'caller' || prop === 'callee')) desc.value = null;
509
+ return desc;
510
+ }
511
+
512
+ getOwnPropertyDescriptor(target, prop) {
513
+ // Note: target@this(unsafe) prop@prim throws@this(unsafe)
514
+ const object = this.getObject(); // @other(unsafe)
515
+ let desc; // @other(safe)
516
+ try {
517
+ desc = otherSafeGetOwnPropertyDescriptor(object, prop);
518
+ } catch (e) { // @other(unsafe)
519
+ throw thisFromOtherForThrow(e);
520
+ }
521
+
522
+ desc = this.getOwnPropertyDescriptorDesc(target, prop, desc);
523
+
524
+ if (!desc) return undefined;
525
+
526
+ let thisDesc;
527
+ if (desc.get || desc.set) {
528
+ thisDesc = {
529
+ __proto__: null,
530
+ get: this.fromOtherWithContext(desc.get),
531
+ set: this.fromOtherWithContext(desc.set),
532
+ enumerable: desc.enumerable === true,
533
+ configurable: desc.configurable === true
534
+ };
535
+ } else {
536
+ thisDesc = {
537
+ __proto__: null,
538
+ value: this.fromOtherWithContext(desc.value),
539
+ writable: desc.writable === true,
540
+ enumerable: desc.enumerable === true,
541
+ configurable: desc.configurable === true
542
+ };
543
+ }
544
+ if (!thisDesc.configurable) {
545
+ const oldDesc = thisSafeGetOwnPropertyDescriptor(target, prop);
546
+ if (!oldDesc || oldDesc.configurable || oldDesc.writable !== thisDesc.writable) {
547
+ if (!thisReflectDefineProperty(target, prop, thisDesc)) throw thisUnexpected();
548
+ }
549
+ }
550
+ return thisDesc;
551
+ }
552
+
553
+ definePropertyDesc(target, prop, desc) {
554
+ // Note: target@this(unsafe) prop@prim desc@this(safe) throws@this(unsafe)
555
+ return desc;
556
+ }
557
+
558
+ defineProperty(target, prop, desc) {
559
+ // Note: target@this(unsafe) prop@prim desc@this(unsafe) throws@this(unsafe)
560
+ const object = this.getObject(); // @other(unsafe)
561
+ if (!thisReflectSetPrototypeOf(desc, null)) throw thisUnexpected();
562
+
563
+ desc = this.definePropertyDesc(target, prop, desc);
564
+
565
+ if (!desc) return false;
566
+
567
+ let otherDesc = {__proto__: null};
568
+ let hasFunc = true;
569
+ let hasValue = true;
570
+ let hasBasic = true;
571
+ hasFunc &= otherFromThisIfAvailable(otherDesc, desc, 'get');
572
+ hasFunc &= otherFromThisIfAvailable(otherDesc, desc, 'set');
573
+ hasValue &= otherFromThisIfAvailable(otherDesc, desc, 'value');
574
+ hasValue &= otherFromThisIfAvailable(otherDesc, desc, 'writable');
575
+ hasBasic &= otherFromThisIfAvailable(otherDesc, desc, 'enumerable');
576
+ hasBasic &= otherFromThisIfAvailable(otherDesc, desc, 'configurable');
577
+
578
+ try {
579
+ if (!otherReflectDefineProperty(object, prop, otherDesc)) return false;
580
+ if (otherDesc.configurable !== true && (!hasBasic || !(hasFunc || hasValue))) {
581
+ otherDesc = otherSafeGetOwnPropertyDescriptor(object, prop);
582
+ }
583
+ } catch (e) { // @other(unsafe)
584
+ throw thisFromOtherForThrow(e);
585
+ }
586
+
587
+ if (!otherDesc.configurable) {
588
+ let thisDesc;
589
+ if (otherDesc.get || otherDesc.set) {
590
+ thisDesc = {
591
+ __proto__: null,
592
+ get: this.fromOtherWithContext(otherDesc.get),
593
+ set: this.fromOtherWithContext(otherDesc.set),
594
+ enumerable: otherDesc.enumerable,
595
+ configurable: otherDesc.configurable
596
+ };
597
+ } else {
598
+ thisDesc = {
599
+ __proto__: null,
600
+ value: this.fromOtherWithContext(otherDesc.value),
601
+ writable: otherDesc.writable,
602
+ enumerable: otherDesc.enumerable,
603
+ configurable: otherDesc.configurable
604
+ };
605
+ }
606
+ if (!thisReflectDefineProperty(target, prop, thisDesc)) throw thisUnexpected();
607
+ }
608
+ return true;
609
+ }
610
+
611
+ deleteProperty(target, prop) {
612
+ // Note: target@this(unsafe) prop@prim throws@this(unsafe)
613
+ const object = this.getObject(); // @other(unsafe)
614
+ try {
615
+ return otherReflectDeleteProperty(object, prop) === true;
616
+ } catch (e) { // @other(unsafe)
617
+ throw thisFromOtherForThrow(e);
618
+ }
619
+ }
620
+
621
+ has(target, key) {
622
+ // Note: target@this(unsafe) key@prim throws@this(unsafe)
623
+ const object = this.getObject(); // @other(unsafe)
624
+ try {
625
+ return otherReflectHas(object, key) === true;
626
+ } catch (e) { // @other(unsafe)
627
+ throw thisFromOtherForThrow(e);
628
+ }
629
+ }
630
+
631
+ isExtensible(target) {
632
+ // Note: target@this(unsafe) throws@this(unsafe)
633
+ const object = this.getObject(); // @other(unsafe)
634
+ try {
635
+ if (otherReflectIsExtensible(object)) return true;
636
+ } catch (e) { // @other(unsafe)
637
+ throw thisFromOtherForThrow(e);
638
+ }
639
+ if (thisReflectIsExtensible(target)) {
640
+ this.doPreventExtensions(target, object, this);
641
+ }
642
+ return false;
643
+ }
644
+
645
+ ownKeys(target) {
646
+ // Note: target@this(unsafe) throws@this(unsafe)
647
+ const object = this.getObject(); // @other(unsafe)
648
+ let res; // @other(unsafe)
649
+ try {
650
+ res = otherReflectOwnKeys(object);
651
+ } catch (e) { // @other(unsafe)
652
+ throw thisFromOtherForThrow(e);
653
+ }
654
+ return thisFromOther(res);
655
+ }
656
+
657
+ preventExtensions(target) {
658
+ // Note: target@this(unsafe) throws@this(unsafe)
659
+ const object = this.getObject(); // @other(unsafe)
660
+ try {
661
+ if (!otherReflectPreventExtensions(object)) return false;
662
+ } catch (e) { // @other(unsafe)
663
+ throw thisFromOtherForThrow(e);
664
+ }
665
+ if (thisReflectIsExtensible(target)) {
666
+ this.doPreventExtensions(target, object, this);
667
+ }
668
+ return true;
669
+ }
670
+
671
+ enumerate(target) {
672
+ // Note: target@this(unsafe) throws@this(unsafe)
673
+ const object = this.getObject(); // @other(unsafe)
674
+ let res; // @other(unsafe)
675
+ try {
676
+ res = otherReflectEnumerate(object);
677
+ } catch (e) { // @other(unsafe)
678
+ throw thisFromOtherForThrow(e);
679
+ }
680
+ return this.fromOtherWithContext(res);
681
+ }
682
+
683
+ }
684
+
685
+ BaseHandler.prototype[thisSymbolNodeJSUtilInspectCustom] = undefined;
686
+ BaseHandler.prototype[thisSymbolToStringTag] = 'VM2 Wrapper';
687
+ BaseHandler.prototype[thisSymbolIterator] = undefined;
688
+
689
+ function defaultFactory(object) {
690
+ // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe)
691
+ return new BaseHandler(object);
692
+ }
693
+
694
+ class ProtectedHandler extends BaseHandler {
695
+
696
+ getFactory() {
697
+ return protectedFactory;
698
+ }
699
+
700
+ set(target, key, value, receiver) {
701
+ // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe)
702
+ if (typeof value === 'function') {
703
+ return thisReflectDefineProperty(receiver, key, {
704
+ __proto__: null,
705
+ value: value,
706
+ writable: true,
707
+ enumerable: true,
708
+ configurable: true
709
+ }) === true;
710
+ }
711
+ return super.set(target, key, value, receiver);
712
+ }
713
+
714
+ definePropertyDesc(target, prop, desc) {
715
+ // Note: target@this(unsafe) prop@prim desc@this(safe) throws@this(unsafe)
716
+ if (desc && (desc.set || desc.get || typeof desc.value === 'function')) return undefined;
717
+ return desc;
718
+ }
719
+
720
+ }
721
+
722
+ function protectedFactory(object) {
723
+ // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe)
724
+ return new ProtectedHandler(object);
725
+ }
726
+
727
+ class ReadOnlyHandler extends BaseHandler {
728
+
729
+ getFactory() {
730
+ return readonlyFactory;
731
+ }
732
+
733
+ set(target, key, value, receiver) {
734
+ // Note: target@this(unsafe) key@prim value@this(unsafe) receiver@this(unsafe) throws@this(unsafe)
735
+ return thisReflectDefineProperty(receiver, key, {
736
+ __proto__: null,
737
+ value: value,
738
+ writable: true,
739
+ enumerable: true,
740
+ configurable: true
741
+ });
742
+ }
743
+
744
+ setPrototypeOf(target, value) {
745
+ // Note: target@this(unsafe) throws@this(unsafe)
746
+ return false;
747
+ }
748
+
749
+ defineProperty(target, prop, desc) {
750
+ // Note: target@this(unsafe) prop@prim desc@this(unsafe) throws@this(unsafe)
751
+ return false;
752
+ }
753
+
754
+ deleteProperty(target, prop) {
755
+ // Note: target@this(unsafe) prop@prim throws@this(unsafe)
756
+ return false;
757
+ }
758
+
759
+ isExtensible(target) {
760
+ // Note: target@this(unsafe) throws@this(unsafe)
761
+ return false;
762
+ }
763
+
764
+ preventExtensions(target) {
765
+ // Note: target@this(unsafe) throws@this(unsafe)
766
+ return false;
767
+ }
768
+
769
+ }
770
+
771
+ function readonlyFactory(object) {
772
+ // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe)
773
+ return new ReadOnlyHandler(object);
774
+ }
775
+
776
+ class ReadOnlyMockHandler extends ReadOnlyHandler {
777
+
778
+ constructor(object, mock) {
779
+ // Note: object@other(unsafe) mock:this(unsafe) throws@this(unsafe)
780
+ super(object);
781
+ this.mock = mock;
782
+ }
783
+
784
+ get(target, key, receiver) {
785
+ // Note: target@this(unsafe) key@prim receiver@this(unsafe) throws@this(unsafe)
786
+ const object = this.getObject(); // @other(unsafe)
787
+ const mock = this.mock;
788
+ if (thisReflectApply(thisObjectHasOwnProperty, mock, key) && !thisOtherHasOwnProperty(object, key)) {
789
+ return mock[key];
790
+ }
791
+ return super.get(target, key, receiver);
792
+ }
793
+
794
+ }
795
+
796
+ function thisFromOther(other) {
797
+ // Note: other@other(unsafe) returns@this(unsafe) throws@this(unsafe)
798
+ return thisFromOtherWithFactory(defaultFactory, other);
799
+ }
800
+
801
+ function thisProxyOther(factory, other, proto) {
802
+ const target = thisCreateTargetObject(other, proto);
803
+ const handler = factory(other);
804
+ const proxy = new ThisProxy(target, handler);
805
+ try {
806
+ otherReflectApply(otherWeakMapSet, mappingThisToOther, [proxy, other]);
807
+ registerProxy(proxy, handler);
808
+ } catch (e) {
809
+ throw new VMError('Unexpected error');
810
+ }
811
+ if (!isHost) {
812
+ thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, proxy]);
813
+ return proxy;
814
+ }
815
+ const proxy2 = new ThisProxy(proxy, emptyForzenObject);
816
+ try {
817
+ otherReflectApply(otherWeakMapSet, mappingThisToOther, [proxy2, other]);
818
+ registerProxy(proxy2, handler);
819
+ } catch (e) {
820
+ throw new VMError('Unexpected error');
821
+ }
822
+ thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, proxy2]);
823
+ return proxy2;
824
+ }
825
+
826
+ function thisEnsureThis(other) {
827
+ const type = typeof other;
828
+ switch (type) {
829
+ case 'object':
830
+ if (other === null) {
831
+ return null;
832
+ }
833
+ // fallthrough
834
+ case 'function':
835
+ let proto = thisReflectGetPrototypeOf(other);
836
+ if (!proto) {
837
+ return other;
838
+ }
839
+ while (proto) {
840
+ const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]);
841
+ if (mapping) {
842
+ const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]);
843
+ if (mapped) return mapped;
844
+ return mapping(defaultFactory, other);
845
+ }
846
+ proto = thisReflectGetPrototypeOf(proto);
847
+ }
848
+ return other;
849
+ case 'undefined':
850
+ case 'string':
851
+ case 'number':
852
+ case 'boolean':
853
+ case 'symbol':
854
+ case 'bigint':
855
+ return other;
856
+
857
+ default: // new, unknown types can be dangerous
858
+ throw new VMError(`Unknown type '${type}'`);
859
+ }
860
+ }
861
+
862
+ function thisFromOtherForThrow(other) {
863
+ for (let loop = 0; loop < 10; loop++) {
864
+ const type = typeof other;
865
+ switch (type) {
866
+ case 'object':
867
+ if (other === null) {
868
+ return null;
869
+ }
870
+ // fallthrough
871
+ case 'function':
872
+ const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]);
873
+ if (mapped) return mapped;
874
+ let proto;
875
+ try {
876
+ proto = otherReflectGetPrototypeOf(other);
877
+ } catch (e) { // @other(unsafe)
878
+ other = e;
879
+ break;
880
+ }
881
+ if (!proto) {
882
+ return thisProxyOther(defaultFactory, other, null);
883
+ }
884
+ for (;;) {
885
+ const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]);
886
+ if (mapping) return mapping(defaultFactory, other);
887
+ try {
888
+ proto = otherReflectGetPrototypeOf(proto);
889
+ } catch (e) { // @other(unsafe)
890
+ other = e;
891
+ break;
892
+ }
893
+ if (!proto) return thisProxyOther(defaultFactory, other, thisObjectPrototype);
894
+ }
895
+ break;
896
+ case 'undefined':
897
+ case 'string':
898
+ case 'number':
899
+ case 'boolean':
900
+ case 'symbol':
901
+ case 'bigint':
902
+ return other;
903
+
904
+ default: // new, unknown types can be dangerous
905
+ throw new VMError(`Unknown type '${type}'`);
906
+ }
907
+ }
908
+ throw new VMError('Exception recursion depth');
909
+ }
910
+
911
+ function thisFromOtherWithFactory(factory, other, proto) {
912
+ const type = typeof other;
913
+ switch (type) {
914
+ case 'object':
915
+ if (other === null) {
916
+ return null;
917
+ }
918
+ // fallthrough
919
+ case 'function':
920
+ const mapped = thisReflectApply(thisWeakMapGet, mappingOtherToThis, [other]);
921
+ if (mapped) return mapped;
922
+ if (proto) {
923
+ return thisProxyOther(factory, other, proto);
924
+ }
925
+ try {
926
+ proto = otherReflectGetPrototypeOf(other);
927
+ } catch (e) { // @other(unsafe)
928
+ throw thisFromOtherForThrow(e);
929
+ }
930
+ if (!proto) {
931
+ return thisProxyOther(factory, other, null);
932
+ }
933
+ do {
934
+ const mapping = thisReflectApply(thisMapGet, protoMappings, [proto]);
935
+ if (mapping) return mapping(factory, other);
936
+ try {
937
+ proto = otherReflectGetPrototypeOf(proto);
938
+ } catch (e) { // @other(unsafe)
939
+ throw thisFromOtherForThrow(e);
940
+ }
941
+ } while (proto);
942
+ return thisProxyOther(factory, other, thisObjectPrototype);
943
+ case 'undefined':
944
+ case 'string':
945
+ case 'number':
946
+ case 'boolean':
947
+ case 'symbol':
948
+ case 'bigint':
949
+ return other;
950
+
951
+ default: // new, unknown types can be dangerous
952
+ throw new VMError(`Unknown type '${type}'`);
953
+ }
954
+ }
955
+
956
+ function thisFromOtherArguments(args) {
957
+ // Note: args@other(safe-array) returns@this(safe-array) throws@this(unsafe)
958
+ const arr = [];
959
+ for (let i = 0; i < args.length; i++) {
960
+ const value = thisFromOther(args[i]);
961
+ thisReflectDefineProperty(arr, i, {
962
+ __proto__: null,
963
+ value: value,
964
+ writable: true,
965
+ enumerable: true,
966
+ configurable: true
967
+ });
968
+ }
969
+ return arr;
970
+ }
971
+
972
+ function thisConnect(obj, other) {
973
+ // Note: obj@this(unsafe) other@other(unsafe) throws@this(unsafe)
974
+ try {
975
+ otherReflectApply(otherWeakMapSet, mappingThisToOther, [obj, other]);
976
+ } catch (e) {
977
+ throw new VMError('Unexpected error');
978
+ }
979
+ thisReflectApply(thisWeakMapSet, mappingOtherToThis, [other, obj]);
980
+ }
981
+
982
+ thisAddProtoMapping(thisGlobalPrototypes.Object, otherGlobalPrototypes.Object);
983
+ thisAddProtoMapping(thisGlobalPrototypes.Array, otherGlobalPrototypes.Array);
984
+
985
+ for (let i = 0; i < globalsList.length; i++) {
986
+ const key = globalsList[i];
987
+ const tp = thisGlobalPrototypes[key];
988
+ const op = otherGlobalPrototypes[key];
989
+ if (tp && op) thisAddProtoMapping(tp, op, key);
990
+ }
991
+
992
+ for (let i = 0; i < errorsList.length; i++) {
993
+ const key = errorsList[i];
994
+ const tp = thisGlobalPrototypes[key];
995
+ const op = otherGlobalPrototypes[key];
996
+ if (tp && op) thisAddProtoMapping(tp, op, 'Error');
997
+ }
998
+
999
+ thisAddProtoMapping(thisGlobalPrototypes.VMError, otherGlobalPrototypes.VMError, 'Error');
1000
+
1001
+ result.BaseHandler = BaseHandler;
1002
+ result.ProtectedHandler = ProtectedHandler;
1003
+ result.ReadOnlyHandler = ReadOnlyHandler;
1004
+ result.ReadOnlyMockHandler = ReadOnlyMockHandler;
1005
+
1006
+ return result;
1007
+ }
1008
+
1009
+ exports.createBridge = createBridge;
1010
+ exports.VMError = VMError;
ndcc/lib/client-dist/socket.io.esm.min.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /*!
2
+ * Socket.IO v4.7.5
3
+ * (c) 2014-2024 Guillermo Rauch
4
+ * Released under the MIT License.
5
+ */
6
+ const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach((s=>{e[t[s]]=s}));const s={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,h)=>n&&s instanceof Blob?o?h(s):a(s,h):i&&(s instanceof ArrayBuffer||r(s))?o?h(s):a(new Blob([s]),h):h(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function h(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let c;const u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)p[u.charCodeAt(t)]=t;const l="function"==typeof ArrayBuffer,d=(t,n)=>{if("string"!=typeof t)return{type:"message",data:y(t,n)};const i=t.charAt(0);if("b"===i)return{type:"message",data:f(t.substring(1),n)};return e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:s},f=(t,e)=>{if(l){const s=(t=>{let e,s,n,i,r,o=.75*t.length,a=t.length,h=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const c=new ArrayBuffer(o),u=new Uint8Array(c);for(e=0;e<a;e+=4)s=p[t.charCodeAt(e)],n=p[t.charCodeAt(e+1)],i=p[t.charCodeAt(e+2)],r=p[t.charCodeAt(e+3)],u[h++]=s<<2|n>>4,u[h++]=(15&n)<<4|i>>2,u[h++]=(3&i)<<6|63&r;return c})(t);return y(s,e)}return{base64:!0,data:t}},y=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,g=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){n&&t.data instanceof Blob?t.data.arrayBuffer().then(h).then(e):i&&(t.data instanceof ArrayBuffer||r(t.data))?e(h(t.data)):o(t,!1,(t=>{c||(c=new TextEncoder),e(c.encode(t))}))}(t,(s=>{const n=s.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,n)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(n))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(s)}))}})}let b;function w(t){return t.reduce(((t,e)=>t+e.length),0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)s[i]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),s}function k(t){if(t)return function(t){for(var e in k.prototype)t[e]=k.prototype[e];return t}(t)}k.prototype.on=k.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},k.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},k.prototype.off=k.prototype.removeListener=k.prototype.removeAllListeners=k.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var s,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<n.length;i++)if((s=n[i])===e||s.fn===e){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},k.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),s=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(s){n=0;for(var i=(s=s.slice(0)).length;n<i;++n)s[n].apply(this,e)}return this},k.prototype.emitReserved=k.prototype.emit,k.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},k.prototype.hasListeners=function(t){return!!this.listeners(t).length};const _="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce(((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e)),{})}const A=_.setTimeout,O=_.clearTimeout;function T(t,e){e.useNativeTimers?(t.setTimeoutFn=A.bind(_),t.clearTimeoutFn=O.bind(_)):(t.setTimeoutFn=_.setTimeout.bind(_),t.clearTimeoutFn=_.clearTimeout.bind(_))}class R extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}}class C extends k{constructor(t){super(),this.writable=!1,T(this,t),this.opts=t,this.query=t.query,this.socket=t.socket}onError(t,e,s){return super.emitReserved("error",new R(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=d(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}_hostname(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}const B="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),S=64,N={};let x,L=0,q=0;function P(t){let e="";do{e=B[t%S]+e,t=Math.floor(t/S)}while(t>0);return e}function j(){const t=P(+new Date);return t!==x?(L=0,x=t):t+"."+P(L++)}for(;q<S;q++)N[B[q]]=q;let U=!1;try{U="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const D=U;function I(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||D))return new XMLHttpRequest}catch(t){}if(!e)try{return new(_[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function F(){}const M=null!=new I({xdomain:!1}).responseType;class V extends k{constructor(t,e){super(),T(this,e),this.opts=e,this.method=e.method||"GET",this.uri=t,this.data=void 0!==e.data?e.data:null,this.create()}create(){var t;const e=E(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd;const s=this.xhr=new I(e);try{s.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){s.setDisableHeaderCheck&&s.setDisableHeaderCheck(!0);for(let t in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(t)&&s.setRequestHeader(t,this.opts.extraHeaders[t])}}catch(t){}if("POST"===this.method)try{s.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{s.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(s),"withCredentials"in s&&(s.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(s.timeout=this.opts.requestTimeout),s.onreadystatechange=()=>{var t;3===s.readyState&&(null===(t=this.opts.cookieJar)||void 0===t||t.parseCookies(s)),4===s.readyState&&(200===s.status||1223===s.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof s.status?s.status:0)}),0))},s.send(this.data)}catch(t){return void this.setTimeoutFn((()=>{this.onError(t)}),0)}"undefined"!=typeof document&&(this.index=V.requestsCount++,V.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=F,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete V.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(V.requestsCount=0,V.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",H);else if("function"==typeof addEventListener){addEventListener("onpagehide"in _?"pagehide":"unload",H,!1)}function H(){for(let t in V.requests)V.requests.hasOwnProperty(t)&&V.requests[t].abort()}const K="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),Y=_.WebSocket||_.MozWebSocket,W="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const z={websocket:class extends C{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),e=this.opts.protocols,s=W?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=W?new Y(t,e,s):e?new Y(t,e):new Y(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;o(s,this.supportsBinary,(t=>{try{this.ws.send(t)}catch(t){}n&&K((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=j()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}check(){return!!Y}},webtransport:class extends C{get name(){return"webtransport"}doOpen(){"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((()=>{this.onClose()})).catch((t=>{this.onError("webtransport error",t)})),this.transport.ready.then((()=>{this.transport.createBidirectionalStream().then((t=>{const e=function(t,e){b||(b=new TextDecoder);const n=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,h){for(n.push(a);;){if(0===i){if(w(n)<1)break;const t=v(n,1);o=128==(128&t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(w(n)<2)break;const t=v(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(w(n)<8)break;const t=v(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){h.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),i=3}else{if(w(n)<r)break;const t=v(n,r);h.enqueue(d(o?t:b.decode(t),e)),i=0}if(0===r||r>t){h.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=m();i.readable.pipeTo(t.writable),this.writer=i.writable.getWriter();const r=()=>{n.read().then((({done:t,value:e})=>{t||(this.onPacket(e),r())})).catch((t=>{}))};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.writer.write(o).then((()=>this.onOpen()))}))})))}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;this.writer.write(s).then((()=>{n&&K((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){var t;null===(t=this.transport)||void 0===t||t.close()}},polling:class extends C{constructor(t){if(super(t),this.polling=!1,"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}const e=t&&t.forceBase64;this.supportsBinary=M&&!e,this.opts.withCredentials&&(this.cookieJar=void 0)}get name(){return"polling"}doOpen(){this.poll()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.polling||!this.writable){let t=0;this.polling&&(t++,this.once("pollComplete",(function(){--t||e()}))),this.writable||(t++,this.once("drain",(function(){--t||e()})))}else e()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(g),n=[];for(let t=0;t<s.length;t++){const i=d(s[t],e);if(n.push(i),"error"===i.type)break}return n})(t,this.socket.binaryType).forEach((t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,n=new Array(s);let i=0;t.forEach(((t,r)=>{o(t,!1,(t=>{n[r]=t,++i===s&&e(n.join(g))}))}))})(t,(t=>{this.doWrite(t,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=j()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new V(this.uri(),t)}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",((t,e)=>{this.onError("xhr post error",t,e)}))}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",((t,e)=>{this.onError("xhr poll error",t,e)})),this.pollXhr=t}}},J=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,$=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Q(t){const e=t,s=t.indexOf("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let i=J.exec(t||""),r={},o=14;for(;o--;)r[$[o]]=i[o]||"";return-1!=s&&-1!=n&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=/\/{2,9}/g,n=e.replace(s,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1);"/"==e.slice(-1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(s[e]=n)})),s}(0,r.query),r}class X extends k{constructor(t,e={}){super(),this.binaryType="arraybuffer",this.writeBuffer=[],t&&"object"==typeof t&&(e=t,t=null),t?(t=Q(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=Q(e.host).host),T(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=e.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,n=s.length;t<n;t++){let n=s[t].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new z[t](s)}open(){let t;if(this.opts.rememberUpgrade&&X.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(t=>this.onClose("transport close",t)))}probe(t){let e=this.createTransport(t),s=!1;X.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;X.priorWebsocketSuccess="websocket"===e.name,this.transport.pause((()=>{s||"closed"!==this.readyState&&(c(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())}))}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}})))};function i(){s||(s=!0,c(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function h(t){e&&t.name!==e.name&&i()}const c=()=>{e.removeListener("open",n),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",h)};e.once("open",n),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",h),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((()=>{s||e.open()}),200):e.open()}onOpen(){if(this.readyState="open",X.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let t=0;const e=this.upgrades.length;for(;t<e;t++)this.probe(this.upgrades[t])}}onPacket(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),this.resetPingTimeout(),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(t+="string"==typeof(e=n)?function(t){let e=0,s=0;for(let n=0,i=t.length;n<i;n++)e=t.charCodeAt(n),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(n++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.maxPayload)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}write(t,e,s){return this.sendPacket("message",t,e,s),this}send(t,e,s){return this.sendPacket("message",t,e,s),this}sendPacket(t,e,s,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?s():t()})):this.upgrading?s():t()),this}onError(t){X.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const e=[];let s=0;const n=t.length;for(;s<n;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}X.protocol=4;const G="function"==typeof ArrayBuffer,Z=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer,tt=Object.prototype.toString,et="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===tt.call(Blob),st="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===tt.call(File);function nt(t){return G&&(t instanceof ArrayBuffer||Z(t))||et&&t instanceof Blob||st&&t instanceof File}function it(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(it(t[e]))return!0;return!1}if(nt(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return it(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&it(t[e]))return!0;return!1}function rt(t){const e=[],s=t.data,n=t;return n.data=ot(s,e),n.attachments=e.length,{packet:n,buffers:e}}function ot(t,e){if(!t)return t;if(nt(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let n=0;n<t.length;n++)s[n]=ot(t[n],e);return s}if("object"==typeof t&&!(t instanceof Date)){const s={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(s[n]=ot(t[n],e));return s}return t}function at(t,e){return t.data=ht(t.data,e),delete t.attachments,t}function ht(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=ht(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=ht(t[s],e));return t}const ct=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ut=5;var pt;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(pt||(pt={}));function lt(t){return"[object Object]"===Object.prototype.toString.call(t)}class dt extends k{constructor(t){super(),this.reviver=t}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===pt.BINARY_EVENT;s||e.type===pt.BINARY_ACK?(e.type=s?pt.EVENT:pt.ACK,this.reconstructor=new ft(e),0===e.attachments&&super.emitReserved("decoded",e)):super.emitReserved("decoded",e)}else{if(!nt(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===pt[s.type])throw new Error("unknown packet type "+s.type);if(s.type===pt.BINARY_EVENT||s.type===pt.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(n,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");s.attachments=Number(i)}if("/"===t.charAt(e+1)){const n=e+1;for(;++e;){if(","===t.charAt(e))break;if(e===t.length)break}s.nsp=t.substring(n,e)}else s.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!dt.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}return s}tryParse(t){try{return JSON.parse(t,this.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case pt.CONNECT:return lt(e);case pt.DISCONNECT:return void 0===e;case pt.CONNECT_ERROR:return"string"==typeof e||lt(e);case pt.EVENT:case pt.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===ct.indexOf(e[0]));case pt.ACK:case pt.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ft{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=at(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var yt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return pt},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==pt.EVENT&&t.type!==pt.ACK||!it(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===pt.EVENT?pt.BINARY_EVENT:pt.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==pt.BINARY_EVENT&&t.type!==pt.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=rt(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}},Decoder:dt});function gt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const mt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class bt extends k{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this._opts=Object.assign({},s),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[gt(t,"open",this.onopen.bind(this)),gt(t,"packet",this.onpacket.bind(this)),gt(t,"error",this.onerror.bind(this)),gt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){if(mt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(e),this;const s={type:pt.EVENT,data:e,options:{}};if(s.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this._registerAckCallback(t,n),s.id=t}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(s),this.packet(s)):this.sendBuffer.push(s)),this.flags={},this}_registerAckCallback(t,e){var s;const n=null!==(s=this.flags.timeout)&&void 0!==s?s:this._opts.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const i=this.io.setTimeoutFn((()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))}),n),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise(((s,n)=>{const i=(t,e)=>t?n(t):s(e);i.withError=!0,e.push(i),this.emit(t,...e)}))}_addToQueue(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push(((t,...n)=>{if(s!==this._queue[0])return;return null!==t?s.tryCount>this._opts.retries&&(this._queue.shift(),e&&e(t)):(this._queue.shift(),e&&e(null,...n)),s.pending=!1,this._drainQueue()})),this._queue.push(s),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||0===this._queue.length)return;const e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){"function"==typeof this.auth?this.auth((t=>{this._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:pt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach((t=>{if(!this.sendBuffer.some((e=>String(e.id)===t))){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}}))}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case pt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("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 pt.EVENT:case pt.BINARY_EVENT:this.onevent(t);break;case pt.ACK:case pt.BINARY_ACK:this.onack(t);break;case pt.DISCONNECT:this.ondisconnect();break;case pt.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const e=this._anyListeners.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:pt.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((t=>this.emitEvent(t))),this.receiveBuffer=[],this.sendBuffer.forEach((t=>{this.notifyOutgoingListeners(t),this.packet(t)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((t=>t())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:pt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const e=this._anyListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}prependAnyOutgoing(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}offAnyOutgoing(t){if(!this._anyOutgoingListeners)return this;if(t){const e=this._anyOutgoingListeners;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const e=this._anyOutgoingListeners.slice();for(const s of e)s.apply(this,t.data)}}}function wt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}wt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-s:t+s}return 0|Math.min(t,this.max)},wt.prototype.reset=function(){this.attempts=0},wt.prototype.setMin=function(t){this.ms=t},wt.prototype.setMax=function(t){this.max=t},wt.prototype.setJitter=function(t){this.jitter=t};class vt extends k{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,T(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this._readyState="closed",this.uri=t;const n=e.parser||yt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==e.autoConnect,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new X(this.uri,this.opts);const e=this.engine,s=this;this._readyState="opening",this.skipReconnect=!1;const n=gt(e,"open",(function(){s.onopen(),t&&t()})),i=e=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=gt(e,"error",i);if(!1!==this._timeout){const t=this._timeout,s=this.setTimeoutFn((()=>{n(),i(new Error("timeout")),e.close()}),t);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}return this.subs.push(n),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(gt(t,"ping",this.onping.bind(this)),gt(t,"data",this.ondata.bind(this)),gt(t,"error",this.onerror.bind(this)),gt(t,"close",this.onclose.bind(this)),gt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){K((()=>{this.emitReserved("packet",t)}),this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this._autoConnect&&!s.active&&s.connect():(s=new bt(this,t,e),this.nsps[t]=s),s}_destroy(t){const e=Object.keys(this.nsps);for(const t of e){if(this.nsps[t].active)return}this._close()}_packet(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach((t=>t())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const e=this.backoff.duration();this._reconnecting=!0;const s=this.setTimeoutFn((()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((e=>{e?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()})))}),e);this.opts.autoUnref&&s.unref(),this.subs.push((()=>{this.clearTimeoutFn(s)}))}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const kt={};function _t(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let n=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),n=Q(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,i=s.id,r=s.path,o=kt[i]&&r in kt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new vt(n,e):(kt[i]||(kt[i]=new vt(n,e)),a=kt[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(_t,{Manager:vt,Socket:bt,io:_t,connect:_t});export{vt as Manager,bt as Socket,_t as connect,_t as default,_t as io,ut as protocol};
7
+ //# sourceMappingURL=socket.io.esm.min.js.map
ndcc/lib/client-dist/socket.io.esm.min.js.map ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/client-dist/socket.io.js ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/client-dist/socket.io.js.map ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/client-dist/socket.io.min.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /*!
2
+ * Socket.IO v4.7.5
3
+ * (c) 2014-2024 Guillermo Rauch
4
+ * Released under the MIT License.
5
+ */
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).io=t()}(this,(function(){"use strict";function e(t){return e="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},e(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,(i=r.key,o=void 0,"symbol"==typeof(o=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(i,"string"))?o:String(o)),r)}var i,o}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i.apply(this,arguments)}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&a(e,t)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function a(e,t){return a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},a(e,t)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function u(e,t,n){return u=c()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&a(i,n.prototype),i},u.apply(null,arguments)}function h(e){var t="function"==typeof Map?new Map:void 0;return h=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return u(e,arguments,s(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),a(r,e)},h(e)}function f(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function l(e){var t=c();return function(){var n,r=s(e);if(t){var i=s(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return f(e)}(this,n)}}function p(){return p="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=s(e)););return e}(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},p.apply(this,arguments)}function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function y(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?d(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}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 o,s=!0,a=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){a=!0,o=e},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var v=Object.create(null);v.open="0",v.close="1",v.ping="2",v.pong="3",v.message="4",v.upgrade="5",v.noop="6";var g=Object.create(null);Object.keys(v).forEach((function(e){g[v[e]]=e}));var m,b={type:"error",data:"parser error"},k="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),w="function"==typeof ArrayBuffer,_=function(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer},E=function(e,t,n){var r=e.type,i=e.data;return k&&i instanceof Blob?t?n(i):A(i,n):w&&(i instanceof ArrayBuffer||_(i))?t?n(i):A(new Blob([i]),n):n(v[r]+(i||""))},A=function(e,t){var n=new FileReader;return n.onload=function(){var e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function O(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}for(var T="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",R="undefined"==typeof Uint8Array?[]:new Uint8Array(256),C=0;C<64;C++)R[T.charCodeAt(C)]=C;var B,S="function"==typeof ArrayBuffer,N=function(e,t){if("string"!=typeof e)return{type:"message",data:x(e,t)};var n=e.charAt(0);return"b"===n?{type:"message",data:L(e.substring(1),t)}:g[n]?e.length>1?{type:g[n],data:e.substring(1)}:{type:g[n]}:b},L=function(e,t){if(S){var n=function(e){var t,n,r,i,o,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);var u=new ArrayBuffer(s),h=new Uint8Array(u);for(t=0;t<a;t+=4)n=R[e.charCodeAt(t)],r=R[e.charCodeAt(t+1)],i=R[e.charCodeAt(t+2)],o=R[e.charCodeAt(t+3)],h[c++]=n<<2|r>>4,h[c++]=(15&r)<<4|i>>2,h[c++]=(3&i)<<6|63&o;return u}(e);return x(n,t)}return{base64:!0,data:e}},x=function(e,t){return"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer},P=String.fromCharCode(30);function j(){return new TransformStream({transform:function(e,t){!function(e,t){k&&e.data instanceof Blob?e.data.arrayBuffer().then(O).then(t):w&&(e.data instanceof ArrayBuffer||_(e.data))?t(O(e.data)):E(e,!1,(function(e){m||(m=new TextEncoder),t(m.encode(e))}))}(e,(function(n){var r,i=n.length;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);var o=new DataView(r.buffer);o.setUint8(0,126),o.setUint16(1,i)}else{r=new Uint8Array(9);var s=new DataView(r.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)}))}})}function q(e){return e.reduce((function(e,t){return e+t.length}),0)}function D(e,t){if(e[0].length===t)return e.shift();for(var n=new Uint8Array(t),r=0,i=0;i<t;i++)n[i]=e[0][r++],r===e[0].length&&(e.shift(),r=0);return e.length&&r<e[0].length&&(e[0]=e[0].slice(r)),n}function U(e){if(e)return function(e){for(var t in U.prototype)e[t]=U.prototype[t];return e}(e)}U.prototype.on=U.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},U.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},U.prototype.off=U.prototype.removeListener=U.prototype.removeAllListeners=U.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+e];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<r.length;i++)if((n=r[i])===t||n.fn===t){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+e],this},U.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],r=1;r<arguments.length;r++)t[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,t)}return this},U.prototype.emitReserved=U.prototype.emit,U.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},U.prototype.hasListeners=function(e){return!!this.listeners(e).length};var I="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function F(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return n.reduce((function(t,n){return e.hasOwnProperty(n)&&(t[n]=e[n]),t}),{})}var M=I.setTimeout,V=I.clearTimeout;function H(e,t){t.useNativeTimers?(e.setTimeoutFn=M.bind(I),e.clearTimeoutFn=V.bind(I)):(e.setTimeoutFn=I.setTimeout.bind(I),e.clearTimeoutFn=I.clearTimeout.bind(I))}var K,Y=function(e){o(i,e);var n=l(i);function i(e,r,o){var s;return t(this,i),(s=n.call(this,e)).description=r,s.context=o,s.type="TransportError",s}return r(i)}(h(Error)),W=function(e){o(i,e);var n=l(i);function i(e){var r;return t(this,i),(r=n.call(this)).writable=!1,H(f(r),e),r.opts=e,r.query=e.query,r.socket=e.socket,r}return r(i,[{key:"onError",value:function(e,t,n){return p(s(i.prototype),"emitReserved",this).call(this,"error",new Y(e,t,n)),this}},{key:"open",value:function(){return this.readyState="opening",this.doOpen(),this}},{key:"close",value:function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}},{key:"send",value:function(e){"open"===this.readyState&&this.write(e)}},{key:"onOpen",value:function(){this.readyState="open",this.writable=!0,p(s(i.prototype),"emitReserved",this).call(this,"open")}},{key:"onData",value:function(e){var t=N(e,this.socket.binaryType);this.onPacket(t)}},{key:"onPacket",value:function(e){p(s(i.prototype),"emitReserved",this).call(this,"packet",e)}},{key:"onClose",value:function(e){this.readyState="closed",p(s(i.prototype),"emitReserved",this).call(this,"close",e)}},{key:"pause",value:function(e){}},{key:"createUri",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}},{key:"_hostname",value:function(){var e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}},{key:"_port",value:function(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}},{key:"_query",value:function(e){var t=function(e){var t="";for(var n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}]),i}(U),z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),J=64,$={},Q=0,X=0;function G(e){var t="";do{t=z[e%J]+t,e=Math.floor(e/J)}while(e>0);return t}function Z(){var e=G(+new Date);return e!==K?(Q=0,K=e):e+"."+G(Q++)}for(;X<J;X++)$[z[X]]=X;var ee=!1;try{ee="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}var te=ee;function ne(e){var t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||te))return new XMLHttpRequest}catch(e){}if(!t)try{return new(I[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}function re(){}var ie=null!=new ne({xdomain:!1}).responseType,oe=function(e){o(s,e);var n=l(s);function s(e){var r;if(t(this,s),(r=n.call(this,e)).polling=!1,"undefined"!=typeof location){var i="https:"===location.protocol,o=location.port;o||(o=i?"443":"80"),r.xd="undefined"!=typeof location&&e.hostname!==location.hostname||o!==e.port}var a=e&&e.forceBase64;return r.supportsBinary=ie&&!a,r.opts.withCredentials&&(r.cookieJar=void 0),r}return r(s,[{key:"name",get:function(){return"polling"}},{key:"doOpen",value:function(){this.poll()}},{key:"pause",value:function(e){var t=this;this.readyState="pausing";var n=function(){t.readyState="paused",e()};if(this.polling||!this.writable){var r=0;this.polling&&(r++,this.once("pollComplete",(function(){--r||n()}))),this.writable||(r++,this.once("drain",(function(){--r||n()})))}else n()}},{key:"poll",value:function(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}},{key:"onData",value:function(e){var t=this;(function(e,t){for(var n=e.split(P),r=[],i=0;i<n.length;i++){var o=N(n[i],t);if(r.push(o),"error"===o.type)break}return r})(e,this.socket.binaryType).forEach((function(e){if("opening"===t.readyState&&"open"===e.type&&t.onOpen(),"close"===e.type)return t.onClose({description:"transport closed by the server"}),!1;t.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}},{key:"doClose",value:function(){var e=this,t=function(){e.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}},{key:"write",value:function(e){var t=this;this.writable=!1,function(e,t){var n=e.length,r=new Array(n),i=0;e.forEach((function(e,o){E(e,!1,(function(e){r[o]=e,++i===n&&t(r.join(P))}))}))}(e,(function(e){t.doWrite(e,(function(){t.writable=!0,t.emitReserved("drain")}))}))}},{key:"uri",value:function(){var e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Z()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}},{key:"request",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return i(e,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new se(this.uri(),e)}},{key:"doWrite",value:function(e,t){var n=this,r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(function(e,t){n.onError("xhr post error",e,t)}))}},{key:"doPoll",value:function(){var e=this,t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(function(t,n){e.onError("xhr poll error",t,n)})),this.pollXhr=t}}]),s}(W),se=function(e){o(i,e);var n=l(i);function i(e,r){var o;return t(this,i),H(f(o=n.call(this)),r),o.opts=r,o.method=r.method||"GET",o.uri=e,o.data=void 0!==r.data?r.data:null,o.create(),o}return r(i,[{key:"create",value:function(){var e,t=this,n=F(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;var r=this.xhr=new ne(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders)for(var o in r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}catch(e){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{r.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.opts.cookieJar)||void 0===e||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=function(){var e;3===r.readyState&&(null===(e=t.opts.cookieJar)||void 0===e||e.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?t.onLoad():t.setTimeoutFn((function(){t.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(e){return void this.setTimeoutFn((function(){t.onError(e)}),0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)}},{key:"onError",value:function(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=re,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),i}(U);if(se.requestsCount=0,se.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ae);else if("function"==typeof addEventListener){addEventListener("onpagehide"in I?"pagehide":"unload",ae,!1)}function ae(){for(var e in se.requests)se.requests.hasOwnProperty(e)&&se.requests[e].abort()}var ce="function"==typeof Promise&&"function"==typeof Promise.resolve?function(e){return Promise.resolve().then(e)}:function(e,t){return t(e,0)},ue=I.WebSocket||I.MozWebSocket,he="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),fe=function(e){o(i,e);var n=l(i);function i(e){var r;return t(this,i),(r=n.call(this,e)).supportsBinary=!e.forceBase64,r}return r(i,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var e=this.uri(),t=this.opts.protocols,n=he?{}:F(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=he?new ue(e,t,n):t?new ue(e,t):new ue(e)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}}},{key:"addEventListeners",value:function(){var e=this;this.ws.onopen=function(){e.opts.autoUnref&&e.ws._socket.unref(),e.onOpen()},this.ws.onclose=function(t){return e.onClose({description:"websocket connection closed",context:t})},this.ws.onmessage=function(t){return e.onData(t.data)},this.ws.onerror=function(t){return e.onError("websocket error",t)}}},{key:"write",value:function(e){var t=this;this.writable=!1;for(var n=function(){var n=e[r],i=r===e.length-1;E(n,t.supportsBinary,(function(e){try{t.ws.send(e)}catch(e){}i&&ce((function(){t.writable=!0,t.emitReserved("drain")}),t.setTimeoutFn)}))},r=0;r<e.length;r++)n()}},{key:"doClose",value:function(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}},{key:"uri",value:function(){var e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Z()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},{key:"check",value:function(){return!!ue}}]),i}(W),le=function(e){o(i,e);var n=l(i);function i(){return t(this,i),n.apply(this,arguments)}return r(i,[{key:"name",get:function(){return"webtransport"}},{key:"doOpen",value:function(){var e=this;"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((function(){e.onClose()})).catch((function(t){e.onError("webtransport error",t)})),this.transport.ready.then((function(){e.transport.createBidirectionalStream().then((function(t){var n=function(e,t){B||(B=new TextDecoder);var n=[],r=0,i=-1,o=!1;return new TransformStream({transform:function(s,a){for(n.push(s);;){if(0===r){if(q(n)<1)break;var c=D(n,1);o=128==(128&c[0]),i=127&c[0],r=i<126?3:126===i?1:2}else if(1===r){if(q(n)<2)break;var u=D(n,2);i=new DataView(u.buffer,u.byteOffset,u.length).getUint16(0),r=3}else if(2===r){if(q(n)<8)break;var h=D(n,8),f=new DataView(h.buffer,h.byteOffset,h.length),l=f.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(b);break}i=l*Math.pow(2,32)+f.getUint32(4),r=3}else{if(q(n)<i)break;var p=D(n,i);a.enqueue(N(o?p:B.decode(p),t)),r=0}if(0===i||i>e){a.enqueue(b);break}}}})}(Number.MAX_SAFE_INTEGER,e.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),i=j();i.readable.pipeTo(t.writable),e.writer=i.writable.getWriter();!function t(){r.read().then((function(n){var r=n.done,i=n.value;r||(e.onPacket(i),t())})).catch((function(e){}))}();var o={type:"open"};e.query.sid&&(o.data='{"sid":"'.concat(e.query.sid,'"}')),e.writer.write(o).then((function(){return e.onOpen()}))}))})))}},{key:"write",value:function(e){var t=this;this.writable=!1;for(var n=function(){var n=e[r],i=r===e.length-1;t.writer.write(n).then((function(){i&&ce((function(){t.writable=!0,t.emitReserved("drain")}),t.setTimeoutFn)}))},r=0;r<e.length;r++)n()}},{key:"doClose",value:function(){var e;null===(e=this.transport)||void 0===e||e.close()}}]),i}(W),pe={websocket:fe,webtransport:le,polling:oe},de=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ye=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function ve(e){var t=e,n=e.indexOf("["),r=e.indexOf("]");-1!=n&&-1!=r&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));for(var i,o,s=de.exec(e||""),a={},c=14;c--;)a[ye[c]]=s[c]||"";return-1!=n&&-1!=r&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){var n=/\/{2,9}/g,r=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||r.splice(0,1);"/"==t.slice(-1)&&r.splice(r.length-1,1);return r}(0,a.path),a.queryKey=(i=a.query,o={},i.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(o[t]=n)})),o),a}var ge=function(n){o(a,n);var s=l(a);function a(n){var r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t(this,a),(r=s.call(this)).binaryType="arraybuffer",r.writeBuffer=[],n&&"object"===e(n)&&(o=n,n=null),n?(n=ve(n),o.hostname=n.host,o.secure="https"===n.protocol||"wss"===n.protocol,o.port=n.port,n.query&&(o.query=n.query)):o.host&&(o.hostname=ve(o.host).host),H(f(r),o),r.secure=null!=o.secure?o.secure:"undefined"!=typeof location&&"https:"===location.protocol,o.hostname&&!o.port&&(o.port=r.secure?"443":"80"),r.hostname=o.hostname||("undefined"!=typeof location?location.hostname:"localhost"),r.port=o.port||("undefined"!=typeof location&&location.port?location.port:r.secure?"443":"80"),r.transports=o.transports||["polling","websocket","webtransport"],r.writeBuffer=[],r.prevBufferLen=0,r.opts=i({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},o),r.opts.path=r.opts.path.replace(/\/$/,"")+(r.opts.addTrailingSlash?"/":""),"string"==typeof r.opts.query&&(r.opts.query=function(e){for(var t={},n=e.split("&"),r=0,i=n.length;r<i;r++){var o=n[r].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}(r.opts.query)),r.id=null,r.upgrades=null,r.pingInterval=null,r.pingTimeout=null,r.pingTimeoutTimer=null,"function"==typeof addEventListener&&(r.opts.closeOnBeforeunload&&(r.beforeunloadEventListener=function(){r.transport&&(r.transport.removeAllListeners(),r.transport.close())},addEventListener("beforeunload",r.beforeunloadEventListener,!1)),"localhost"!==r.hostname&&(r.offlineEventListener=function(){r.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",r.offlineEventListener,!1))),r.open(),r}return r(a,[{key:"createTransport",value:function(e){var t=i({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);var n=i({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new pe[e](n)}},{key:"open",value:function(){var e,t=this;if(this.opts.rememberUpgrade&&a.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((function(){t.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}},{key:"setTransport",value:function(e){var t=this;this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(function(e){return t.onClose("transport close",e)}))}},{key:"probe",value:function(e){var t=this,n=this.createTransport(e),r=!1;a.priorWebsocketSuccess=!1;var i=function(){r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",(function(e){if(!r)if("pong"===e.type&&"probe"===e.data){if(t.upgrading=!0,t.emitReserved("upgrading",n),!n)return;a.priorWebsocketSuccess="websocket"===n.name,t.transport.pause((function(){r||"closed"!==t.readyState&&(f(),t.setTransport(n),n.send([{type:"upgrade"}]),t.emitReserved("upgrade",n),n=null,t.upgrading=!1,t.flush())}))}else{var i=new Error("probe error");i.transport=n.name,t.emitReserved("upgradeError",i)}})))};function o(){r||(r=!0,f(),n.close(),n=null)}var s=function(e){var r=new Error("probe error: "+e);r.transport=n.name,o(),t.emitReserved("upgradeError",r)};function c(){s("transport closed")}function u(){s("socket closed")}function h(e){n&&e.name!==n.name&&o()}var f=function(){n.removeListener("open",i),n.removeListener("error",s),n.removeListener("close",c),t.off("close",u),t.off("upgrading",h)};n.once("open",i),n.once("error",s),n.once("close",c),this.once("close",u),this.once("upgrading",h),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn((function(){r||n.open()}),200):n.open()}},{key:"onOpen",value:function(){if(this.readyState="open",a.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},{key:"onPacket",value:function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),this.resetPingTimeout(),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}},{key:"onHandshake",value:function(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}},{key:"resetPingTimeout",value:function(){var e=this;this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((function(){e.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}},{key:"onDrain",value:function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}},{key:"flush",value:function(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){var e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}},{key:"getWritablePackets",value:function(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;for(var e,t=1,n=0;n<this.writeBuffer.length;n++){var r=this.writeBuffer[n].data;if(r&&(t+="string"==typeof(e=r)?function(e){for(var t=0,n=0,r=0,i=e.length;r<i;r++)(t=e.charCodeAt(r))<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(r++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))),n>0&&t>this.maxPayload)return this.writeBuffer.slice(0,n);t+=2}return this.writeBuffer}},{key:"write",value:function(e,t,n){return this.sendPacket("message",e,t,n),this}},{key:"send",value:function(e,t,n){return this.sendPacket("message",e,t,n),this}},{key:"sendPacket",value:function(e,t,n,r){if("function"==typeof t&&(r=t,t=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var i={type:e,data:t,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}}},{key:"close",value:function(){var e=this,t=function(){e.onClose("forced close"),e.transport.close()},n=function n(){e.off("upgrade",n),e.off("upgradeError",n),t()},r=function(){e.once("upgrade",n),e.once("upgradeError",n)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){e.upgrading?r():t()})):this.upgrading?r():t()),this}},{key:"onError",value:function(e){a.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}},{key:"onClose",value:function(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(e){for(var t=[],n=0,r=e.length;n<r;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}]),a}(U);ge.protocol=4,ge.protocol;var me="function"==typeof ArrayBuffer,be=function(e){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer},ke=Object.prototype.toString,we="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===ke.call(Blob),_e="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===ke.call(File);function Ee(e){return me&&(e instanceof ArrayBuffer||be(e))||we&&e instanceof Blob||_e&&e instanceof File}function Ae(t,n){if(!t||"object"!==e(t))return!1;if(Array.isArray(t)){for(var r=0,i=t.length;r<i;r++)if(Ae(t[r]))return!0;return!1}if(Ee(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return Ae(t.toJSON(),!0);for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)&&Ae(t[o]))return!0;return!1}function Oe(e){var t=[],n=e.data,r=e;return r.data=Te(n,t),r.attachments=t.length,{packet:r,buffers:t}}function Te(t,n){if(!t)return t;if(Ee(t)){var r={_placeholder:!0,num:n.length};return n.push(t),r}if(Array.isArray(t)){for(var i=new Array(t.length),o=0;o<t.length;o++)i[o]=Te(t[o],n);return i}if("object"===e(t)&&!(t instanceof Date)){var s={};for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(s[a]=Te(t[a],n));return s}return t}function Re(e,t){return e.data=Ce(e.data,t),delete e.attachments,e}function Ce(t,n){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<n.length)return n[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(var r=0;r<t.length;r++)t[r]=Ce(t[r],n);else if("object"===e(t))for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(t[i]=Ce(t[i],n));return t}var Be,Se=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Be||(Be={}));var Ne=function(){function e(n){t(this,e),this.replacer=n}return r(e,[{key:"encode",value:function(e){return e.type!==Be.EVENT&&e.type!==Be.ACK||!Ae(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Be.EVENT?Be.BINARY_EVENT:Be.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}},{key:"encodeAsString",value:function(e){var t=""+e.type;return e.type!==Be.BINARY_EVENT&&e.type!==Be.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}},{key:"encodeAsBinary",value:function(e){var t=Oe(e),n=this.encodeAsString(t.packet),r=t.buffers;return r.unshift(n),r}}]),e}();function Le(e){return"[object Object]"===Object.prototype.toString.call(e)}var xe=function(e){o(i,e);var n=l(i);function i(e){var r;return t(this,i),(r=n.call(this)).reviver=e,r}return r(i,[{key:"add",value:function(e){var t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");var n=(t=this.decodeString(e)).type===Be.BINARY_EVENT;n||t.type===Be.BINARY_ACK?(t.type=n?Be.EVENT:Be.ACK,this.reconstructor=new Pe(t),0===t.attachments&&p(s(i.prototype),"emitReserved",this).call(this,"decoded",t)):p(s(i.prototype),"emitReserved",this).call(this,"decoded",t)}else{if(!Ee(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(t=this.reconstructor.takeBinaryData(e))&&(this.reconstructor=null,p(s(i.prototype),"emitReserved",this).call(this,"decoded",t))}}},{key:"decodeString",value:function(e){var t=0,n={type:Number(e.charAt(0))};if(void 0===Be[n.type])throw new Error("unknown packet type "+n.type);if(n.type===Be.BINARY_EVENT||n.type===Be.BINARY_ACK){for(var r=t+1;"-"!==e.charAt(++t)&&t!=e.length;);var o=e.substring(r,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===e.charAt(t+1)){for(var s=t+1;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(s,t)}else n.nsp="/";var a=e.charAt(t+1);if(""!==a&&Number(a)==a){for(var c=t+1;++t;){var u=e.charAt(t);if(null==u||Number(u)!=u){--t;break}if(t===e.length)break}n.id=Number(e.substring(c,t+1))}if(e.charAt(++t)){var h=this.tryParse(e.substr(t));if(!i.isPayloadValid(n.type,h))throw new Error("invalid payload");n.data=h}return n}},{key:"tryParse",value:function(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}},{key:"destroy",value:function(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}],[{key:"isPayloadValid",value:function(e,t){switch(e){case Be.CONNECT:return Le(t);case Be.DISCONNECT:return void 0===t;case Be.CONNECT_ERROR:return"string"==typeof t||Le(t);case Be.EVENT:case Be.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Se.indexOf(t[0]));case Be.ACK:case Be.BINARY_ACK:return Array.isArray(t)}}}]),i}(U),Pe=function(){function e(n){t(this,e),this.packet=n,this.buffers=[],this.reconPack=n}return r(e,[{key:"takeBinaryData",value:function(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){var t=Re(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}},{key:"finishedReconstruction",value:function(){this.reconPack=null,this.buffers=[]}}]),e}(),je=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Be},Encoder:Ne,Decoder:xe});function qe(e,t,n){return e.on(t,n),function(){e.off(t,n)}}var De=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ue=function(e){o(a,e);var n=l(a);function a(e,r,o){var s;return t(this,a),(s=n.call(this)).connected=!1,s.recovered=!1,s.receiveBuffer=[],s.sendBuffer=[],s._queue=[],s._queueSeq=0,s.ids=0,s.acks={},s.flags={},s.io=e,s.nsp=r,o&&o.auth&&(s.auth=o.auth),s._opts=i({},o),s.io._autoConnect&&s.open(),s}return r(a,[{key:"disconnected",get:function(){return!this.connected}},{key:"subEvents",value:function(){if(!this.subs){var e=this.io;this.subs=[qe(e,"open",this.onopen.bind(this)),qe(e,"packet",this.onpacket.bind(this)),qe(e,"error",this.onerror.bind(this)),qe(e,"close",this.onclose.bind(this))]}}},{key:"active",get:function(){return!!this.subs}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.unshift("message"),this.emit.apply(this,t),this}},{key:"emit",value:function(e){if(De.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(n.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;var i={type:Be.EVENT,data:n,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof n[n.length-1]){var o=this.ids++,s=n.pop();this._registerAckCallback(o,s),i.id=o}var a=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!a||!this.connected)||(this.connected?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}},{key:"_registerAckCallback",value:function(e,t){var n,r=this,i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0!==i){var o=this.io.setTimeoutFn((function(){delete r.acks[e];for(var n=0;n<r.sendBuffer.length;n++)r.sendBuffer[n].id===e&&r.sendBuffer.splice(n,1);t.call(r,new Error("operation has timed out"))}),i),s=function(){r.io.clearTimeoutFn(o);for(var e=arguments.length,n=new Array(e),i=0;i<e;i++)n[i]=arguments[i];t.apply(r,n)};s.withError=!0,this.acks[e]=s}else this.acks[e]=t}},{key:"emitWithAck",value:function(e){for(var t=this,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new Promise((function(n,i){var o=function(e,t){return e?i(e):n(t)};o.withError=!0,r.push(o),t.emit.apply(t,[e].concat(r))}))}},{key:"_addToQueue",value:function(e){var t,n=this;"function"==typeof e[e.length-1]&&(t=e.pop());var r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:i({fromQueue:!0},this.flags)};e.push((function(e){if(r===n._queue[0]){if(null!==e)r.tryCount>n._opts.retries&&(n._queue.shift(),t&&t(e));else if(n._queue.shift(),t){for(var i=arguments.length,o=new Array(i>1?i-1:0),s=1;s<i;s++)o[s-1]=arguments[s];t.apply(void 0,[null].concat(o))}return r.pending=!1,n._drainQueue()}})),this._queue.push(r),this._drainQueue()}},{key:"_drainQueue",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.connected&&0!==this._queue.length){var t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}}},{key:"packet",value:function(e){e.nsp=this.nsp,this.io._packet(e)}},{key:"onopen",value:function(){var e=this;"function"==typeof this.auth?this.auth((function(t){e._sendConnectPacket(t)})):this._sendConnectPacket(this.auth)}},{key:"_sendConnectPacket",value:function(e){this.packet({type:Be.CONNECT,data:this._pid?i({pid:this._pid,offset:this._lastOffset},e):e})}},{key:"onerror",value:function(e){this.connected||this.emitReserved("connect_error",e)}},{key:"onclose",value:function(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}},{key:"_clearAcks",value:function(){var e=this;Object.keys(this.acks).forEach((function(t){if(!e.sendBuffer.some((function(e){return String(e.id)===t}))){var n=e.acks[t];delete e.acks[t],n.withError&&n.call(e,new Error("socket has been disconnected"))}}))}},{key:"onpacket",value:function(e){if(e.nsp===this.nsp)switch(e.type){case Be.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("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 Be.EVENT:case Be.BINARY_EVENT:this.onevent(e);break;case Be.ACK:case Be.BINARY_ACK:this.onack(e);break;case Be.DISCONNECT:this.ondisconnect();break;case Be.CONNECT_ERROR:this.destroy();var t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}},{key:"onevent",value:function(e){var t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}},{key:"emitEvent",value:function(e){if(this._anyListeners&&this._anyListeners.length){var t,n=y(this._anyListeners.slice());try{for(n.s();!(t=n.n()).done;){t.value.apply(this,e)}}catch(e){n.e(e)}finally{n.f()}}p(s(a.prototype),"emit",this).apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}},{key:"ack",value:function(e){var t=this,n=!1;return function(){if(!n){n=!0;for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];t.packet({type:Be.ACK,id:e,data:i})}}}},{key:"onack",value:function(e){var t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}},{key:"onconnect",value:function(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}},{key:"emitBuffered",value:function(){var e=this;this.receiveBuffer.forEach((function(t){return e.emitEvent(t)})),this.receiveBuffer=[],this.sendBuffer.forEach((function(t){e.notifyOutgoingListeners(t),e.packet(t)})),this.sendBuffer=[]}},{key:"ondisconnect",value:function(){this.destroy(),this.onclose("io server disconnect")}},{key:"destroy",value:function(){this.subs&&(this.subs.forEach((function(e){return e()})),this.subs=void 0),this.io._destroy(this)}},{key:"disconnect",value:function(){return this.connected&&this.packet({type:Be.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}},{key:"close",value:function(){return this.disconnect()}},{key:"compress",value:function(e){return this.flags.compress=e,this}},{key:"volatile",get:function(){return this.flags.volatile=!0,this}},{key:"timeout",value:function(e){return this.flags.timeout=e,this}},{key:"onAny",value:function(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}},{key:"prependAny",value:function(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}},{key:"offAny",value:function(e){if(!this._anyListeners)return this;if(e){for(var t=this._anyListeners,n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}},{key:"listenersAny",value:function(){return this._anyListeners||[]}},{key:"onAnyOutgoing",value:function(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}},{key:"prependAnyOutgoing",value:function(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}},{key:"offAnyOutgoing",value:function(e){if(!this._anyOutgoingListeners)return this;if(e){for(var t=this._anyOutgoingListeners,n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}},{key:"listenersAnyOutgoing",value:function(){return this._anyOutgoingListeners||[]}},{key:"notifyOutgoingListeners",value:function(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){var t,n=y(this._anyOutgoingListeners.slice());try{for(n.s();!(t=n.n()).done;){t.value.apply(this,e.data)}}catch(e){n.e(e)}finally{n.f()}}}}]),a}(U);function Ie(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ie.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-n:e+n}return 0|Math.min(e,this.max)},Ie.prototype.reset=function(){this.attempts=0},Ie.prototype.setMin=function(e){this.ms=e},Ie.prototype.setMax=function(e){this.max=e},Ie.prototype.setJitter=function(e){this.jitter=e};var Fe=function(n){o(s,n);var i=l(s);function s(n,r){var o,a;t(this,s),(o=i.call(this)).nsps={},o.subs=[],n&&"object"===e(n)&&(r=n,n=void 0),(r=r||{}).path=r.path||"/socket.io",o.opts=r,H(f(o),r),o.reconnection(!1!==r.reconnection),o.reconnectionAttempts(r.reconnectionAttempts||1/0),o.reconnectionDelay(r.reconnectionDelay||1e3),o.reconnectionDelayMax(r.reconnectionDelayMax||5e3),o.randomizationFactor(null!==(a=r.randomizationFactor)&&void 0!==a?a:.5),o.backoff=new Ie({min:o.reconnectionDelay(),max:o.reconnectionDelayMax(),jitter:o.randomizationFactor()}),o.timeout(null==r.timeout?2e4:r.timeout),o._readyState="closed",o.uri=n;var c=r.parser||je;return o.encoder=new c.Encoder,o.decoder=new c.Decoder,o._autoConnect=!1!==r.autoConnect,o._autoConnect&&o.open(),o}return r(s,[{key:"reconnection",value:function(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}},{key:"reconnectionAttempts",value:function(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}},{key:"reconnectionDelay",value:function(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}},{key:"randomizationFactor",value:function(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}},{key:"reconnectionDelayMax",value:function(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}},{key:"timeout",value:function(e){return arguments.length?(this._timeout=e,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(e){var t=this;if(~this._readyState.indexOf("open"))return this;this.engine=new ge(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var i=qe(n,"open",(function(){r.onopen(),e&&e()})),o=function(n){t.cleanup(),t._readyState="closed",t.emitReserved("error",n),e?e(n):t.maybeReconnectOnOpen()},s=qe(n,"error",o);if(!1!==this._timeout){var a=this._timeout,c=this.setTimeoutFn((function(){i(),o(new Error("timeout")),n.close()}),a);this.opts.autoUnref&&c.unref(),this.subs.push((function(){t.clearTimeoutFn(c)}))}return this.subs.push(i),this.subs.push(s),this}},{key:"connect",value:function(e){return this.open(e)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",this.emitReserved("open");var e=this.engine;this.subs.push(qe(e,"ping",this.onping.bind(this)),qe(e,"data",this.ondata.bind(this)),qe(e,"error",this.onerror.bind(this)),qe(e,"close",this.onclose.bind(this)),qe(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){this.emitReserved("ping")}},{key:"ondata",value:function(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}},{key:"ondecoded",value:function(e){var t=this;ce((function(){t.emitReserved("packet",e)}),this.setTimeoutFn)}},{key:"onerror",value:function(e){this.emitReserved("error",e)}},{key:"socket",value:function(e,t){var n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new Ue(this,e,t),this.nsps[e]=n),n}},{key:"_destroy",value:function(e){for(var t=0,n=Object.keys(this.nsps);t<n.length;t++){var r=n[t];if(this.nsps[r].active)return}this._close()}},{key:"_packet",value:function(e){for(var t=this.encoder.encode(e),n=0;n<t.length;n++)this.engine.write(t[n],e.options)}},{key:"cleanup",value:function(){this.subs.forEach((function(e){return e()})),this.subs.length=0,this.decoder.destroy()}},{key:"_close",value:function(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}},{key:"disconnect",value:function(){return this._close()}},{key:"onclose",value:function(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}},{key:"reconnect",value:function(){var e=this;if(this._reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{var n=this.backoff.duration();this._reconnecting=!0;var r=this.setTimeoutFn((function(){t.skipReconnect||(e.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open((function(n){n?(t._reconnecting=!1,t.reconnect(),e.emitReserved("reconnect_error",n)):t.onreconnect()})))}),n);this.opts.autoUnref&&r.unref(),this.subs.push((function(){e.clearTimeoutFn(r)}))}}},{key:"onreconnect",value:function(){var e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}]),s}(U),Me={};function Ve(t,n){"object"===e(t)&&(n=t,t=void 0);var r,i=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0,r=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),r=ve(e)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+t,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(t,(n=n||{}).path||"/socket.io"),o=i.source,s=i.id,a=i.path,c=Me[s]&&a in Me[s].nsps;return n.forceNew||n["force new connection"]||!1===n.multiplex||c?r=new Fe(o,n):(Me[s]||(Me[s]=new Fe(o,n)),r=Me[s]),i.query&&!n.query&&(n.query=i.queryKey),r.socket(i.path,n)}return i(Ve,{Manager:Fe,Socket:Ue,io:Ve,connect:Ve}),Ve}));
7
+ //# sourceMappingURL=socket.io.min.js.map
ndcc/lib/client-dist/socket.io.min.js.map ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/client-dist/socket.io.msgpack.min.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ /*!
2
+ * Socket.IO v4.7.5
3
+ * (c) 2014-2024 Guillermo Rauch
4
+ * Released under the MIT License.
5
+ */
6
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).io=e()}(this,(function(){"use strict";function t(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(n){if("default"!==n&&!(n in t)){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}}))})),Object.freeze(t)}function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e(t)}function n(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function r(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,(i=r.key,o=void 0,"symbol"==typeof(o=function(t,e){if("object"!=typeof t||null===t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(i,"string"))?o:String(o)),r)}var i,o}function i(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function o(){return o=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},o.apply(this,arguments)}function s(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&u(t,e)}function a(t){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},a(t)}function u(t,e){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},u(t,e)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function h(t,e,n){return h=c()?Reflect.construct.bind():function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&u(i,n.prototype),i},h.apply(null,arguments)}function f(t){var e="function"==typeof Map?new Map:void 0;return f=function(t){if(null===t||(n=t,-1===Function.toString.call(n).indexOf("[native code]")))return t;var n;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return h(t,arguments,a(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),u(r,t)},f(t)}function l(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function p(t){var e=c();return function(){var n,r=a(t);if(e){var i=a(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return function(t,e){if(e&&("object"==typeof e||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return l(t)}(this,n)}}function d(){return d="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,n){var r=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(r){var i=Object.getOwnPropertyDescriptor(r,e);return i.get?i.get.call(arguments.length<3?t:n):i.value}},d.apply(this,arguments)}function y(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n<e;n++)r[n]=t[n];return r}function v(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=function(t,e){if(t){if("string"==typeof t)return y(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?y(t,e):void 0}}(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,i=function(){};return{s:i,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:i}}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 o,s=!0,a=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return s=t.done,t},e:function(t){a=!0,o=t},f:function(){try{s||null==n.return||n.return()}finally{if(a)throw o}}}}var g=Object.create(null);g.open="0",g.close="1",g.ping="2",g.pong="3",g.message="4",g.upgrade="5",g.noop="6";var m=Object.create(null);Object.keys(g).forEach((function(t){m[g[t]]=t}));var _,b={type:"error",data:"parser error"},k="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),w="function"==typeof ArrayBuffer,O=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer},E=function(t,e,n){var r=t.type,i=t.data;return k&&i instanceof Blob?e?n(i):T(i,n):w&&(i instanceof ArrayBuffer||O(i))?e?n(i):T(new Blob([i]),n):n(g[r]+(i||""))},T=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function C(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}for(var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",R="undefined"==typeof Uint8Array?[]:new Uint8Array(256),S=0;S<64;S++)R[A.charCodeAt(S)]=S;var L,U="function"==typeof ArrayBuffer,x=function(t,e){if("string"!=typeof t)return{type:"message",data:q(t,e)};var n=t.charAt(0);return"b"===n?{type:"message",data:B(t.substring(1),e)}:m[n]?t.length>1?{type:m[n],data:t.substring(1)}:{type:m[n]}:b},B=function(t,e){if(U){var n=function(t){var e,n,r,i,o,s=.75*t.length,a=t.length,u=0;"="===t[t.length-1]&&(s--,"="===t[t.length-2]&&s--);var c=new ArrayBuffer(s),h=new Uint8Array(c);for(e=0;e<a;e+=4)n=R[t.charCodeAt(e)],r=R[t.charCodeAt(e+1)],i=R[t.charCodeAt(e+2)],o=R[t.charCodeAt(e+3)],h[u++]=n<<2|r>>4,h[u++]=(15&r)<<4|i>>2,h[u++]=(3&i)<<6|63&o;return c}(t);return q(n,e)}return{base64:!0,data:t}},q=function(t,e){return"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer},P=String.fromCharCode(30);function j(){return new TransformStream({transform:function(t,e){!function(t,e){k&&t.data instanceof Blob?t.data.arrayBuffer().then(C).then(e):w&&(t.data instanceof ArrayBuffer||O(t.data))?e(C(t.data)):E(t,!1,(function(t){_||(_=new TextEncoder),e(_.encode(t))}))}(t,(function(n){var r,i=n.length;if(i<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,i);else if(i<65536){r=new Uint8Array(3);var o=new DataView(r.buffer);o.setUint8(0,126),o.setUint16(1,i)}else{r=new Uint8Array(9);var s=new DataView(r.buffer);s.setUint8(0,127),s.setBigUint64(1,BigInt(i))}t.data&&"string"!=typeof t.data&&(r[0]|=128),e.enqueue(r),e.enqueue(n)}))}})}function D(t){return t.reduce((function(t,e){return t+e.length}),0)}function N(t,e){if(t[0].length===e)return t.shift();for(var n=new Uint8Array(e),r=0,i=0;i<e;i++)n[i]=t[0][r++],r===t[0].length&&(t.shift(),r=0);return t.length&&r<t[0].length&&(t[0]=t[0].slice(r)),n}function M(t){if(t)return function(t){for(var e in M.prototype)t[e]=M.prototype[e];return t}(t)}M.prototype.on=M.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},M.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},M.prototype.off=M.prototype.removeListener=M.prototype.removeAllListeners=M.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},M.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,e)}return this},M.prototype.emitReserved=M.prototype.emit,M.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},M.prototype.hasListeners=function(t){return!!this.listeners(t).length};var I="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function F(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return n.reduce((function(e,n){return t.hasOwnProperty(n)&&(e[n]=t[n]),e}),{})}var H=I.setTimeout,$=I.clearTimeout;function V(t,e){e.useNativeTimers?(t.setTimeoutFn=H.bind(I),t.clearTimeoutFn=$.bind(I)):(t.setTimeoutFn=I.setTimeout.bind(I),t.clearTimeoutFn=I.clearTimeout.bind(I))}var W,z=function(t){s(r,t);var e=p(r);function r(t,i,o){var s;return n(this,r),(s=e.call(this,t)).description=i,s.context=o,s.type="TransportError",s}return i(r)}(f(Error)),J=function(t){s(r,t);var e=p(r);function r(t){var i;return n(this,r),(i=e.call(this)).writable=!1,V(l(i),t),i.opts=t,i.query=t.query,i.socket=t.socket,i}return i(r,[{key:"onError",value:function(t,e,n){return d(a(r.prototype),"emitReserved",this).call(this,"error",new z(t,e,n)),this}},{key:"open",value:function(){return this.readyState="opening",this.doOpen(),this}},{key:"close",value:function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}},{key:"send",value:function(t){"open"===this.readyState&&this.write(t)}},{key:"onOpen",value:function(){this.readyState="open",this.writable=!0,d(a(r.prototype),"emitReserved",this).call(this,"open")}},{key:"onData",value:function(t){var e=x(t,this.socket.binaryType);this.onPacket(e)}},{key:"onPacket",value:function(t){d(a(r.prototype),"emitReserved",this).call(this,"packet",t)}},{key:"onClose",value:function(t){this.readyState="closed",d(a(r.prototype),"emitReserved",this).call(this,"close",t)}},{key:"pause",value:function(t){}},{key:"createUri",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t+"://"+this._hostname()+this._port()+this.opts.path+this._query(e)}},{key:"_hostname",value:function(){var t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}},{key:"_port",value:function(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}},{key:"_query",value:function(t){var e=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}]),r}(M),Q="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),X=64,K={},G=0,Y=0;function Z(t){var e="";do{e=Q[t%X]+e,t=Math.floor(t/X)}while(t>0);return e}function tt(){var t=Z(+new Date);return t!==W?(G=0,W=t):t+"."+Z(G++)}for(;Y<X;Y++)K[Q[Y]]=Y;var et=!1;try{et="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}var nt=et;function rt(t){var e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||nt))return new XMLHttpRequest}catch(t){}if(!e)try{return new(I[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}function it(){}var ot=null!=new rt({xdomain:!1}).responseType,st=function(t){s(r,t);var e=p(r);function r(t){var i;if(n(this,r),(i=e.call(this,t)).polling=!1,"undefined"!=typeof location){var o="https:"===location.protocol,s=location.port;s||(s=o?"443":"80"),i.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}var a=t&&t.forceBase64;return i.supportsBinary=ot&&!a,i.opts.withCredentials&&(i.cookieJar=void 0),i}return i(r,[{key:"name",get:function(){return"polling"}},{key:"doOpen",value:function(){this.poll()}},{key:"pause",value:function(t){var e=this;this.readyState="pausing";var n=function(){e.readyState="paused",t()};if(this.polling||!this.writable){var r=0;this.polling&&(r++,this.once("pollComplete",(function(){--r||n()}))),this.writable||(r++,this.once("drain",(function(){--r||n()})))}else n()}},{key:"poll",value:function(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}},{key:"onData",value:function(t){var e=this;(function(t,e){for(var n=t.split(P),r=[],i=0;i<n.length;i++){var o=x(n[i],e);if(r.push(o),"error"===o.type)break}return r})(t,this.socket.binaryType).forEach((function(t){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose({description:"transport closed by the server"}),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}},{key:"doClose",value:function(){var t=this,e=function(){t.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}},{key:"write",value:function(t){var e=this;this.writable=!1,function(t,e){var n=t.length,r=new Array(n),i=0;t.forEach((function(t,o){E(t,!1,(function(t){r[o]=t,++i===n&&e(r.join(P))}))}))}(t,(function(t){e.doWrite(t,(function(){e.writable=!0,e.emitReserved("drain")}))}))}},{key:"uri",value:function(){var t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=tt()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}},{key:"request",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return o(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new at(this.uri(),t)}},{key:"doWrite",value:function(t,e){var n=this,r=this.request({method:"POST",data:t});r.on("success",e),r.on("error",(function(t,e){n.onError("xhr post error",t,e)}))}},{key:"doPoll",value:function(){var t=this,e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(function(e,n){t.onError("xhr poll error",e,n)})),this.pollXhr=e}}]),r}(J),at=function(t){s(r,t);var e=p(r);function r(t,i){var o;return n(this,r),V(l(o=e.call(this)),i),o.opts=i,o.method=i.method||"GET",o.uri=t,o.data=void 0!==i.data?i.data:null,o.create(),o}return i(r,[{key:"create",value:function(){var t,e=this,n=F(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;var i=this.xhr=new rt(n);try{i.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders)for(var o in i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0),this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&i.setRequestHeader(o,this.opts.extraHeaders[o])}catch(t){}if("POST"===this.method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{i.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(i.timeout=this.opts.requestTimeout),i.onreadystatechange=function(){var t;3===i.readyState&&(null===(t=e.opts.cookieJar)||void 0===t||t.parseCookies(i)),4===i.readyState&&(200===i.status||1223===i.status?e.onLoad():e.setTimeoutFn((function(){e.onError("number"==typeof i.status?i.status:0)}),0))},i.send(this.data)}catch(t){return void this.setTimeoutFn((function(){e.onError(t)}),0)}"undefined"!=typeof document&&(this.index=r.requestsCount++,r.requests[this.index]=this)}},{key:"onError",value:function(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}},{key:"cleanup",value:function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=it,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete r.requests[this.index],this.xhr=null}}},{key:"onLoad",value:function(){var t=this.xhr.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}},{key:"abort",value:function(){this.cleanup()}}]),r}(M);if(at.requestsCount=0,at.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ut);else if("function"==typeof addEventListener){addEventListener("onpagehide"in I?"pagehide":"unload",ut,!1)}function ut(){for(var t in at.requests)at.requests.hasOwnProperty(t)&&at.requests[t].abort()}var ct="function"==typeof Promise&&"function"==typeof Promise.resolve?function(t){return Promise.resolve().then(t)}:function(t,e){return e(t,0)},ht=I.WebSocket||I.MozWebSocket,ft="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),lt=function(t){s(r,t);var e=p(r);function r(t){var i;return n(this,r),(i=e.call(this,t)).supportsBinary=!t.forceBase64,i}return i(r,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=ft?{}:F(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=ft?new ht(t,e,n):e?new ht(t,e):new ht(t)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}}},{key:"addEventListeners",value:function(){var t=this;this.ws.onopen=function(){t.opts.autoUnref&&t.ws._socket.unref(),t.onOpen()},this.ws.onclose=function(e){return t.onClose({description:"websocket connection closed",context:e})},this.ws.onmessage=function(e){return t.onData(e.data)},this.ws.onerror=function(e){return t.onError("websocket error",e)}}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var n=function(){var n=t[r],i=r===t.length-1;E(n,e.supportsBinary,(function(t){try{e.ws.send(t)}catch(t){}i&&ct((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;r<t.length;r++)n()}},{key:"doClose",value:function(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}},{key:"uri",value:function(){var t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=tt()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}},{key:"check",value:function(){return!!ht}}]),r}(J),pt=function(t){s(r,t);var e=p(r);function r(){return n(this,r),e.apply(this,arguments)}return i(r,[{key:"name",get:function(){return"webtransport"}},{key:"doOpen",value:function(){var t=this;"function"==typeof WebTransport&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then((function(){t.onClose()})).catch((function(e){t.onError("webtransport error",e)})),this.transport.ready.then((function(){t.transport.createBidirectionalStream().then((function(e){var n=function(t,e){L||(L=new TextDecoder);var n=[],r=0,i=-1,o=!1;return new TransformStream({transform:function(s,a){for(n.push(s);;){if(0===r){if(D(n)<1)break;var u=N(n,1);o=128==(128&u[0]),i=127&u[0],r=i<126?3:126===i?1:2}else if(1===r){if(D(n)<2)break;var c=N(n,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(2===r){if(D(n)<8)break;var h=N(n,8),f=new DataView(h.buffer,h.byteOffset,h.length),l=f.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(b);break}i=l*Math.pow(2,32)+f.getUint32(4),r=3}else{if(D(n)<i)break;var p=N(n,i);a.enqueue(x(o?p:L.decode(p),e)),r=0}if(0===i||i>t){a.enqueue(b);break}}}})}(Number.MAX_SAFE_INTEGER,t.socket.binaryType),r=e.readable.pipeThrough(n).getReader(),i=j();i.readable.pipeTo(e.writable),t.writer=i.writable.getWriter();!function e(){r.read().then((function(n){var r=n.done,i=n.value;r||(t.onPacket(i),e())})).catch((function(t){}))}();var o={type:"open"};t.query.sid&&(o.data='{"sid":"'.concat(t.query.sid,'"}')),t.writer.write(o).then((function(){return t.onOpen()}))}))})))}},{key:"write",value:function(t){var e=this;this.writable=!1;for(var n=function(){var n=t[r],i=r===t.length-1;e.writer.write(n).then((function(){i&&ct((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;r<t.length;r++)n()}},{key:"doClose",value:function(){var t;null===(t=this.transport)||void 0===t||t.close()}}]),r}(J),dt={websocket:lt,webtransport:pt,polling:st},yt=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,vt=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function gt(t){var e=t,n=t.indexOf("["),r=t.indexOf("]");-1!=n&&-1!=r&&(t=t.substring(0,n)+t.substring(n,r).replace(/:/g,";")+t.substring(r,t.length));for(var i,o,s=yt.exec(t||""),a={},u=14;u--;)a[vt[u]]=s[u]||"";return-1!=n&&-1!=r&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(t,e){var n=/\/{2,9}/g,r=e.replace(n,"/").split("/");"/"!=e.slice(0,1)&&0!==e.length||r.splice(0,1);"/"==e.slice(-1)&&r.splice(r.length-1,1);return r}(0,a.path),a.queryKey=(i=a.query,o={},i.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(o[e]=n)})),o),a}var mt=function(t){s(a,t);var r=p(a);function a(t){var i,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return n(this,a),(i=r.call(this)).binaryType="arraybuffer",i.writeBuffer=[],t&&"object"===e(t)&&(s=t,t=null),t?(t=gt(t),s.hostname=t.host,s.secure="https"===t.protocol||"wss"===t.protocol,s.port=t.port,t.query&&(s.query=t.query)):s.host&&(s.hostname=gt(s.host).host),V(l(i),s),i.secure=null!=s.secure?s.secure:"undefined"!=typeof location&&"https:"===location.protocol,s.hostname&&!s.port&&(s.port=i.secure?"443":"80"),i.hostname=s.hostname||("undefined"!=typeof location?location.hostname:"localhost"),i.port=s.port||("undefined"!=typeof location&&location.port?location.port:i.secure?"443":"80"),i.transports=s.transports||["polling","websocket","webtransport"],i.writeBuffer=[],i.prevBufferLen=0,i.opts=o({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},s),i.opts.path=i.opts.path.replace(/\/$/,"")+(i.opts.addTrailingSlash?"/":""),"string"==typeof i.opts.query&&(i.opts.query=function(t){for(var e={},n=t.split("&"),r=0,i=n.length;r<i;r++){var o=n[r].split("=");e[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return e}(i.opts.query)),i.id=null,i.upgrades=null,i.pingInterval=null,i.pingTimeout=null,i.pingTimeoutTimer=null,"function"==typeof addEventListener&&(i.opts.closeOnBeforeunload&&(i.beforeunloadEventListener=function(){i.transport&&(i.transport.removeAllListeners(),i.transport.close())},addEventListener("beforeunload",i.beforeunloadEventListener,!1)),"localhost"!==i.hostname&&(i.offlineEventListener=function(){i.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",i.offlineEventListener,!1))),i.open(),i}return i(a,[{key:"createTransport",value:function(t){var e=o({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);var n=o({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new dt[t](n)}},{key:"open",value:function(){var t,e=this;if(this.opts.rememberUpgrade&&a.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((function(){e.emitReserved("error","No transports available")}),0);t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)}},{key:"setTransport",value:function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(function(t){return e.onClose("transport close",t)}))}},{key:"probe",value:function(t){var e=this,n=this.createTransport(t),r=!1;a.priorWebsocketSuccess=!1;var i=function(){r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",(function(t){if(!r)if("pong"===t.type&&"probe"===t.data){if(e.upgrading=!0,e.emitReserved("upgrading",n),!n)return;a.priorWebsocketSuccess="websocket"===n.name,e.transport.pause((function(){r||"closed"!==e.readyState&&(f(),e.setTransport(n),n.send([{type:"upgrade"}]),e.emitReserved("upgrade",n),n=null,e.upgrading=!1,e.flush())}))}else{var i=new Error("probe error");i.transport=n.name,e.emitReserved("upgradeError",i)}})))};function o(){r||(r=!0,f(),n.close(),n=null)}var s=function(t){var r=new Error("probe error: "+t);r.transport=n.name,o(),e.emitReserved("upgradeError",r)};function u(){s("transport closed")}function c(){s("socket closed")}function h(t){n&&t.name!==n.name&&o()}var f=function(){n.removeListener("open",i),n.removeListener("error",s),n.removeListener("close",u),e.off("close",c),e.off("upgrading",h)};n.once("open",i),n.once("error",s),n.once("close",u),this.once("close",c),this.once("upgrading",h),-1!==this.upgrades.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn((function(){r||n.open()}),200):n.open()}},{key:"onOpen",value:function(){if(this.readyState="open",a.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},{key:"onPacket",value:function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),this.resetPingTimeout(),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}},{key:"onHandshake",value:function(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.maxPayload=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}},{key:"resetPingTimeout",value:function(){var t=this;this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((function(){t.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}},{key:"onDrain",value:function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}},{key:"flush",value:function(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){var t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}},{key:"getWritablePackets",value:function(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;for(var t,e=1,n=0;n<this.writeBuffer.length;n++){var r=this.writeBuffer[n].data;if(r&&(e+="string"==typeof(t=r)?function(t){for(var e=0,n=0,r=0,i=t.length;r<i;r++)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}(t):Math.ceil(1.33*(t.byteLength||t.size))),n>0&&e>this.maxPayload)return this.writeBuffer.slice(0,n);e+=2}return this.writeBuffer}},{key:"write",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"send",value:function(t,e,n){return this.sendPacket("message",t,e,n),this}},{key:"sendPacket",value:function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),r&&this.once("flush",r),this.flush()}}},{key:"close",value:function(){var t=this,e=function(){t.onClose("forced close"),t.transport.close()},n=function n(){t.off("upgrade",n),t.off("upgradeError",n),e()},r=function(){t.once("upgrade",n),t.once("upgradeError",n)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(function(){t.upgrading?r():e()})):this.upgrading?r():e()),this}},{key:"onError",value:function(t){a.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}},{key:"onClose",value:function(t,e){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.prevBufferLen=0)}},{key:"filterUpgrades",value:function(t){for(var e=[],n=0,r=t.length;n<r;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}]),a}(M);mt.protocol=4,mt.protocol;var _t={},bt={};function kt(t,e,n){for(var r=0,i=0,o=n.length;i<o;i++)(r=n.charCodeAt(i))<128?t.setUint8(e++,r):r<2048?(t.setUint8(e++,192|r>>6),t.setUint8(e++,128|63&r)):r<55296||r>=57344?(t.setUint8(e++,224|r>>12),t.setUint8(e++,128|r>>6&63),t.setUint8(e++,128|63&r)):(i++,r=65536+((1023&r)<<10|1023&n.charCodeAt(i)),t.setUint8(e++,240|r>>18),t.setUint8(e++,128|r>>12&63),t.setUint8(e++,128|r>>6&63),t.setUint8(e++,128|63&r))}function wt(t,n,r){var i=e(r),o=0,s=0,a=0,u=0,c=0,h=0;if("string"===i){if(c=function(t){for(var e=0,n=0,r=0,i=t.length;r<i;r++)(e=t.charCodeAt(r))<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(r++,n+=4);return n}(r),c<32)t.push(160|c),h=1;else if(c<256)t.push(217,c),h=2;else if(c<65536)t.push(218,c>>8,c),h=3;else{if(!(c<4294967296))throw new Error("String too long");t.push(219,c>>24,c>>16,c>>8,c),h=5}return n.push({_str:r,_length:c,_offset:t.length}),h+c}if("number"===i)return Math.floor(r)===r&&isFinite(r)?r>=0?r<128?(t.push(r),1):r<256?(t.push(204,r),2):r<65536?(t.push(205,r>>8,r),3):r<4294967296?(t.push(206,r>>24,r>>16,r>>8,r),5):(a=r/Math.pow(2,32)>>0,u=r>>>0,t.push(207,a>>24,a>>16,a>>8,a,u>>24,u>>16,u>>8,u),9):r>=-32?(t.push(r),1):r>=-128?(t.push(208,r),2):r>=-32768?(t.push(209,r>>8,r),3):r>=-2147483648?(t.push(210,r>>24,r>>16,r>>8,r),5):(a=Math.floor(r/Math.pow(2,32)),u=r>>>0,t.push(211,a>>24,a>>16,a>>8,a,u>>24,u>>16,u>>8,u),9):(t.push(203),n.push({_float:r,_length:8,_offset:t.length}),9);if("object"===i){if(null===r)return t.push(192),1;if(Array.isArray(r)){if((c=r.length)<16)t.push(144|c),h=1;else if(c<65536)t.push(220,c>>8,c),h=3;else{if(!(c<4294967296))throw new Error("Array too large");t.push(221,c>>24,c>>16,c>>8,c),h=5}for(o=0;o<c;o++)h+=wt(t,n,r[o]);return h}if(r instanceof Date){var f=r.getTime();return a=Math.floor(f/Math.pow(2,32)),u=f>>>0,t.push(215,0,a>>24,a>>16,a>>8,a,u>>24,u>>16,u>>8,u),10}if(r instanceof ArrayBuffer){if((c=r.byteLength)<256)t.push(196,c),h=2;else if(c<65536)t.push(197,c>>8,c),h=3;else{if(!(c<4294967296))throw new Error("Buffer too large");t.push(198,c>>24,c>>16,c>>8,c),h=5}return n.push({_bin:r,_length:c,_offset:t.length}),h+c}if("function"==typeof r.toJSON)return wt(t,n,r.toJSON());var l=[],p="",d=Object.keys(r);for(o=0,s=d.length;o<s;o++)"function"!=typeof r[p=d[o]]&&l.push(p);if((c=l.length)<16)t.push(128|c),h=1;else if(c<65536)t.push(222,c>>8,c),h=3;else{if(!(c<4294967296))throw new Error("Object too large");t.push(223,c>>24,c>>16,c>>8,c),h=5}for(o=0;o<c;o++)h+=wt(t,n,p=l[o]),h+=wt(t,n,r[p]);return h}if("boolean"===i)return t.push(r?195:194),1;if("undefined"===i)return t.push(212,0,0),3;throw new Error("Could not encode")}var Ot=function(t){var e=[],n=[],r=wt(e,n,t),i=new ArrayBuffer(r),o=new DataView(i),s=0,a=0,u=-1;n.length>0&&(u=n[0]._offset);for(var c,h=0,f=0,l=0,p=e.length;l<p;l++)if(o.setUint8(a+l,e[l]),l+1===u){if(h=(c=n[s])._length,f=a+u,c._bin)for(var d=new Uint8Array(c._bin),y=0;y<h;y++)o.setUint8(f+y,d[y]);else c._str?kt(o,f,c._str):void 0!==c._float&&o.setFloat64(f,c._float);a+=h,n[++s]&&(u=n[s]._offset)}return i};function Et(t){if(this._offset=0,t instanceof ArrayBuffer)this._buffer=t,this._view=new DataView(this._buffer);else{if(!ArrayBuffer.isView(t))throw new Error("Invalid argument");this._buffer=t.buffer,this._view=new DataView(this._buffer,t.byteOffset,t.byteLength)}}Et.prototype._array=function(t){for(var e=new Array(t),n=0;n<t;n++)e[n]=this._parse();return e},Et.prototype._map=function(t){for(var e={},n=0;n<t;n++)e[this._parse()]=this._parse();return e},Et.prototype._str=function(t){var e=function(t,e,n){for(var r="",i=0,o=e,s=e+n;o<s;o++){var a=t.getUint8(o);if(0!=(128&a))if(192!=(224&a))if(224!=(240&a)){if(240!=(248&a))throw new Error("Invalid byte "+a.toString(16));(i=(7&a)<<18|(63&t.getUint8(++o))<<12|(63&t.getUint8(++o))<<6|(63&t.getUint8(++o))<<0)>=65536?(i-=65536,r+=String.fromCharCode(55296+(i>>>10),56320+(1023&i))):r+=String.fromCharCode(i)}else r+=String.fromCharCode((15&a)<<12|(63&t.getUint8(++o))<<6|(63&t.getUint8(++o))<<0);else r+=String.fromCharCode((31&a)<<6|63&t.getUint8(++o));else r+=String.fromCharCode(a)}return r}(this._view,this._offset,t);return this._offset+=t,e},Et.prototype._bin=function(t){var e=this._buffer.slice(this._offset,this._offset+t);return this._offset+=t,e},Et.prototype._parse=function(){var t,e=this._view.getUint8(this._offset++),n=0,r=0,i=0,o=0;if(e<192)return e<128?e:e<144?this._map(15&e):e<160?this._array(15&e):this._str(31&e);if(e>223)return-1*(255-e+1);switch(e){case 192:return null;case 194:return!1;case 195:return!0;case 196:return n=this._view.getUint8(this._offset),this._offset+=1,this._bin(n);case 197:return n=this._view.getUint16(this._offset),this._offset+=2,this._bin(n);case 198:return n=this._view.getUint32(this._offset),this._offset+=4,this._bin(n);case 199:return n=this._view.getUint8(this._offset),r=this._view.getInt8(this._offset+1),this._offset+=2,[r,this._bin(n)];case 200:return n=this._view.getUint16(this._offset),r=this._view.getInt8(this._offset+2),this._offset+=3,[r,this._bin(n)];case 201:return n=this._view.getUint32(this._offset),r=this._view.getInt8(this._offset+4),this._offset+=5,[r,this._bin(n)];case 202:return t=this._view.getFloat32(this._offset),this._offset+=4,t;case 203:return t=this._view.getFloat64(this._offset),this._offset+=8,t;case 204:return t=this._view.getUint8(this._offset),this._offset+=1,t;case 205:return t=this._view.getUint16(this._offset),this._offset+=2,t;case 206:return t=this._view.getUint32(this._offset),this._offset+=4,t;case 207:return i=this._view.getUint32(this._offset)*Math.pow(2,32),o=this._view.getUint32(this._offset+4),this._offset+=8,i+o;case 208:return t=this._view.getInt8(this._offset),this._offset+=1,t;case 209:return t=this._view.getInt16(this._offset),this._offset+=2,t;case 210:return t=this._view.getInt32(this._offset),this._offset+=4,t;case 211:return i=this._view.getInt32(this._offset)*Math.pow(2,32),o=this._view.getUint32(this._offset+4),this._offset+=8,i+o;case 212:return r=this._view.getInt8(this._offset),this._offset+=1,0===r?void(this._offset+=1):[r,this._bin(1)];case 213:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(2)];case 214:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(4)];case 215:return r=this._view.getInt8(this._offset),this._offset+=1,0===r?(i=this._view.getInt32(this._offset)*Math.pow(2,32),o=this._view.getUint32(this._offset+4),this._offset+=8,new Date(i+o)):[r,this._bin(8)];case 216:return r=this._view.getInt8(this._offset),this._offset+=1,[r,this._bin(16)];case 217:return n=this._view.getUint8(this._offset),this._offset+=1,this._str(n);case 218:return n=this._view.getUint16(this._offset),this._offset+=2,this._str(n);case 219:return n=this._view.getUint32(this._offset),this._offset+=4,this._str(n);case 220:return n=this._view.getUint16(this._offset),this._offset+=2,this._array(n);case 221:return n=this._view.getUint32(this._offset),this._offset+=4,this._array(n);case 222:return n=this._view.getUint16(this._offset),this._offset+=2,this._map(n);case 223:return n=this._view.getUint32(this._offset),this._offset+=4,this._map(n)}throw new Error("Could not parse")};var Tt=function(t){var e=new Et(t),n=e._parse();if(e._offset!==t.byteLength)throw new Error(t.byteLength-e._offset+" trailing bytes");return n};bt.encode=Ot,bt.decode=Tt;var Ct,At={exports:{}};!function(t){function e(t){if(t)return function(t){for(var n in e.prototype)t[n]=e.prototype[n];return t}(t)}t.exports=e,e.prototype.on=e.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},e.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var i=0;i<r.length;i++)if((n=r[i])===e||n.fn===e){r.splice(i,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},e.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var i=(n=n.slice(0)).length;r<i;++r)n[r].apply(this,e)}return this},e.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},e.prototype.hasListeners=function(t){return!!this.listeners(t).length}}(At);var Rt=bt,St=At.exports,Lt=_t.protocol=5,Ut=Ct=_t.PacketType={CONNECT:0,DISCONNECT:1,EVENT:2,ACK:3,CONNECT_ERROR:4},xt=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t},Bt=function(t){return"string"==typeof t},qt=function(t){return"[object Object]"===Object.prototype.toString.call(t)};function Pt(){}function jt(){}Pt.prototype.encode=function(t){return[Rt.encode(t)]},St(jt.prototype),jt.prototype.add=function(t){var e=Rt.decode(t);this.checkPacket(e),this.emit("decoded",e)},jt.prototype.checkPacket=function(t){if(!(xt(t.type)&&t.type>=Ut.CONNECT&&t.type<=Ut.CONNECT_ERROR))throw new Error("invalid packet type");if(!Bt(t.nsp))throw new Error("invalid namespace");if(!function(t){switch(t.type){case Ut.CONNECT:return void 0===t.data||qt(t.data);case Ut.DISCONNECT:return void 0===t.data;case Ut.CONNECT_ERROR:return Bt(t.data)||qt(t.data);default:return Array.isArray(t.data)}}(t))throw new Error("invalid payload");if(!(void 0===t.id||xt(t.id)))throw new Error("invalid packet id")},jt.prototype.destroy=function(){};var Dt=_t.Encoder=Pt,Nt=_t.Decoder=jt,Mt=t({__proto__:null,default:_t,protocol:Lt,get PacketType(){return Ct},Encoder:Dt,Decoder:Nt},[_t]);function It(t,e,n){return t.on(e,n),function(){t.off(e,n)}}var Ft=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),Ht=function(t){s(r,t);var e=p(r);function r(t,i,s){var a;return n(this,r),(a=e.call(this)).connected=!1,a.recovered=!1,a.receiveBuffer=[],a.sendBuffer=[],a._queue=[],a._queueSeq=0,a.ids=0,a.acks={},a.flags={},a.io=t,a.nsp=i,s&&s.auth&&(a.auth=s.auth),a._opts=o({},s),a.io._autoConnect&&a.open(),a}return i(r,[{key:"disconnected",get:function(){return!this.connected}},{key:"subEvents",value:function(){if(!this.subs){var t=this.io;this.subs=[It(t,"open",this.onopen.bind(this)),It(t,"packet",this.onpacket.bind(this)),It(t,"error",this.onerror.bind(this)),It(t,"close",this.onclose.bind(this))]}}},{key:"active",get:function(){return!!this.subs}},{key:"connect",value:function(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}},{key:"open",value:function(){return this.connect()}},{key:"send",value:function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.unshift("message"),this.emit.apply(this,e),this}},{key:"emit",value:function(t){if(Ft.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];if(n.unshift(t),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(n),this;var i={type:Ct.EVENT,data:n,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof n[n.length-1]){var o=this.ids++,s=n.pop();this._registerAckCallback(o,s),i.id=o}var a=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!a||!this.connected)||(this.connected?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}},{key:"_registerAckCallback",value:function(t,e){var n,r=this,i=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0!==i){var o=this.io.setTimeoutFn((function(){delete r.acks[t];for(var n=0;n<r.sendBuffer.length;n++)r.sendBuffer[n].id===t&&r.sendBuffer.splice(n,1);e.call(r,new Error("operation has timed out"))}),i),s=function(){r.io.clearTimeoutFn(o);for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];e.apply(r,n)};s.withError=!0,this.acks[t]=s}else this.acks[t]=e}},{key:"emitWithAck",value:function(t){for(var e=this,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new Promise((function(n,i){var o=function(t,e){return t?i(t):n(e)};o.withError=!0,r.push(o),e.emit.apply(e,[t].concat(r))}))}},{key:"_addToQueue",value:function(t){var e,n=this;"function"==typeof t[t.length-1]&&(e=t.pop());var r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:o({fromQueue:!0},this.flags)};t.push((function(t){if(r===n._queue[0]){if(null!==t)r.tryCount>n._opts.retries&&(n._queue.shift(),e&&e(t));else if(n._queue.shift(),e){for(var i=arguments.length,o=new Array(i>1?i-1:0),s=1;s<i;s++)o[s-1]=arguments[s];e.apply(void 0,[null].concat(o))}return r.pending=!1,n._drainQueue()}})),this._queue.push(r),this._drainQueue()}},{key:"_drainQueue",value:function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.connected&&0!==this._queue.length){var e=this._queue[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}}},{key:"packet",value:function(t){t.nsp=this.nsp,this.io._packet(t)}},{key:"onopen",value:function(){var t=this;"function"==typeof this.auth?this.auth((function(e){t._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}},{key:"_sendConnectPacket",value:function(t){this.packet({type:Ct.CONNECT,data:this._pid?o({pid:this._pid,offset:this._lastOffset},t):t})}},{key:"onerror",value:function(t){this.connected||this.emitReserved("connect_error",t)}},{key:"onclose",value:function(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this._clearAcks()}},{key:"_clearAcks",value:function(){var t=this;Object.keys(this.acks).forEach((function(e){if(!t.sendBuffer.some((function(t){return String(t.id)===e}))){var n=t.acks[e];delete t.acks[e],n.withError&&n.call(t,new Error("socket has been disconnected"))}}))}},{key:"onpacket",value:function(t){if(t.nsp===this.nsp)switch(t.type){case Ct.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("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 Ct.EVENT:case Ct.BINARY_EVENT:this.onevent(t);break;case Ct.ACK:case Ct.BINARY_ACK:this.onack(t);break;case Ct.DISCONNECT:this.ondisconnect();break;case Ct.CONNECT_ERROR:this.destroy();var e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}},{key:"onevent",value:function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}},{key:"emitEvent",value:function(t){if(this._anyListeners&&this._anyListeners.length){var e,n=v(this._anyListeners.slice());try{for(n.s();!(e=n.n()).done;){e.value.apply(this,t)}}catch(t){n.e(t)}finally{n.f()}}d(a(r.prototype),"emit",this).apply(this,t),this._pid&&t.length&&"string"==typeof t[t.length-1]&&(this._lastOffset=t[t.length-1])}},{key:"ack",value:function(t){var e=this,n=!1;return function(){if(!n){n=!0;for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];e.packet({type:Ct.ACK,id:t,data:i})}}}},{key:"onack",value:function(t){var e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}},{key:"onconnect",value:function(t,e){this.id=t,this.recovered=e&&this._pid===e,this._pid=e,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}},{key:"emitBuffered",value:function(){var t=this;this.receiveBuffer.forEach((function(e){return t.emitEvent(e)})),this.receiveBuffer=[],this.sendBuffer.forEach((function(e){t.notifyOutgoingListeners(e),t.packet(e)})),this.sendBuffer=[]}},{key:"ondisconnect",value:function(){this.destroy(),this.onclose("io server disconnect")}},{key:"destroy",value:function(){this.subs&&(this.subs.forEach((function(t){return t()})),this.subs=void 0),this.io._destroy(this)}},{key:"disconnect",value:function(){return this.connected&&this.packet({type:Ct.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}},{key:"close",value:function(){return this.disconnect()}},{key:"compress",value:function(t){return this.flags.compress=t,this}},{key:"volatile",get:function(){return this.flags.volatile=!0,this}},{key:"timeout",value:function(t){return this.flags.timeout=t,this}},{key:"onAny",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}},{key:"prependAny",value:function(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}},{key:"offAny",value:function(t){if(!this._anyListeners)return this;if(t){for(var e=this._anyListeners,n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyListeners=[];return this}},{key:"listenersAny",value:function(){return this._anyListeners||[]}},{key:"onAnyOutgoing",value:function(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(t),this}},{key:"prependAnyOutgoing",value:function(t){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(t),this}},{key:"offAnyOutgoing",value:function(t){if(!this._anyOutgoingListeners)return this;if(t){for(var e=this._anyOutgoingListeners,n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this._anyOutgoingListeners=[];return this}},{key:"listenersAnyOutgoing",value:function(){return this._anyOutgoingListeners||[]}},{key:"notifyOutgoingListeners",value:function(t){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){var e,n=v(this._anyOutgoingListeners.slice());try{for(n.s();!(e=n.n()).done;){e.value.apply(this,t.data)}}catch(t){n.e(t)}finally{n.f()}}}}]),r}(M);function $t(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}$t.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},$t.prototype.reset=function(){this.attempts=0},$t.prototype.setMin=function(t){this.ms=t},$t.prototype.setMax=function(t){this.max=t},$t.prototype.setJitter=function(t){this.jitter=t};var Vt=function(t){s(o,t);var r=p(o);function o(t,i){var s,a;n(this,o),(s=r.call(this)).nsps={},s.subs=[],t&&"object"===e(t)&&(i=t,t=void 0),(i=i||{}).path=i.path||"/socket.io",s.opts=i,V(l(s),i),s.reconnection(!1!==i.reconnection),s.reconnectionAttempts(i.reconnectionAttempts||1/0),s.reconnectionDelay(i.reconnectionDelay||1e3),s.reconnectionDelayMax(i.reconnectionDelayMax||5e3),s.randomizationFactor(null!==(a=i.randomizationFactor)&&void 0!==a?a:.5),s.backoff=new $t({min:s.reconnectionDelay(),max:s.reconnectionDelayMax(),jitter:s.randomizationFactor()}),s.timeout(null==i.timeout?2e4:i.timeout),s._readyState="closed",s.uri=t;var u=i.parser||Mt;return s.encoder=new u.Encoder,s.decoder=new u.Decoder,s._autoConnect=!1!==i.autoConnect,s._autoConnect&&s.open(),s}return i(o,[{key:"reconnection",value:function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}},{key:"reconnectionAttempts",value:function(t){return void 0===t?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}},{key:"reconnectionDelay",value:function(t){var e;return void 0===t?this._reconnectionDelay:(this._reconnectionDelay=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}},{key:"randomizationFactor",value:function(t){var e;return void 0===t?this._randomizationFactor:(this._randomizationFactor=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}},{key:"reconnectionDelayMax",value:function(t){var e;return void 0===t?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}},{key:"timeout",value:function(t){return arguments.length?(this._timeout=t,this):this._timeout}},{key:"maybeReconnectOnOpen",value:function(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}},{key:"open",value:function(t){var e=this;if(~this._readyState.indexOf("open"))return this;this.engine=new mt(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var i=It(n,"open",(function(){r.onopen(),t&&t()})),o=function(n){e.cleanup(),e._readyState="closed",e.emitReserved("error",n),t?t(n):e.maybeReconnectOnOpen()},s=It(n,"error",o);if(!1!==this._timeout){var a=this._timeout,u=this.setTimeoutFn((function(){i(),o(new Error("timeout")),n.close()}),a);this.opts.autoUnref&&u.unref(),this.subs.push((function(){e.clearTimeoutFn(u)}))}return this.subs.push(i),this.subs.push(s),this}},{key:"connect",value:function(t){return this.open(t)}},{key:"onopen",value:function(){this.cleanup(),this._readyState="open",this.emitReserved("open");var t=this.engine;this.subs.push(It(t,"ping",this.onping.bind(this)),It(t,"data",this.ondata.bind(this)),It(t,"error",this.onerror.bind(this)),It(t,"close",this.onclose.bind(this)),It(this.decoder,"decoded",this.ondecoded.bind(this)))}},{key:"onping",value:function(){this.emitReserved("ping")}},{key:"ondata",value:function(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}},{key:"ondecoded",value:function(t){var e=this;ct((function(){e.emitReserved("packet",t)}),this.setTimeoutFn)}},{key:"onerror",value:function(t){this.emitReserved("error",t)}},{key:"socket",value:function(t,e){var n=this.nsps[t];return n?this._autoConnect&&!n.active&&n.connect():(n=new Ht(this,t,e),this.nsps[t]=n),n}},{key:"_destroy",value:function(t){for(var e=0,n=Object.keys(this.nsps);e<n.length;e++){var r=n[e];if(this.nsps[r].active)return}this._close()}},{key:"_packet",value:function(t){for(var e=this.encoder.encode(t),n=0;n<e.length;n++)this.engine.write(e[n],t.options)}},{key:"cleanup",value:function(){this.subs.forEach((function(t){return t()})),this.subs.length=0,this.decoder.destroy()}},{key:"_close",value:function(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}},{key:"disconnect",value:function(){return this._close()}},{key:"onclose",value:function(t,e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,e),this._reconnection&&!this.skipReconnect&&this.reconnect()}},{key:"reconnect",value:function(){var t=this;if(this._reconnecting||this.skipReconnect)return this;var e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{var n=this.backoff.duration();this._reconnecting=!0;var r=this.setTimeoutFn((function(){e.skipReconnect||(t.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((function(n){n?(e._reconnecting=!1,e.reconnect(),t.emitReserved("reconnect_error",n)):e.onreconnect()})))}),n);this.opts.autoUnref&&r.unref(),this.subs.push((function(){t.clearTimeoutFn(r)}))}}},{key:"onreconnect",value:function(){var t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}]),o}(M),Wt={};function zt(t,n){"object"===e(t)&&(n=t,t=void 0);var r,i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0,r=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),r=gt(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var i=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(n&&n.port===r.port?"":":"+r.port),r}(t,(n=n||{}).path||"/socket.io"),o=i.source,s=i.id,a=i.path,u=Wt[s]&&a in Wt[s].nsps;return n.forceNew||n["force new connection"]||!1===n.multiplex||u?r=new Vt(o,n):(Wt[s]||(Wt[s]=new Vt(o,n)),r=Wt[s]),i.query&&!n.query&&(n.query=i.queryKey),r.socket(i.path,n)}return o(zt,{Manager:Vt,Socket:Ht,io:zt,connect:zt}),zt}));
7
+ //# sourceMappingURL=socket.io.msgpack.min.js.map
ndcc/lib/client-dist/socket.io.msgpack.min.js.map ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/deploy ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ #
4
+ # deploy(1) - Minimalistic shell script to deploy Git repositories.
5
+ # Released under the MIT License.
6
+ #
7
+ # https://github.com/visionmedia/deploy
8
+ #
9
+
10
+ VERSION="0.6.0"
11
+ CONFIG=./deploy.conf
12
+ LOG=/tmp/pm2-deploy-${USER:-default}.log
13
+ FORCE=0
14
+ REF=
15
+ ENV=
16
+
17
+ #
18
+ # Read PIPED JSON
19
+ #
20
+ read conf
21
+
22
+ #
23
+ # Output usage information.
24
+ #
25
+
26
+ usage() {
27
+ cat <<-EOF
28
+
29
+ Usage: deploy [options] <env> [command]
30
+
31
+ Options:
32
+
33
+ -C, --chdir <path> change the working directory to <path>
34
+ -c, --config <path> set config path. defaults to ./deploy.conf
35
+ -V, --version output program version
36
+ -h, --help output help information
37
+ -f, --force skip local change checking
38
+
39
+ Commands:
40
+
41
+ setup run remote setup commands
42
+ revert [n] revert to [n]th last deployment or 1
43
+ config [key] output config file or [key]
44
+ curr[ent] output current release commit
45
+ prev[ious] output previous release commit
46
+ exec|run <cmd> execute the given <cmd>
47
+ list list previous deploy commits
48
+ ref [ref] deploy [ref]
49
+
50
+ EOF
51
+ }
52
+
53
+ #
54
+ # Abort with <msg>
55
+ #
56
+
57
+ abort() {
58
+ echo
59
+ echo " $@" 1>&2
60
+ echo
61
+ exit 1
62
+ }
63
+
64
+ #
65
+ # Log <msg>.
66
+ #
67
+
68
+ log() {
69
+ echo " ○ $@"
70
+ }
71
+
72
+ #
73
+ # Get config value by <key>.
74
+ #
75
+
76
+ config_get() {
77
+ local key=$1
78
+ echo $(expr "$conf" : '.*"'$key'":"\([^"]*\)"')
79
+ }
80
+
81
+ #
82
+ # Output version.
83
+ #
84
+
85
+ version() {
86
+ echo $VERSION
87
+ }
88
+
89
+ #
90
+ # Return the ssh command to run.
91
+ #
92
+
93
+ ssh_command() {
94
+ local user="`config_get user`"
95
+ if test -n "$user"; then
96
+ local url="$user@`config_get host`"
97
+ else
98
+ local url="`config_get host`"
99
+ fi
100
+ local unexpanded_key="`config_get key`"
101
+ local key="${unexpanded_key/#\~/$HOME}"
102
+ local forward_agent="`config_get forward-agent`"
103
+ local port="`config_get port`"
104
+ local needs_tty="`config_get needs_tty`"
105
+ local ssh_options="`config_get ssh_options`"
106
+
107
+ test -n "$forward_agent" && local agent="-A"
108
+ test -n "$key" && local identity="-i $key"
109
+ test -n "$port" && local port="-p $port"
110
+ test -n "$needs_tty" && local tty="-t"
111
+ test -n "ssh_options" && local ssh_opts="$ssh_options"
112
+ echo "ssh $ssh_opts $tty $agent $port $identity $url"
113
+ }
114
+
115
+ #
116
+ # Run the given remote <cmd>.
117
+ #
118
+
119
+ runRemote() {
120
+ local shell="`ssh_command`"
121
+ echo $shell "\"$@\"" >> $LOG
122
+ $shell $@
123
+ }
124
+
125
+ #
126
+ # Run the given local <cmd>.
127
+ #
128
+
129
+ runLocal() {
130
+ echo "\"$@\"" >> $LOG
131
+ /usr/bin/env bash -c "$*"
132
+ }
133
+
134
+ #
135
+ # Run the given <cmd> either locally or remotely
136
+ #
137
+
138
+ run() {
139
+ local host="`config_get host`"
140
+ if [[ $host == localhost ]]
141
+ then
142
+ runLocal $@
143
+ else
144
+ runRemote $@
145
+ fi
146
+ }
147
+
148
+ #
149
+ # Output config or [key].
150
+ #
151
+
152
+ config() {
153
+ echo $(expr "$conf" : '.*"$key":"\([^"]*\)"')
154
+ }
155
+
156
+ #
157
+ # Execute hook <name> relative to the path configured.
158
+ #
159
+
160
+ hook() {
161
+ test -n "$1" || abort hook name required
162
+ local hook=$1
163
+ local path=`config_get path`
164
+ local cmd=`config_get $hook`
165
+ if test -n "$cmd"; then
166
+ log "executing $hook \`$cmd\`"
167
+ run "cd $path/current; \
168
+ SHARED=\"$path/shared\" \
169
+ $cmd 2>&1 | tee -a $LOG; \
170
+ exit \${PIPESTATUS[0]}"
171
+ test $? -eq 0
172
+ else
173
+ log hook $hook
174
+ fi
175
+ }
176
+
177
+ #
178
+ # Pre Setup hook runs on the host before the actual setup runs
179
+ # multiple commands or a script
180
+ #
181
+
182
+ hook_pre_setup() {
183
+ local cmd=`config_get pre-setup`
184
+ if test -n "$cmd"; then
185
+ local is_script=($cmd)
186
+ if [ -f "${is_script[0]}" ]; then
187
+ log "executing pre-setup script \`$cmd\`"
188
+ local shell="`ssh_command`"
189
+ runLocal "$shell 'bash -s' -- < $cmd"
190
+ else
191
+ log "executing pre-setup \`$cmd\`"
192
+ run "$cmd"
193
+ fi
194
+ test $? -eq 0
195
+ else
196
+ log hook pre-setup
197
+ fi
198
+ }
199
+
200
+ #
201
+ # Run setup.
202
+ #
203
+
204
+ setup() {
205
+ local path=`config_get path`
206
+ local repo=`config_get repo`
207
+ local ref=`config_get ref`
208
+ local fetch=`config_get fetch`
209
+ local branch=${ref#*/}
210
+
211
+ hook_pre_setup || abort pre-setup hook failed
212
+ run "mkdir -p $path/{shared/{logs,pids},source}"
213
+ test $? -eq 0 || abort setup paths failed
214
+ log running setup
215
+ log cloning $repo
216
+ if test "$fetch" != "fast"; then
217
+ log "full fetch"
218
+ run "git clone --branch $branch $repo $path/source"
219
+ else
220
+ log "fast fetch"
221
+ run "git clone --depth=5 --branch $branch $repo $path/source"
222
+ fi
223
+ test $? -eq 0 || abort failed to clone
224
+ run "ln -sfn $path/source $path/current"
225
+ test $? -eq 0 || abort symlink failed
226
+ hook post-setup || abort post-setup hook failed
227
+ log setup complete
228
+ }
229
+
230
+ #
231
+ # Deploy [ref].
232
+ #
233
+
234
+ deploy() {
235
+ local ref=$1
236
+ local branch=$2
237
+
238
+ if test -z "$branch"; then
239
+ branch=${ref#*/}
240
+ fi
241
+ local path=`config_get path`
242
+ local fetch=`config_get fetch`
243
+
244
+ log "deploying ${ref}"
245
+
246
+ # 1- Execute local commands
247
+ log executing pre-deploy-local
248
+ local pdl=`config_get pre-deploy-local`
249
+ runLocal $pdl || abort pre-deploy-local hook failed
250
+
251
+ # 2- Execute pre deploy commands on remote server
252
+ hook pre-deploy || abort pre-deploy hook failed
253
+
254
+ # 3- Fetch updates
255
+ log fetching updates
256
+ if test "$fetch" != "fast"; then
257
+ log "full fetch"
258
+ run "cd $path/source && git fetch --all --tags"
259
+ else
260
+ log "fast fetch"
261
+ run "cd $path/source && git fetch --depth=5 --all --tags"
262
+ fi
263
+ test $? -eq 0 || abort fetch failed
264
+
265
+ # 4- If no reference retrieve shorthand name for the remote repo
266
+ if test -z "$ref"; then
267
+ log fetching latest tag
268
+ ref=`run "cd $path/source && git for-each-ref \
269
+ --sort=-*authordate \
270
+ --format='%(refname)' \
271
+ --count=1 | cut -d '/' -f 3"`
272
+ test $? -eq 0 || abort failed to determine latest tag
273
+ fi
274
+
275
+ # 5- Reset to ref
276
+ log resetting HEAD to $ref
277
+ run "cd $path/source && git reset --hard $ref"
278
+ test $? -eq 0 || abort git reset failed
279
+
280
+ # 6- Link current
281
+ run "ln -sfn $path/source $path/current"
282
+ test $? -eq 0 || abort symlink failed
283
+
284
+ # deploy log
285
+ run "cd $path/source && \
286
+ echo \`git rev-parse HEAD\` \
287
+ >> $path/.deploys"
288
+ test $? -eq 0 || abort deploy log append failed
289
+
290
+ hook post-deploy || abort post-deploy hook failed
291
+
292
+ # done
293
+ log successfully deployed $ref
294
+ }
295
+
296
+ #
297
+ # Get current commit.
298
+ #
299
+
300
+ current_commit() {
301
+ local path=`config_get path`
302
+ run "cd $path/source && \
303
+ git rev-parse --short HEAD"
304
+ }
305
+
306
+ #
307
+ # Get <n>th deploy commit.
308
+ #
309
+
310
+ nth_deploy_commit() {
311
+ local n=$1
312
+ local path=`config_get path`
313
+ run "cat $path/.deploys | tail -n $n | head -n 1 | cut -d ' ' -f 1"
314
+ }
315
+
316
+ #
317
+ # List deploys.
318
+ #
319
+
320
+ list_deploys() {
321
+ local path=`config_get path`
322
+ run "tac $path/.deploys | awk '{printf \"%d\t%s\n\", NR-1, \$0}'"
323
+ }
324
+
325
+ #
326
+ # Revert to the <n>th last deployment.
327
+ #
328
+
329
+ revert_to() {
330
+ local n=$1
331
+ log "reverting $n deploy(s)"
332
+ local commit=`nth_deploy_commit $((n + 1))`
333
+ deploy "$commit"
334
+ }
335
+
336
+ #
337
+ # Ensure all changes are committed and pushed before deploying.
338
+ #
339
+
340
+ check_for_local_changes() {
341
+ local path=`config_get path`
342
+
343
+ if [ $FORCE -eq 1 ]
344
+ then
345
+ return
346
+ fi
347
+ git --no-pager diff --exit-code --quiet || abort "commit or stash your changes before deploying"
348
+ git --no-pager diff --exit-code --quiet --cached || abort "commit your staged changes before deploying"
349
+ [ -z "`git rev-list @{upstream}.. -n 1`" ] || abort "push your changes before deploying"
350
+ }
351
+
352
+ # parse argv
353
+ while test $# -ne 0; do
354
+ arg=$1; shift
355
+ case $arg in
356
+ -h|--help) usage; exit ;;
357
+ -V|--version) version; exit ;;
358
+ -C|--chdir) log cd $1; cd $1; shift ;;
359
+ -F|--force) FORCE=1 ;;
360
+ run|exec) run "cd `config_get path`/current && $@"; exit ;;
361
+ console) console; exit ;;
362
+ curr|current) current_commit; exit ;;
363
+ prev|previous) nth_deploy_commit 2; exit ;;
364
+ revert) revert_to ${1-1}; exit ;;
365
+ setup) setup $@; exit ;;
366
+ list) list_deploys; exit ;;
367
+ config) config $@; exit ;;
368
+ ref) REF=$1; BRANCH=$2 ;;
369
+ esac
370
+ done
371
+
372
+ check_for_local_changes
373
+
374
+ echo
375
+ # deploy
376
+ deploy "${REF:-`config_get ref`}" "${BRANCH}"
ndcc/lib/events.js ADDED
@@ -0,0 +1,977 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Joyent, Inc. and other Node contributors.
2
+ //
3
+ // Permission is hereby granted, free of charge, to any person obtaining a
4
+ // copy of this software and associated documentation files (the
5
+ // "Software"), to deal in the Software without restriction, including
6
+ // without limitation the rights to use, copy, modify, merge, publish,
7
+ // distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ // persons to whom the Software is furnished to do so, subject to the
9
+ // following conditions:
10
+ //
11
+ // The above copyright notice and this permission notice shall be included
12
+ // in all copies or substantial portions of the Software.
13
+ //
14
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
+ // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
+ // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
+ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
+ // USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ // Modified by the vm2 team to make this a standalone module to be loaded into the sandbox.
23
+
24
+ 'use strict';
25
+
26
+ const host = fromhost;
27
+
28
+ const {
29
+ Boolean,
30
+ Error,
31
+ String,
32
+ Symbol
33
+ } = globalThis;
34
+
35
+ const ReflectApply = Reflect.apply;
36
+ const ReflectOwnKeys = Reflect.ownKeys;
37
+
38
+ const ErrorCaptureStackTrace = Error.captureStackTrace;
39
+
40
+ const NumberIsNaN = Number.isNaN;
41
+
42
+ const ObjectCreate = Object.create;
43
+ const ObjectDefineProperty = Object.defineProperty;
44
+ const ObjectDefineProperties = Object.defineProperties;
45
+ const ObjectGetPrototypeOf = Object.getPrototypeOf;
46
+
47
+ const SymbolFor = Symbol.for;
48
+
49
+ function uncurryThis(func) {
50
+ return (thiz, ...args) => ReflectApply(func, thiz, args);
51
+ }
52
+
53
+ const ArrayPrototypeIndexOf = uncurryThis(Array.prototype.indexOf);
54
+ const ArrayPrototypeJoin = uncurryThis(Array.prototype.join);
55
+ const ArrayPrototypeSlice = uncurryThis(Array.prototype.slice);
56
+ const ArrayPrototypeSplice = uncurryThis(Array.prototype.splice);
57
+ const ArrayPrototypeUnshift = uncurryThis(Array.prototype.unshift);
58
+
59
+ const kRejection = SymbolFor('nodejs.rejection');
60
+
61
+ function inspect(obj) {
62
+ return typeof obj === 'symbol' ? obj.toString() : `${obj}`;
63
+ }
64
+
65
+ function spliceOne(list, index) {
66
+ for (; index + 1 < list.length; index++)
67
+ list[index] = list[index + 1];
68
+ list.pop();
69
+ }
70
+
71
+ function assert(what, message) {
72
+ if (!what) throw new Error(message);
73
+ }
74
+
75
+ function E(key, msg, Base) {
76
+ return function NodeError(...args) {
77
+ const error = new Base();
78
+ const message = ReflectApply(msg, error, args);
79
+ ObjectDefineProperties(error, {
80
+ message: {
81
+ value: message,
82
+ enumerable: false,
83
+ writable: true,
84
+ configurable: true,
85
+ },
86
+ toString: {
87
+ value() {
88
+ return `${this.name} [${key}]: ${this.message}`;
89
+ },
90
+ enumerable: false,
91
+ writable: true,
92
+ configurable: true,
93
+ },
94
+ });
95
+ error.code = key;
96
+ return error;
97
+ };
98
+ }
99
+
100
+
101
+ const ERR_INVALID_ARG_TYPE = E('ERR_INVALID_ARG_TYPE',
102
+ (name, expected, actual) => {
103
+ assert(typeof name === 'string', "'name' must be a string");
104
+ if (!ArrayIsArray(expected)) {
105
+ expected = [expected];
106
+ }
107
+
108
+ let msg = 'The ';
109
+ if (StringPrototypeEndsWith(name, ' argument')) {
110
+ // For cases like 'first argument'
111
+ msg += `${name} `;
112
+ } else {
113
+ const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument';
114
+ msg += `"${name}" ${type} `;
115
+ }
116
+ msg += 'must be ';
117
+
118
+ const types = [];
119
+ const instances = [];
120
+ const other = [];
121
+
122
+ for (const value of expected) {
123
+ assert(typeof value === 'string',
124
+ 'All expected entries have to be of type string');
125
+ if (ArrayPrototypeIncludes(kTypes, value)) {
126
+ ArrayPrototypePush(types, StringPrototypeToLowerCase(value));
127
+ } else if (RegExpPrototypeTest(classRegExp, value)) {
128
+ ArrayPrototypePush(instances, value);
129
+ } else {
130
+ assert(value !== 'object',
131
+ 'The value "object" should be written as "Object"');
132
+ ArrayPrototypePush(other, value);
133
+ }
134
+ }
135
+
136
+ // Special handle `object` in case other instances are allowed to outline
137
+ // the differences between each other.
138
+ if (instances.length > 0) {
139
+ const pos = ArrayPrototypeIndexOf(types, 'object');
140
+ if (pos !== -1) {
141
+ ArrayPrototypeSplice(types, pos, 1);
142
+ ArrayPrototypePush(instances, 'Object');
143
+ }
144
+ }
145
+
146
+ if (types.length > 0) {
147
+ if (types.length > 2) {
148
+ const last = ArrayPrototypePop(types);
149
+ msg += `one of type ${ArrayPrototypeJoin(types, ', ')}, or ${last}`;
150
+ } else if (types.length === 2) {
151
+ msg += `one of type ${types[0]} or ${types[1]}`;
152
+ } else {
153
+ msg += `of type ${types[0]}`;
154
+ }
155
+ if (instances.length > 0 || other.length > 0)
156
+ msg += ' or ';
157
+ }
158
+
159
+ if (instances.length > 0) {
160
+ if (instances.length > 2) {
161
+ const last = ArrayPrototypePop(instances);
162
+ msg +=
163
+ `an instance of ${ArrayPrototypeJoin(instances, ', ')}, or ${last}`;
164
+ } else {
165
+ msg += `an instance of ${instances[0]}`;
166
+ if (instances.length === 2) {
167
+ msg += ` or ${instances[1]}`;
168
+ }
169
+ }
170
+ if (other.length > 0)
171
+ msg += ' or ';
172
+ }
173
+
174
+ if (other.length > 0) {
175
+ if (other.length > 2) {
176
+ const last = ArrayPrototypePop(other);
177
+ msg += `one of ${ArrayPrototypeJoin(other, ', ')}, or ${last}`;
178
+ } else if (other.length === 2) {
179
+ msg += `one of ${other[0]} or ${other[1]}`;
180
+ } else {
181
+ if (StringPrototypeToLowerCase(other[0]) !== other[0])
182
+ msg += 'an ';
183
+ msg += `${other[0]}`;
184
+ }
185
+ }
186
+
187
+ if (actual == null) {
188
+ msg += `. Received ${actual}`;
189
+ } else if (typeof actual === 'function' && actual.name) {
190
+ msg += `. Received function ${actual.name}`;
191
+ } else if (typeof actual === 'object') {
192
+ if (actual.constructor && actual.constructor.name) {
193
+ msg += `. Received an instance of ${actual.constructor.name}`;
194
+ } else {
195
+ const inspected = inspect(actual, { depth: -1 });
196
+ msg += `. Received ${inspected}`;
197
+ }
198
+ } else {
199
+ let inspected = inspect(actual, { colors: false });
200
+ if (inspected.length > 25)
201
+ inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`;
202
+ msg += `. Received type ${typeof actual} (${inspected})`;
203
+ }
204
+ return msg;
205
+ }, TypeError);
206
+
207
+ const ERR_INVALID_THIS = E('ERR_INVALID_THIS', s => `Value of "this" must be of type ${s}`, TypeError);
208
+
209
+ const ERR_OUT_OF_RANGE = E('ERR_OUT_OF_RANGE',
210
+ (str, range, input, replaceDefaultBoolean = false) => {
211
+ assert(range, 'Missing "range" argument');
212
+ let msg = replaceDefaultBoolean ? str :
213
+ `The value of "${str}" is out of range.`;
214
+ const received = inspect(input);
215
+ msg += ` It must be ${range}. Received ${received}`;
216
+ return msg;
217
+ }, RangeError);
218
+
219
+ const ERR_UNHANDLED_ERROR = E('ERR_UNHANDLED_ERROR',
220
+ err => {
221
+ const msg = 'Unhandled error.';
222
+ if (err === undefined) return msg;
223
+ return `${msg} (${err})`;
224
+ }, Error);
225
+
226
+ function validateBoolean(value, name) {
227
+ if (typeof value !== 'boolean')
228
+ throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value);
229
+ }
230
+
231
+ function validateFunction(value, name) {
232
+ if (typeof value !== 'function')
233
+ throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
234
+ }
235
+
236
+ function validateString(value, name) {
237
+ if (typeof value !== 'string')
238
+ throw new ERR_INVALID_ARG_TYPE(name, 'string', value);
239
+ }
240
+
241
+ function nc(cond, e) {
242
+ return cond === undefined || cond === null ? e : cond;
243
+ }
244
+
245
+ function oc(base, key) {
246
+ return base === undefined || base === null ? undefined : base[key];
247
+ }
248
+
249
+ const kCapture = Symbol('kCapture');
250
+ const kErrorMonitor = host.kErrorMonitor || Symbol('events.errorMonitor');
251
+ const kMaxEventTargetListeners = Symbol('events.maxEventTargetListeners');
252
+ const kMaxEventTargetListenersWarned =
253
+ Symbol('events.maxEventTargetListenersWarned');
254
+
255
+ const kIsEventTarget = SymbolFor('nodejs.event_target');
256
+
257
+ function isEventTarget(obj) {
258
+ return oc(oc(obj, 'constructor'), kIsEventTarget);
259
+ }
260
+
261
+ /**
262
+ * Creates a new `EventEmitter` instance.
263
+ * @param {{ captureRejections?: boolean; }} [opts]
264
+ * @constructs {EventEmitter}
265
+ */
266
+ function EventEmitter(opts) {
267
+ EventEmitter.init.call(this, opts);
268
+ }
269
+ module.exports = EventEmitter;
270
+ if (host.once) module.exports.once = host.once;
271
+ if (host.on) module.exports.on = host.on;
272
+ if (host.getEventListeners) module.exports.getEventListeners = host.getEventListeners;
273
+ // Backwards-compat with node 0.10.x
274
+ EventEmitter.EventEmitter = EventEmitter;
275
+
276
+ EventEmitter.usingDomains = false;
277
+
278
+ EventEmitter.captureRejectionSymbol = kRejection;
279
+ ObjectDefineProperty(EventEmitter, 'captureRejections', {
280
+ get() {
281
+ return EventEmitter.prototype[kCapture];
282
+ },
283
+ set(value) {
284
+ validateBoolean(value, 'EventEmitter.captureRejections');
285
+
286
+ EventEmitter.prototype[kCapture] = value;
287
+ },
288
+ enumerable: true
289
+ });
290
+
291
+ if (host.EventEmitterReferencingAsyncResource) {
292
+ const kAsyncResource = Symbol('kAsyncResource');
293
+ const EventEmitterReferencingAsyncResource = host.EventEmitterReferencingAsyncResource;
294
+
295
+ class EventEmitterAsyncResource extends EventEmitter {
296
+ /**
297
+ * @param {{
298
+ * name?: string,
299
+ * triggerAsyncId?: number,
300
+ * requireManualDestroy?: boolean,
301
+ * }} [options]
302
+ */
303
+ constructor(options = undefined) {
304
+ let name;
305
+ if (typeof options === 'string') {
306
+ name = options;
307
+ options = undefined;
308
+ } else {
309
+ if (new.target === EventEmitterAsyncResource) {
310
+ validateString(oc(options, 'name'), 'options.name');
311
+ }
312
+ name = oc(options, 'name') || new.target.name;
313
+ }
314
+ super(options);
315
+
316
+ this[kAsyncResource] =
317
+ new EventEmitterReferencingAsyncResource(this, name, options);
318
+ }
319
+
320
+ /**
321
+ * @param {symbol,string} event
322
+ * @param {...any} args
323
+ * @returns {boolean}
324
+ */
325
+ emit(event, ...args) {
326
+ if (this[kAsyncResource] === undefined)
327
+ throw new ERR_INVALID_THIS('EventEmitterAsyncResource');
328
+ const { asyncResource } = this;
329
+ ArrayPrototypeUnshift(args, super.emit, this, event);
330
+ return ReflectApply(asyncResource.runInAsyncScope, asyncResource,
331
+ args);
332
+ }
333
+
334
+ /**
335
+ * @returns {void}
336
+ */
337
+ emitDestroy() {
338
+ if (this[kAsyncResource] === undefined)
339
+ throw new ERR_INVALID_THIS('EventEmitterAsyncResource');
340
+ this.asyncResource.emitDestroy();
341
+ }
342
+
343
+ /**
344
+ * @type {number}
345
+ */
346
+ get asyncId() {
347
+ if (this[kAsyncResource] === undefined)
348
+ throw new ERR_INVALID_THIS('EventEmitterAsyncResource');
349
+ return this.asyncResource.asyncId();
350
+ }
351
+
352
+ /**
353
+ * @type {number}
354
+ */
355
+ get triggerAsyncId() {
356
+ if (this[kAsyncResource] === undefined)
357
+ throw new ERR_INVALID_THIS('EventEmitterAsyncResource');
358
+ return this.asyncResource.triggerAsyncId();
359
+ }
360
+
361
+ /**
362
+ * @type {EventEmitterReferencingAsyncResource}
363
+ */
364
+ get asyncResource() {
365
+ if (this[kAsyncResource] === undefined)
366
+ throw new ERR_INVALID_THIS('EventEmitterAsyncResource');
367
+ return this[kAsyncResource];
368
+ }
369
+ }
370
+ EventEmitter.EventEmitterAsyncResource = EventEmitterAsyncResource;
371
+ }
372
+
373
+ EventEmitter.errorMonitor = kErrorMonitor;
374
+
375
+ // The default for captureRejections is false
376
+ ObjectDefineProperty(EventEmitter.prototype, kCapture, {
377
+ value: false,
378
+ writable: true,
379
+ enumerable: false
380
+ });
381
+
382
+ EventEmitter.prototype._events = undefined;
383
+ EventEmitter.prototype._eventsCount = 0;
384
+ EventEmitter.prototype._maxListeners = undefined;
385
+
386
+ // By default EventEmitters will print a warning if more than 10 listeners are
387
+ // added to it. This is a useful default which helps finding memory leaks.
388
+ let defaultMaxListeners = 10;
389
+
390
+ function checkListener(listener) {
391
+ validateFunction(listener, 'listener');
392
+ }
393
+
394
+ ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', {
395
+ enumerable: true,
396
+ get: function() {
397
+ return defaultMaxListeners;
398
+ },
399
+ set: function(arg) {
400
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
401
+ throw new ERR_OUT_OF_RANGE('defaultMaxListeners',
402
+ 'a non-negative number',
403
+ arg);
404
+ }
405
+ defaultMaxListeners = arg;
406
+ }
407
+ });
408
+
409
+ ObjectDefineProperties(EventEmitter, {
410
+ kMaxEventTargetListeners: {
411
+ value: kMaxEventTargetListeners,
412
+ enumerable: false,
413
+ configurable: false,
414
+ writable: false,
415
+ },
416
+ kMaxEventTargetListenersWarned: {
417
+ value: kMaxEventTargetListenersWarned,
418
+ enumerable: false,
419
+ configurable: false,
420
+ writable: false,
421
+ }
422
+ });
423
+
424
+ /**
425
+ * Sets the max listeners.
426
+ * @param {number} n
427
+ * @param {EventTarget[] | EventEmitter[]} [eventTargets]
428
+ * @returns {void}
429
+ */
430
+ EventEmitter.setMaxListeners =
431
+ function(n = defaultMaxListeners, ...eventTargets) {
432
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n))
433
+ throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n);
434
+ if (eventTargets.length === 0) {
435
+ defaultMaxListeners = n;
436
+ } else {
437
+ for (let i = 0; i < eventTargets.length; i++) {
438
+ const target = eventTargets[i];
439
+ if (isEventTarget(target)) {
440
+ target[kMaxEventTargetListeners] = n;
441
+ target[kMaxEventTargetListenersWarned] = false;
442
+ } else if (typeof target.setMaxListeners === 'function') {
443
+ target.setMaxListeners(n);
444
+ } else {
445
+ throw new ERR_INVALID_ARG_TYPE(
446
+ 'eventTargets',
447
+ ['EventEmitter', 'EventTarget'],
448
+ target);
449
+ }
450
+ }
451
+ }
452
+ };
453
+
454
+ // If you're updating this function definition, please also update any
455
+ // re-definitions, such as the one in the Domain module (lib/domain.js).
456
+ EventEmitter.init = function(opts) {
457
+
458
+ if (this._events === undefined ||
459
+ this._events === ObjectGetPrototypeOf(this)._events) {
460
+ this._events = ObjectCreate(null);
461
+ this._eventsCount = 0;
462
+ }
463
+
464
+ this._maxListeners = this._maxListeners || undefined;
465
+
466
+
467
+ if (oc(opts, 'captureRejections')) {
468
+ validateBoolean(opts.captureRejections, 'options.captureRejections');
469
+ this[kCapture] = Boolean(opts.captureRejections);
470
+ } else {
471
+ // Assigning the kCapture property directly saves an expensive
472
+ // prototype lookup in a very sensitive hot path.
473
+ this[kCapture] = EventEmitter.prototype[kCapture];
474
+ }
475
+ };
476
+
477
+ function addCatch(that, promise, type, args) {
478
+ if (!that[kCapture]) {
479
+ return;
480
+ }
481
+
482
+ // Handle Promises/A+ spec, then could be a getter
483
+ // that throws on second use.
484
+ try {
485
+ const then = promise.then;
486
+
487
+ if (typeof then === 'function') {
488
+ then.call(promise, undefined, function(err) {
489
+ // The callback is called with nextTick to avoid a follow-up
490
+ // rejection from this promise.
491
+ process.nextTick(emitUnhandledRejectionOrErr, that, err, type, args);
492
+ });
493
+ }
494
+ } catch (err) {
495
+ that.emit('error', err);
496
+ }
497
+ }
498
+
499
+ function emitUnhandledRejectionOrErr(ee, err, type, args) {
500
+ if (typeof ee[kRejection] === 'function') {
501
+ ee[kRejection](err, type, ...args);
502
+ } else {
503
+ // We have to disable the capture rejections mechanism, otherwise
504
+ // we might end up in an infinite loop.
505
+ const prev = ee[kCapture];
506
+
507
+ // If the error handler throws, it is not catchable and it
508
+ // will end up in 'uncaughtException'. We restore the previous
509
+ // value of kCapture in case the uncaughtException is present
510
+ // and the exception is handled.
511
+ try {
512
+ ee[kCapture] = false;
513
+ ee.emit('error', err);
514
+ } finally {
515
+ ee[kCapture] = prev;
516
+ }
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Increases the max listeners of the event emitter.
522
+ * @param {number} n
523
+ * @returns {EventEmitter}
524
+ */
525
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
526
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
527
+ throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n);
528
+ }
529
+ this._maxListeners = n;
530
+ return this;
531
+ };
532
+
533
+ function _getMaxListeners(that) {
534
+ if (that._maxListeners === undefined)
535
+ return EventEmitter.defaultMaxListeners;
536
+ return that._maxListeners;
537
+ }
538
+
539
+ /**
540
+ * Returns the current max listener value for the event emitter.
541
+ * @returns {number}
542
+ */
543
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
544
+ return _getMaxListeners(this);
545
+ };
546
+
547
+ /**
548
+ * Synchronously calls each of the listeners registered
549
+ * for the event.
550
+ * @param {string | symbol} type
551
+ * @param {...any} [args]
552
+ * @returns {boolean}
553
+ */
554
+ EventEmitter.prototype.emit = function emit(type, ...args) {
555
+ let doError = (type === 'error');
556
+
557
+ const events = this._events;
558
+ if (events !== undefined) {
559
+ if (doError && events[kErrorMonitor] !== undefined)
560
+ this.emit(kErrorMonitor, ...args);
561
+ doError = (doError && events.error === undefined);
562
+ } else if (!doError)
563
+ return false;
564
+
565
+ // If there is no 'error' event listener then throw.
566
+ if (doError) {
567
+ let er;
568
+ if (args.length > 0)
569
+ er = args[0];
570
+ if (er instanceof Error) {
571
+ try {
572
+ const capture = {};
573
+ ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit);
574
+ } catch (e) {}
575
+
576
+ // Note: The comments on the `throw` lines are intentional, they show
577
+ // up in Node's output if this results in an unhandled exception.
578
+ throw er; // Unhandled 'error' event
579
+ }
580
+
581
+ let stringifiedEr;
582
+ try {
583
+ stringifiedEr = inspect(er);
584
+ } catch (e) {
585
+ stringifiedEr = er;
586
+ }
587
+
588
+ // At least give some kind of context to the user
589
+ const err = new ERR_UNHANDLED_ERROR(stringifiedEr);
590
+ err.context = er;
591
+ throw err; // Unhandled 'error' event
592
+ }
593
+
594
+ const handler = events[type];
595
+
596
+ if (handler === undefined)
597
+ return false;
598
+
599
+ if (typeof handler === 'function') {
600
+ const result = handler.apply(this, args);
601
+
602
+ // We check if result is undefined first because that
603
+ // is the most common case so we do not pay any perf
604
+ // penalty
605
+ if (result !== undefined && result !== null) {
606
+ addCatch(this, result, type, args);
607
+ }
608
+ } else {
609
+ const len = handler.length;
610
+ const listeners = arrayClone(handler);
611
+ for (let i = 0; i < len; ++i) {
612
+ const result = listeners[i].apply(this, args);
613
+
614
+ // We check if result is undefined first because that
615
+ // is the most common case so we do not pay any perf
616
+ // penalty.
617
+ // This code is duplicated because extracting it away
618
+ // would make it non-inlineable.
619
+ if (result !== undefined && result !== null) {
620
+ addCatch(this, result, type, args);
621
+ }
622
+ }
623
+ }
624
+
625
+ return true;
626
+ };
627
+
628
+ function _addListener(target, type, listener, prepend) {
629
+ let m;
630
+ let events;
631
+ let existing;
632
+
633
+ checkListener(listener);
634
+
635
+ events = target._events;
636
+ if (events === undefined) {
637
+ events = target._events = ObjectCreate(null);
638
+ target._eventsCount = 0;
639
+ } else {
640
+ // To avoid recursion in the case that type === "newListener"! Before
641
+ // adding it to the listeners, first emit "newListener".
642
+ if (events.newListener !== undefined) {
643
+ target.emit('newListener', type,
644
+ nc(listener.listener, listener));
645
+
646
+ // Re-assign `events` because a newListener handler could have caused the
647
+ // this._events to be assigned to a new object
648
+ events = target._events;
649
+ }
650
+ existing = events[type];
651
+ }
652
+
653
+ if (existing === undefined) {
654
+ // Optimize the case of one listener. Don't need the extra array object.
655
+ events[type] = listener;
656
+ ++target._eventsCount;
657
+ } else {
658
+ if (typeof existing === 'function') {
659
+ // Adding the second element, need to change to array.
660
+ existing = events[type] =
661
+ prepend ? [listener, existing] : [existing, listener];
662
+ // If we've already got an array, just append.
663
+ } else if (prepend) {
664
+ existing.unshift(listener);
665
+ } else {
666
+ existing.push(listener);
667
+ }
668
+
669
+ // Check for listener leak
670
+ m = _getMaxListeners(target);
671
+ if (m > 0 && existing.length > m && !existing.warned) {
672
+ existing.warned = true;
673
+ // No error code for this since it is a Warning
674
+ // eslint-disable-next-line no-restricted-syntax
675
+ const w = new Error('Possible EventEmitter memory leak detected. ' +
676
+ `${existing.length} ${String(type)} listeners ` +
677
+ `added to ${inspect(target, { depth: -1 })}. Use ` +
678
+ 'emitter.setMaxListeners() to increase limit');
679
+ w.name = 'MaxListenersExceededWarning';
680
+ w.emitter = target;
681
+ w.type = type;
682
+ w.count = existing.length;
683
+ process.emitWarning(w);
684
+ }
685
+ }
686
+
687
+ return target;
688
+ }
689
+
690
+ /**
691
+ * Adds a listener to the event emitter.
692
+ * @param {string | symbol} type
693
+ * @param {Function} listener
694
+ * @returns {EventEmitter}
695
+ */
696
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
697
+ return _addListener(this, type, listener, false);
698
+ };
699
+
700
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
701
+
702
+ /**
703
+ * Adds the `listener` function to the beginning of
704
+ * the listeners array.
705
+ * @param {string | symbol} type
706
+ * @param {Function} listener
707
+ * @returns {EventEmitter}
708
+ */
709
+ EventEmitter.prototype.prependListener =
710
+ function prependListener(type, listener) {
711
+ return _addListener(this, type, listener, true);
712
+ };
713
+
714
+ function onceWrapper() {
715
+ if (!this.fired) {
716
+ this.target.removeListener(this.type, this.wrapFn);
717
+ this.fired = true;
718
+ if (arguments.length === 0)
719
+ return this.listener.call(this.target);
720
+ return this.listener.apply(this.target, arguments);
721
+ }
722
+ }
723
+
724
+ function _onceWrap(target, type, listener) {
725
+ const state = { fired: false, wrapFn: undefined, target, type, listener };
726
+ const wrapped = onceWrapper.bind(state);
727
+ wrapped.listener = listener;
728
+ state.wrapFn = wrapped;
729
+ return wrapped;
730
+ }
731
+
732
+ /**
733
+ * Adds a one-time `listener` function to the event emitter.
734
+ * @param {string | symbol} type
735
+ * @param {Function} listener
736
+ * @returns {EventEmitter}
737
+ */
738
+ EventEmitter.prototype.once = function once(type, listener) {
739
+ checkListener(listener);
740
+
741
+ this.on(type, _onceWrap(this, type, listener));
742
+ return this;
743
+ };
744
+
745
+ /**
746
+ * Adds a one-time `listener` function to the beginning of
747
+ * the listeners array.
748
+ * @param {string | symbol} type
749
+ * @param {Function} listener
750
+ * @returns {EventEmitter}
751
+ */
752
+ EventEmitter.prototype.prependOnceListener =
753
+ function prependOnceListener(type, listener) {
754
+ checkListener(listener);
755
+
756
+ this.prependListener(type, _onceWrap(this, type, listener));
757
+ return this;
758
+ };
759
+
760
+
761
+ /**
762
+ * Removes the specified `listener` from the listeners array.
763
+ * @param {string | symbol} type
764
+ * @param {Function} listener
765
+ * @returns {EventEmitter}
766
+ */
767
+ EventEmitter.prototype.removeListener =
768
+ function removeListener(type, listener) {
769
+ checkListener(listener);
770
+
771
+ const events = this._events;
772
+ if (events === undefined)
773
+ return this;
774
+
775
+ const list = events[type];
776
+ if (list === undefined)
777
+ return this;
778
+
779
+ if (list === listener || list.listener === listener) {
780
+ if (--this._eventsCount === 0)
781
+ this._events = ObjectCreate(null);
782
+ else {
783
+ delete events[type];
784
+ if (events.removeListener)
785
+ this.emit('removeListener', type, list.listener || listener);
786
+ }
787
+ } else if (typeof list !== 'function') {
788
+ let position = -1;
789
+
790
+ for (let i = list.length - 1; i >= 0; i--) {
791
+ if (list[i] === listener || list[i].listener === listener) {
792
+ position = i;
793
+ break;
794
+ }
795
+ }
796
+
797
+ if (position < 0)
798
+ return this;
799
+
800
+ if (position === 0)
801
+ list.shift();
802
+ else {
803
+ spliceOne(list, position);
804
+ }
805
+
806
+ if (list.length === 1)
807
+ events[type] = list[0];
808
+
809
+ if (events.removeListener !== undefined)
810
+ this.emit('removeListener', type, listener);
811
+ }
812
+
813
+ return this;
814
+ };
815
+
816
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
817
+
818
+ /**
819
+ * Removes all listeners from the event emitter. (Only
820
+ * removes listeners for a specific event name if specified
821
+ * as `type`).
822
+ * @param {string | symbol} [type]
823
+ * @returns {EventEmitter}
824
+ */
825
+ EventEmitter.prototype.removeAllListeners =
826
+ function removeAllListeners(type) {
827
+ const events = this._events;
828
+ if (events === undefined)
829
+ return this;
830
+
831
+ // Not listening for removeListener, no need to emit
832
+ if (events.removeListener === undefined) {
833
+ if (arguments.length === 0) {
834
+ this._events = ObjectCreate(null);
835
+ this._eventsCount = 0;
836
+ } else if (events[type] !== undefined) {
837
+ if (--this._eventsCount === 0)
838
+ this._events = ObjectCreate(null);
839
+ else
840
+ delete events[type];
841
+ }
842
+ return this;
843
+ }
844
+
845
+ // Emit removeListener for all listeners on all events
846
+ if (arguments.length === 0) {
847
+ for (const key of ReflectOwnKeys(events)) {
848
+ if (key === 'removeListener') continue;
849
+ this.removeAllListeners(key);
850
+ }
851
+ this.removeAllListeners('removeListener');
852
+ this._events = ObjectCreate(null);
853
+ this._eventsCount = 0;
854
+ return this;
855
+ }
856
+
857
+ const listeners = events[type];
858
+
859
+ if (typeof listeners === 'function') {
860
+ this.removeListener(type, listeners);
861
+ } else if (listeners !== undefined) {
862
+ // LIFO order
863
+ for (let i = listeners.length - 1; i >= 0; i--) {
864
+ this.removeListener(type, listeners[i]);
865
+ }
866
+ }
867
+
868
+ return this;
869
+ };
870
+
871
+ function _listeners(target, type, unwrap) {
872
+ const events = target._events;
873
+
874
+ if (events === undefined)
875
+ return [];
876
+
877
+ const evlistener = events[type];
878
+ if (evlistener === undefined)
879
+ return [];
880
+
881
+ if (typeof evlistener === 'function')
882
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
883
+
884
+ return unwrap ?
885
+ unwrapListeners(evlistener) : arrayClone(evlistener);
886
+ }
887
+
888
+ /**
889
+ * Returns a copy of the array of listeners for the event name
890
+ * specified as `type`.
891
+ * @param {string | symbol} type
892
+ * @returns {Function[]}
893
+ */
894
+ EventEmitter.prototype.listeners = function listeners(type) {
895
+ return _listeners(this, type, true);
896
+ };
897
+
898
+ /**
899
+ * Returns a copy of the array of listeners and wrappers for
900
+ * the event name specified as `type`.
901
+ * @param {string | symbol} type
902
+ * @returns {Function[]}
903
+ */
904
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
905
+ return _listeners(this, type, false);
906
+ };
907
+
908
+ /**
909
+ * Returns the number of listeners listening to the event name
910
+ * specified as `type`.
911
+ * @deprecated since v3.2.0
912
+ * @param {EventEmitter} emitter
913
+ * @param {string | symbol} type
914
+ * @returns {number}
915
+ */
916
+ EventEmitter.listenerCount = function(emitter, type) {
917
+ if (typeof emitter.listenerCount === 'function') {
918
+ return emitter.listenerCount(type);
919
+ }
920
+ return emitter.listenerCount(type);
921
+ };
922
+
923
+ EventEmitter.prototype.listenerCount = listenerCount;
924
+
925
+ /**
926
+ * Returns the number of listeners listening to event name
927
+ * specified as `type`.
928
+ * @param {string | symbol} type
929
+ * @returns {number}
930
+ */
931
+ function listenerCount(type) {
932
+ const events = this._events;
933
+
934
+ if (events !== undefined) {
935
+ const evlistener = events[type];
936
+
937
+ if (typeof evlistener === 'function') {
938
+ return 1;
939
+ } else if (evlistener !== undefined) {
940
+ return evlistener.length;
941
+ }
942
+ }
943
+
944
+ return 0;
945
+ }
946
+
947
+ /**
948
+ * Returns an array listing the events for which
949
+ * the emitter has registered listeners.
950
+ * @returns {any[]}
951
+ */
952
+ EventEmitter.prototype.eventNames = function eventNames() {
953
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
954
+ };
955
+
956
+ function arrayClone(arr) {
957
+ // At least since V8 8.3, this implementation is faster than the previous
958
+ // which always used a simple for-loop
959
+ switch (arr.length) {
960
+ case 2: return [arr[0], arr[1]];
961
+ case 3: return [arr[0], arr[1], arr[2]];
962
+ case 4: return [arr[0], arr[1], arr[2], arr[3]];
963
+ case 5: return [arr[0], arr[1], arr[2], arr[3], arr[4]];
964
+ case 6: return [arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]];
965
+ }
966
+ return ArrayPrototypeSlice(arr);
967
+ }
968
+
969
+ function unwrapListeners(arr) {
970
+ const ret = arrayClone(arr);
971
+ for (let i = 0; i < ret.length; ++i) {
972
+ const orig = ret[i].listener;
973
+ if (typeof orig === 'function')
974
+ ret[i] = orig;
975
+ }
976
+ return ret;
977
+ }
ndcc/lib/index.html ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>{{title}}</title>
5
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
6
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.slim.js"></script>
7
+ <style>
8
+ {{style}}
9
+ </style>
10
+ </head>
11
+ <body>
12
+ <div class="content">
13
+ <div class="header">
14
+ <b>{{title}}</b>
15
+ <div id="span-controls" class="span-controls">
16
+ </div>
17
+ </div>
18
+ <div class="container">
19
+ <div class="stats-column">
20
+ <h5>CPU Usage</h5>
21
+ <h1 id="cpuStat">- %</h1>
22
+ </div>
23
+ <div class="chart-container">
24
+ <canvas id="cpuChart" width="400" height="100"></canvas>
25
+ </div>
26
+ </div>
27
+ <div class="container">
28
+ <div class="stats-column">
29
+ <h5>Memory Usage</h5>
30
+ <h1 id="memStat">- %</h1>
31
+ </div>
32
+ <div class="chart-container">
33
+ <canvas id="memChart" width="200" height="100"></canvas>
34
+ </div>
35
+ </div>
36
+ <div class="container">
37
+ <div class="stats-column">
38
+ <h5>One Minute Load Avg</h5>
39
+ <h1 id="loadStat">-</h1>
40
+ </div>
41
+ <div class="chart-container">
42
+ <canvas id="loadChart" width="200" height="100"></canvas>
43
+ </div>
44
+ </div>
45
+ <div class="container">
46
+ <div class="stats-column">
47
+ <h5>Response Time</h5>
48
+ <h1 id="responseTimeStat">-</h1>
49
+ </div>
50
+ <div class="chart-container">
51
+ <canvas id="responseTimeChart" width="200" height="100"></canvas>
52
+ </div>
53
+ </div>
54
+ <div class="container">
55
+ <div class="stats-column">
56
+ <h5>Requests per Second</h5>
57
+ <h1 id="rpsStat">-</h1>
58
+ </div>
59
+ <div class="chart-container">
60
+ <canvas id="rpsChart" width="200" height="100"></canvas>
61
+ </div>
62
+ </div>
63
+ <div class="container">
64
+ <div class="stats-column">
65
+ <h5>Status Codes</h5>
66
+ <h6 class="status-code status-code-2xx">2xx</h6>
67
+ <h6 class="status-code status-code-3xx">3xx</h6>
68
+ <h6 class="status-code status-code-4xx">4xx</h6>
69
+ <h6 class="status-code status-code-5xx">5xx</h6>
70
+ </div>
71
+ <div class="chart-container">
72
+ <canvas id="statusCodesChart" width="200" height="100"></canvas>
73
+ </div>
74
+ </div>
75
+ <div class="footer">
76
+ <p>Made with &#9829; with Socket.io & Chart.js</p>
77
+ </div>
78
+ </div>
79
+ <script>
80
+ {{script}}
81
+ </script>
82
+ </body>
83
+ </html>
ndcc/lib/index.js ADDED
The diff for this file is too large to render. See raw diff
 
ndcc/lib/init-scripts/launchd.tpl ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>Label</key>
6
+ <string>com.PM2</string>
7
+ <key>UserName</key>
8
+ <string>%USER%</string>
9
+ <key>KeepAlive</key>
10
+ <true/>
11
+ <key>ProgramArguments</key>
12
+ <array>
13
+ <string>/bin/sh</string>
14
+ <string>-c</string>
15
+ <string>%PM2_PATH% resurrect</string>
16
+ </array>
17
+ <key>RunAtLoad</key>
18
+ <true/>
19
+ <key>OnDemand</key>
20
+ <false/>
21
+ <key>LaunchOnlyOnce</key>
22
+ <true/>
23
+ <key>EnvironmentVariables</key>
24
+ <dict>
25
+ <key>PATH</key>
26
+ <string>%NODE_PATH%</string>
27
+ <key>PM2_HOME</key>
28
+ <string>%HOME_PATH%</string>
29
+ </dict>
30
+ <key>StandardErrorPath</key>
31
+ <string>/tmp/com.PM2.err</string>
32
+ <key>StandardOutPath</key>
33
+ <string>/tmp/com.PM2.out</string>
34
+ </dict>
35
+ </plist>
ndcc/lib/init-scripts/openrc.tpl ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/sbin/openrc-run
2
+ # Copyright 2013-2022 the PM2 project authors. All rights reserved.
3
+ # Init script automatically generated by pm2 startup
4
+
5
+ description="Production process manager for Node.js apps with a built-in load balancer."
6
+
7
+ extra_started_commands="reload"
8
+
9
+ PM2="%PM2_PATH%"
10
+ user=${PM2_USER:-%USER%}
11
+ export PM2_HOME=$(eval echo ~${user})"/.pm2/"
12
+ # Options for start-stop-daemon (default start function)
13
+ command=${PM2}
14
+ command_user=${user}
15
+ command_args="resurrect"
16
+ pidfile=${PM2_HOME}/pm2.pid
17
+
18
+ run_pm2_as_user() {
19
+ einfo "${PM2} $@"
20
+ eval su -l ${user} -c \'${PM2} $@\'
21
+ }
22
+
23
+ depend() {
24
+ need net
25
+ need localmount
26
+ after bootmisc
27
+ }
28
+
29
+ start_post() {
30
+ if [ "${user}" == "root" ]; then
31
+ ewarn "PM2: Better run this daemon as a non root user. To set this user create"
32
+ ewarn "PM2: /etc/conf.d/pm2 file and define 'PM2_USER=user' there."
33
+ ewarn "PM2: Note user MUST have home directory for PM2 logs/state/etc..."
34
+ fi
35
+ einfo "PM2: Process Manager started. To start services run:"
36
+ einfo "PM2: # su -l ${user} -c '$PM2 start /path/to/app'"
37
+ }
38
+
39
+ stop() {
40
+ ebegin "Stopping PM2 process manager..."
41
+ run_pm2_as_user dump
42
+ run_pm2_as_user kill
43
+ eend $?
44
+ }
45
+
46
+ reload() {
47
+ ebegin "Reloading pm2"
48
+ run_pm2_as_user reload all
49
+ eend $?
50
+ }
51
+
52
+ # vim: ts=4
ndcc/lib/init-scripts/rcd-openbsd.tpl ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ #
3
+ # from /usr/ports/infrastructure/templates/rc.template
4
+
5
+ daemon="/usr/local/bin/pm2"
6
+ #daemon_flags=
7
+ #daemon_rtable=0
8
+ #daemon_timeout="30"
9
+ daemon_user="%USER%"
10
+
11
+ . /etc/rc.d/rc.subr
12
+
13
+ pexp="node: PM2.*God Daemon.*"
14
+ #rc_bg= # (undefined)
15
+ #rc_reload= # (undefined)
16
+ #rc_usercheck=YES
17
+
18
+ #rc_pre() {
19
+ #}
20
+
21
+ rc_start() {
22
+ ${rcexec} "${daemon} ${daemon_flags} resurrect"
23
+ }
24
+
25
+ #rc_check() {
26
+ # pgrep -T "${daemon_rtable}" -q -xf "${pexp}"
27
+ #}
28
+
29
+ rc_reload() {
30
+ ${rcexec} "${daemon} reload all"
31
+ #pkill -HUP -T "${daemon_rtable}" -xf "${pexp}"
32
+ }
33
+
34
+ #rc_stop() {
35
+ # pkill -T "${daemon_rtable}" -xf "${pexp}"
36
+ #}
37
+
38
+ #rc_post() {
39
+ #}
40
+
41
+ rc_cmd $1
ndcc/lib/init-scripts/rcd.tpl ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ # PROVIDE: pm2
4
+ # REQUIRE: LOGIN
5
+ # KEYWORD: shutdown
6
+
7
+ . /etc/rc.subr
8
+
9
+ name="%SERVICE_NAME%"
10
+ rcvar="%SERVICE_NAME%_enable"
11
+
12
+ start_cmd="pm2_start"
13
+ stop_cmd="pm2_stop"
14
+ reload_cmd="pm2_reload"
15
+ status_cmd="pm2_status"
16
+ extra_commands="reload status"
17
+
18
+ pm2()
19
+ {
20
+ env PATH="$PATH:%NODE_PATH%" PM2_HOME="%HOME_PATH%" su -m "%USER%" -c "%PM2_PATH% $*"
21
+ }
22
+
23
+ pm2_start()
24
+ {
25
+ pm2 resurrect
26
+ }
27
+
28
+ pm2_stop()
29
+ {
30
+ pm2 kill
31
+ }
32
+
33
+ pm2_reload()
34
+ {
35
+ pm2 reload all
36
+ }
37
+
38
+ pm2_status()
39
+ {
40
+ pm2 list
41
+ }
42
+
43
+ load_rc_config $name
44
+ run_rc_command "$1"
ndcc/lib/init-scripts/smf.tpl ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1">
3
+ <service_bundle type="manifest" name="%SERVICE_NAME%">
4
+ <service name="application/%SERVICE_NAME%" type="service" version="1">
5
+ <create_default_instance enabled="false"/>
6
+ <single_instance/>
7
+
8
+ <dependency name="network" grouping="require_all" restart_on="error" type="service">
9
+ <service_fmri value="svc:/milestone/network:default"/>
10
+ </dependency>
11
+
12
+ <dependency name="filesystem" grouping="require_all" restart_on="error" type="service">
13
+ <service_fmri value="svc:/system/filesystem/local"/>
14
+ </dependency>
15
+
16
+ <method_context>
17
+ <method_environment>
18
+ <envvar name='PATH' value="%NODE_PATH%:/usr/local/sbin:/usr/local/bin:/opt/local/sbin:/opt/local/bin:/usr/sbin:/usr/bin:/sbin"/>
19
+ <envvar name='PM2_HOME' value="%HOME_PATH%"/>
20
+ </method_environment>
21
+ </method_context>
22
+
23
+ <exec_method type="method" name="start" exec="%PM2_PATH% resurrect" timeout_seconds="60"/>
24
+ <exec_method type="method" name="refresh" exec="%PM2_PATH% reload all" timeout_seconds="60"/>
25
+ <exec_method type="method" name="stop" exec="%PM2_PATH% kill" timeout_seconds="60"/>
26
+
27
+ <property_group name="startd" type="framework">
28
+ <propval name="duration" type="astring" value="contract"/>
29
+ <propval name="ignore_error" type="astring" value="core,signal"/>
30
+ </property_group>
31
+
32
+ <property_group name="application" type="application"></property_group>
33
+ <stability value="Evolving"/>
34
+
35
+ <template>
36
+ <common_name>
37
+ <loctext xml:lang="C">
38
+ PM2 process manager
39
+ </loctext>
40
+ </common_name>
41
+ </template>
42
+ </service>
43
+ </service_bundle>
ndcc/lib/init-scripts/systemd-online.tpl ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Unit]
2
+ Description=PM2 process manager
3
+ Documentation=https://pm2.keymetrics.io/
4
+ After=network-online.target
5
+ Restart=on-failure
6
+
7
+ [Service]
8
+ Type=forking
9
+ User=%USER%
10
+ LimitNOFILE=infinity
11
+ LimitNPROC=infinity
12
+ LimitCORE=infinity
13
+ Environment=PATH=%NODE_PATH%:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
14
+ Environment=PM2_HOME=%HOME_PATH%
15
+ PIDFile=%HOME_PATH%/pm2.pid
16
+
17
+ ExecStart=%PM2_PATH% resurrect
18
+ ExecReload=%PM2_PATH% reload all
19
+ ExecStop=%PM2_PATH% kill
20
+
21
+ [Install]
22
+ WantedBy=network-online.target
ndcc/lib/init-scripts/systemd.tpl ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Unit]
2
+ Description=PM2 process manager
3
+ Documentation=https://pm2.keymetrics.io/
4
+ After=network.target
5
+
6
+ [Service]
7
+ Type=forking
8
+ User=%USER%
9
+ LimitNOFILE=infinity
10
+ LimitNPROC=infinity
11
+ LimitCORE=infinity
12
+ Environment=PATH=%NODE_PATH%:/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
13
+ Environment=PM2_HOME=%HOME_PATH%
14
+ PIDFile=%HOME_PATH%/pm2.pid
15
+ Restart=on-failure
16
+
17
+ ExecStart=%PM2_PATH% resurrect
18
+ ExecReload=%PM2_PATH% reload all
19
+ ExecStop=%PM2_PATH% kill
20
+
21
+ [Install]
22
+ WantedBy=multi-user.target
ndcc/lib/init-scripts/upstart.tpl ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ ### BEGIN INIT INFO
3
+ # Provides: pm2
4
+ # Required-Start: $local_fs $remote_fs $network
5
+ # Required-Stop: $local_fs $remote_fs $network
6
+ # Default-Start: 2 3 4 5
7
+ # Default-Stop: 0 1 6
8
+ # Short-Description: PM2 Init script
9
+ # Description: PM2 process manager
10
+ ### END INIT INFO
11
+
12
+ NAME=pm2
13
+ PM2=%PM2_PATH%
14
+ USER=%USER%
15
+ DEFAULT=/etc/default/$NAME
16
+
17
+ export PATH=%NODE_PATH%:$PATH
18
+ export PM2_HOME="%HOME_PATH%"
19
+
20
+ # The following variables can be overwritten in $DEFAULT
21
+
22
+ # maximum number of open files
23
+ MAX_OPEN_FILES=
24
+
25
+ # overwrite settings from default file
26
+ if [ -f "$DEFAULT" ]; then
27
+ . "$DEFAULT"
28
+ fi
29
+
30
+ # set maximum open files if set
31
+ if [ -n "$MAX_OPEN_FILES" ]; then
32
+ ulimit -n $MAX_OPEN_FILES
33
+ fi
34
+
35
+ get_user_shell() {
36
+ local shell
37
+ shell=$(getent passwd "${1:-$(whoami)}" | cut -d: -f7 | sed -e 's/[[:space:]]*$//')
38
+
39
+ if [[ $shell == *"/sbin/nologin" ]] || [[ $shell == "/bin/false" ]] || [[ -z "$shell" ]];
40
+ then
41
+ shell="/bin/bash"
42
+ fi
43
+
44
+ echo "$shell"
45
+ }
46
+
47
+ super() {
48
+ local shell
49
+ shell=$(get_user_shell $USER)
50
+ su - "$USER" -s "$shell" -c "PATH=$PATH; PM2_HOME=$PM2_HOME $*"
51
+ }
52
+
53
+ start() {
54
+ echo "Starting $NAME"
55
+ super $PM2 resurrect
56
+ }
57
+
58
+ stop() {
59
+ super $PM2 kill
60
+ }
61
+
62
+ restart() {
63
+ echo "Restarting $NAME"
64
+ stop
65
+ start
66
+ }
67
+
68
+ reload() {
69
+ echo "Reloading $NAME"
70
+ super $PM2 reload all
71
+ }
72
+
73
+ status() {
74
+ echo "Status for $NAME:"
75
+ super $PM2 list
76
+ RETVAL=$?
77
+ }
78
+
79
+ case "$1" in
80
+ start)
81
+ start
82
+ ;;
83
+ stop)
84
+ stop
85
+ ;;
86
+ status)
87
+ status
88
+ ;;
89
+ restart)
90
+ restart
91
+ ;;
92
+ reload)
93
+ reload
94
+ ;;
95
+ force-reload)
96
+ reload
97
+ ;;
98
+ *)
99
+ echo "Usage: {start|stop|status|restart|reload|force-reload}"
100
+ exit 1
101
+ ;;
102
+ esac
103
+ exit $RETVAL
ndcc/lib/pm2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ require('../lib/binaries/CLI.js');
ndcc/lib/pm2-sysmonit/LICENSE-APACHE.txt ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
ndcc/lib/pm2-sysmonit/index.js ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const tx2 = require('tx2')
3
+ const SystemInfos = require('./src/SystemInfos.js')
4
+ const PM2Infos = require('./src/pm2.js')
5
+
6
+ class SysMonit {
7
+ constructor() {
8
+ this.sysinfos = new SystemInfos()
9
+ this.report = {}
10
+ this.pass = 0
11
+
12
+ this.pm2infos = new PM2Infos()
13
+ this.pm2_report = {}
14
+ }
15
+
16
+ start() {
17
+ this.sysinfos.startCollection()
18
+ this.report = this.sysinfos.report()
19
+
20
+ this.pm2infos.startCollection()
21
+ this.pm2_report = this.pm2infos.report()
22
+
23
+ this.bindActions()
24
+
25
+ setInterval(() => {
26
+ if (this.pass++ < 4)
27
+ this.bindMetrics()
28
+ this.report = this.sysinfos.report()
29
+ this.pm2_report = this.pm2infos.report()
30
+
31
+ this.processContinuousMetrics()
32
+
33
+ if (process.env.VERBOSE) {
34
+ console.log(JSON.stringify(this.report, '', 2))
35
+ console.log(JSON.stringify(this.pm2_report, '', 2))
36
+ }
37
+ }, 1000)
38
+ }
39
+
40
+ bindActions() {
41
+ tx2.action('info', (cb) => {
42
+ cb(this.sysinfos.report())
43
+ })
44
+ }
45
+
46
+ processContinuousMetrics() {
47
+ let most_used_disk = this.report.storage.filesystems.reduce((p, v) => {
48
+ return (p.use < v.use ? p : v)
49
+ })
50
+
51
+ tx2.metric(`Disk Usage`, '%', () => most_used_disk.use)
52
+ tx2.metric(`Disk Size`, 'gb', () => (most_used_disk.size / 1024 / 1024 / 1024).toFixed(2))
53
+
54
+ let tx5 = 0, rx5 = 0
55
+ Object.keys(this.report.network).forEach(iface => {
56
+ tx5 += this.report.network[iface].tx_5
57
+ rx5 += this.report.network[iface].rx_5
58
+
59
+ })
60
+ tx2.metric(`Total TX`, 'mb/s', () => tx5)
61
+ tx2.metric(`Total RX`, 'mb/s', () => rx5)
62
+ }
63
+
64
+ bindMetrics() {
65
+ tx2.metric('PM2 CPU Usage', '%', () => this.pm2_report.pm2.cpu)
66
+ tx2.metric('PM2 Memory Usage', 'mb', () => this.pm2_report.pm2.mem)
67
+
68
+ tx2.metric('PM2 Agent CPU Usage', '%', () => this.pm2_report.agent.cpu)
69
+ tx2.metric('PM2 Agent Memory Usage', 'mb', () => this.pm2_report.agent.mem)
70
+
71
+ /**
72
+ * From Sysinfo
73
+ */
74
+ tx2.metric('CPU Usage', '%', () => this.report.cpu.load)
75
+ tx2.metric('CPUs Usage', () => this.report.cpu.loads)
76
+ tx2.metric('CPU Temperature', '°C', () => this.report.cpu.temperature)
77
+ tx2.metric('RAM Total', 'gb', () => this.report.mem.total)
78
+ tx2.metric('RAM Free', 'gb', () => this.report.mem.free)
79
+ tx2.metric('RAM Active', 'gb', () => this.report.mem.active)
80
+ tx2.metric('RAM Available', 'gb', () => this.report.mem.available)
81
+ tx2.metric('RAM Usage', '%', () => this.report.mem.usage)
82
+ tx2.metric('FD Opened', () => this.report.fd.opened)
83
+ tx2.metric('Disk Writes', 'mb/s', () => this.report.storage.io.read)
84
+ tx2.metric('Disk Reads', 'mb/s', () => this.report.storage.io.write)
85
+
86
+
87
+ this.report.storage.filesystems.forEach((fss, i) => {
88
+ if (!fss.fs) return
89
+ tx2.metric(`fs:use:${fss.fs}`, '%', () => this.report.storage.filesystems[i].use)
90
+ tx2.metric(`fs:size:${fss.fs}`, 'gb', () => (this.report.storage.filesystems[i].size / 1024 / 1024 / 1024).toFixed(2))
91
+ })
92
+
93
+ Object.keys(this.report.network).forEach(iface => {
94
+ tx2.metric(`net:tx_5:${iface}`, 'mb/s', () => this.report.network[iface].tx_5)
95
+ tx2.metric(`net:rx_5:${iface}`, 'mb/s', () => this.report.network[iface].rx_5)
96
+ tx2.metric(`net:rx_errors_60:${iface}`, '/min', () => this.report.network[iface].rx_errors_60)
97
+ tx2.metric(`net:tx_errors_60:${iface}`, '/min', () => this.report.network[iface].tx_errors_60)
98
+ tx2.metric(`net:rx_dropped_60:${iface}`, '/min', () => this.report.network[iface].rx_dropped_60)
99
+ tx2.metric(`net:tx_dropped_60:${iface}`, '/min', () => this.report.network[iface].tx_dropped_60)
100
+ })
101
+
102
+ if (this.report.graphics.memTotal) {
103
+ tx2.metric('graphics:mem:total', 'mb', () => this.report.graphics.memTotal)
104
+ tx2.metric('graphics:mem:used', 'mb', () => this.report.graphics.memUsed)
105
+ tx2.metric('graphics:temp', '°C', () => this.report.graphics.temperature)
106
+ }
107
+
108
+ //tx2.transpose('report', () => this.report)
109
+ }
110
+ }
111
+
112
+ if (require.main === module) {
113
+ let sys = new SysMonit()
114
+ sys.start()
115
+ }
ndcc/lib/pm2-sysmonit/node_modules/pidusage/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014 soyuka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ndcc/lib/pm2-sysmonit/node_modules/pidusage/index.js ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ var stats = require('./lib/stats')
4
+
5
+ /**
6
+ * Get pid informations.
7
+ * @public
8
+ * @param {Number|Number[]|String|String[]} pids A pid or a list of pids.
9
+ * @param {Object} [options={}] Options object
10
+ * @param {Function} [callback=undefined] Called when the statistics are ready.
11
+ * If not provided a promise is returned instead.
12
+ * @returns {Promise.<Object>} Only when the callback is not provided.
13
+ */
14
+ function pidusage (pids, options, callback) {
15
+ if (typeof options === 'function') {
16
+ callback = options
17
+ options = {}
18
+ }
19
+
20
+ if (options === undefined) {
21
+ options = {}
22
+ }
23
+
24
+ if (typeof callback === 'function') {
25
+ stats(pids, options, callback)
26
+ return
27
+ }
28
+
29
+ return new Promise(function (resolve, reject) {
30
+ stats(pids, options, function (err, data) {
31
+ if (err) return reject(err)
32
+ resolve(data)
33
+ })
34
+ })
35
+ }
36
+
37
+ module.exports = pidusage
38
+ module.exports.clear = require('./lib/history').clear
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/bin.js ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ var spawn = require('child_process').spawn
4
+
5
+ /**
6
+ * Spawn a binary and read its stdout.
7
+ * @param {String} cmd
8
+ * @param {String[]} args
9
+ * @param {Function} done(err, stdout)
10
+ */
11
+ function run (cmd, args, options, done) {
12
+ if (typeof options === 'function') {
13
+ done = options
14
+ options = undefined
15
+ }
16
+
17
+ var executed = false
18
+ var ch = spawn(cmd, args, options)
19
+ var stdout = ''
20
+ var stderr = ''
21
+
22
+ ch.stdout.on('data', function (d) {
23
+ stdout += d.toString()
24
+ })
25
+
26
+ ch.stderr.on('data', function (d) {
27
+ stderr += d.toString()
28
+ })
29
+
30
+ ch.on('error', function (err) {
31
+ if (executed) return
32
+ executed = true
33
+ done(new Error(err))
34
+ })
35
+
36
+ ch.on('close', function (code, signal) {
37
+ if (executed) return
38
+ executed = true
39
+
40
+ if (stderr) {
41
+ return done(new Error(stderr))
42
+ }
43
+
44
+ done(null, stdout, code)
45
+ })
46
+ }
47
+
48
+ module.exports = run
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/helpers/cpu.js ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var os = require('os')
2
+ var fs = require('fs')
3
+ var exec = require('child_process').exec
4
+ var parallel = require('./parallel')
5
+
6
+ /**
7
+ * Gathers Clock, PageSize and system uptime through /proc/uptime
8
+ * This method is mocked in procfile tests
9
+ */
10
+ function updateCpu (cpu, next) {
11
+ if (cpu !== null) {
12
+ getRealUptime(function (err, uptime) {
13
+ if (err) return next(err)
14
+ cpu.uptime = uptime
15
+ next(null, cpu)
16
+ })
17
+ return
18
+ }
19
+
20
+ parallel([
21
+ getClockAndPageSize,
22
+ getRealUptime
23
+ ], function (err, data) {
24
+ if (err) return next(err)
25
+
26
+ cpu = {
27
+ clockTick: data[0].clockTick,
28
+ pageSize: data[0].pageSize,
29
+ uptime: data[1]
30
+ }
31
+
32
+ next(null, cpu)
33
+ })
34
+ }
35
+
36
+ module.exports = updateCpu
37
+
38
+ /**
39
+ * Fallback on os.uptime(), though /proc/uptime is more precise
40
+ */
41
+ function getRealUptime (next) {
42
+ fs.readFile('/proc/uptime', 'utf8', function (err, uptime) {
43
+ if (err || uptime === undefined) {
44
+ console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value")
45
+ return next(null, os.uptime())
46
+ }
47
+
48
+ return next(null, parseFloat(uptime.split(' ')[0]))
49
+ })
50
+ }
51
+
52
+ function getClockAndPageSize (next) {
53
+ parallel([
54
+ function getClockTick (cb) {
55
+ getconf('CLK_TCK', { default: 100 }, cb)
56
+ },
57
+ function getPageSize (cb) {
58
+ getconf('PAGESIZE', { default: 4096 }, cb)
59
+ }
60
+ ], function (err, data) {
61
+ if (err) return next(err)
62
+
63
+ next(null, { clockTick: data[0], pageSize: data[1] })
64
+ })
65
+ }
66
+
67
+ function getconf (keyword, options, next) {
68
+ if (typeof options === 'function') {
69
+ next = options
70
+ options = { default: '' }
71
+ }
72
+
73
+ exec('getconf ' + keyword, function (error, stdout, stderr) {
74
+ if (error !== null) {
75
+ console.error('Error while getting ' + keyword, error)
76
+ return next(null, options.default)
77
+ }
78
+
79
+ stdout = parseInt(stdout)
80
+
81
+ if (!isNaN(stdout)) {
82
+ return next(null, stdout)
83
+ }
84
+
85
+ return next(null, options.default)
86
+ })
87
+ }
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/helpers/parallel.js ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // execute an array of asynchronous functions in parallel
2
+ // @param {Array} fns - an array of functions
3
+ // @param {Function} done - callback(err, results)
4
+ function parallel (fns, options, done) {
5
+ if (typeof options === 'function') {
6
+ done = options
7
+ options = {}
8
+ }
9
+
10
+ var keys
11
+ if (!Array.isArray(fns)) { keys = Object.keys(fns) }
12
+ var length = keys ? keys.length : fns.length
13
+ var pending = length
14
+ var results = keys ? {} : []
15
+
16
+ function each (i, err, result) {
17
+ results[i] = result
18
+
19
+ if (--pending === 0 || (err && !options.graceful)) {
20
+ if (options.graceful && err && length > 1) {
21
+ err = null
22
+ }
23
+
24
+ done && done(err, results)
25
+ done = null
26
+ }
27
+ }
28
+
29
+ if (keys) {
30
+ keys.forEach(function (key) {
31
+ fns[key](function (err, res) {
32
+ each(key, err, res)
33
+ })
34
+ })
35
+ } else {
36
+ fns.forEach(function (fn, i) {
37
+ fn(function (err, res) {
38
+ each(i, err, res)
39
+ })
40
+ })
41
+ }
42
+ }
43
+
44
+ module.exports = parallel
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/history.js ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+ var DEFAULT_MAXAGE = 60000
3
+
4
+ var expiration = {}
5
+ var history = {}
6
+ var expireListeners = {}
7
+
8
+ var size = 0
9
+ var interval = null
10
+
11
+ function get (pid, maxage) {
12
+ if (maxage <= 0) {
13
+ return
14
+ }
15
+
16
+ if (history[pid] !== undefined) {
17
+ expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE)
18
+ }
19
+
20
+ return history[pid]
21
+ }
22
+
23
+ function set (pid, object, maxage, onExpire) {
24
+ if (object === undefined || maxage <= 0) return
25
+
26
+ expiration[pid] = Date.now() + (maxage || DEFAULT_MAXAGE)
27
+ if (history[pid] === undefined) {
28
+ size++
29
+ sheduleInvalidator(maxage)
30
+ }
31
+
32
+ history[pid] = object
33
+ if (onExpire) {
34
+ expireListeners[pid] = onExpire
35
+ }
36
+ }
37
+
38
+ function sheduleInvalidator (maxage) {
39
+ if (size > 0) {
40
+ if (interval === null) {
41
+ interval = setInterval(runInvalidator, (maxage || DEFAULT_MAXAGE) / 2)
42
+ if (typeof interval.unref === 'function') {
43
+ interval.unref()
44
+ }
45
+ }
46
+
47
+ return
48
+ }
49
+
50
+ if (interval !== null) {
51
+ clearInterval(interval)
52
+ interval = null
53
+ }
54
+ }
55
+
56
+ function runInvalidator () {
57
+ var now = Date.now()
58
+ var pids = Object.keys(expiration)
59
+ for (var i = 0; i < pids.length; i++) {
60
+ var pid = pids[i]
61
+ if (expiration[pid] < now) {
62
+ size--
63
+ if (expireListeners[pid]) {
64
+ expireListeners[pid](history[pid])
65
+ }
66
+
67
+ delete history[pid]
68
+ delete expiration[pid]
69
+ delete expireListeners[pid]
70
+ }
71
+ }
72
+ sheduleInvalidator()
73
+ }
74
+
75
+ function deleteLoop (obj) { for (const i in obj) { delete obj[i] } }
76
+
77
+ function clear () {
78
+ if (interval !== null) {
79
+ clearInterval(interval)
80
+ interval = null
81
+ }
82
+
83
+ deleteLoop(history)
84
+ deleteLoop(expiration)
85
+ deleteLoop(expireListeners)
86
+ }
87
+
88
+ module.exports = {
89
+ get: get,
90
+ set: set,
91
+ clear: clear
92
+ }
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/procfile.js ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var fs = require('fs')
2
+ var path = require('path')
3
+ var updateCpu = require('./helpers/cpu')
4
+ var parallel = require('./helpers/parallel')
5
+ var history = require('./history')
6
+ var cpuInfo = null
7
+ var Buffer = require('safe-buffer').Buffer
8
+ var SIZE = 1024 // if the stat file is bigger then this I'll buy you a drink
9
+
10
+ function noop () {}
11
+
12
+ function open (path, history, cb) {
13
+ if (history.fd) { return cb(null, history.fd) }
14
+ fs.open(path, 'r', cb)
15
+ }
16
+
17
+ function close (history) {
18
+ if (history.fd) {
19
+ fs.close(history.fd, noop)
20
+ }
21
+ }
22
+
23
+ function readUntilEnd (fd, buf, cb) {
24
+ var firstRead = false
25
+ if (typeof buf === 'function') {
26
+ cb = buf
27
+ buf = Buffer.alloc(SIZE)
28
+ firstRead = true
29
+ }
30
+
31
+ fs.read(fd, buf, 0, SIZE, 0, function (err, bytesRead, buffer) {
32
+ if (err) {
33
+ cb(err)
34
+ return
35
+ }
36
+
37
+ var data = Buffer.concat([buf, buffer], firstRead ? bytesRead : buf.length + bytesRead)
38
+ if (bytesRead === SIZE) {
39
+ readUntilEnd(fd, data, cb)
40
+ return
41
+ }
42
+
43
+ cb(null, buf)
44
+ })
45
+ }
46
+
47
+ function readProcFile (pid, options, done) {
48
+ var hst = history.get(pid, options.maxage)
49
+ var again = false
50
+ if (hst === undefined) {
51
+ again = true
52
+ hst = {}
53
+ }
54
+
55
+ // Arguments to path.join must be strings
56
+ open(path.join('/proc', '' + pid, 'stat'), hst, function (err, fd) {
57
+ if (err) {
58
+ if (err.code === 'ENOENT') {
59
+ err.message = 'No matching pid found'
60
+ }
61
+ return done(err, null)
62
+ }
63
+
64
+ if (err) {
65
+ return done(err)
66
+ }
67
+
68
+ readUntilEnd(fd, function (err, buffer) {
69
+ if (err) {
70
+ return done(err)
71
+ }
72
+
73
+ var infos = buffer.toString('utf8')
74
+ var date = Date.now()
75
+
76
+ // https://github.com/arunoda/node-usage/commit/a6ca74ecb8dd452c3c00ed2bde93294d7bb75aa8
77
+ // preventing process space in name by removing values before last ) (pid (name) ...)
78
+ var index = infos.lastIndexOf(')')
79
+ infos = infos.substr(index + 2).split(' ')
80
+
81
+ // according to http://man7.org/linux/man-pages/man5/proc.5.html (index 0 based - 2)
82
+ // In kernels before Linux 2.6, start was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
83
+ var stat = {
84
+ ppid: parseInt(infos[1]),
85
+ utime: parseFloat(infos[11]) * 1000 / cpuInfo.clockTick,
86
+ stime: parseFloat(infos[12]) * 1000 / cpuInfo.clockTick,
87
+ cutime: parseFloat(infos[13]) * 1000 / cpuInfo.clockTick,
88
+ cstime: parseFloat(infos[14]) * 1000 / cpuInfo.clockTick,
89
+ start: parseFloat(infos[19]) * 1000 / cpuInfo.clockTick,
90
+ rss: parseFloat(infos[21]),
91
+ uptime: cpuInfo.uptime * 1000,
92
+ fd: fd
93
+ }
94
+
95
+ var memory = stat.rss * cpuInfo.pageSize
96
+
97
+ // https://stackoverflow.com/a/16736599/3921589
98
+ var childrens = options.childrens ? stat.cutime + stat.cstime : 0
99
+ // process usage since last call in seconds
100
+ var total = (stat.stime - (hst.stime || 0) + stat.utime - (hst.utime || 0) + childrens)
101
+ // time elapsed between calls in seconds
102
+ var seconds = Math.abs(hst.uptime !== undefined ? stat.uptime - hst.uptime : stat.start - stat.uptime)
103
+ var cpu = seconds > 0 ? (total / seconds) * 100 : 0
104
+
105
+ history.set(pid, stat, options.maxage, close)
106
+
107
+ if (again) {
108
+ return readProcFile(pid, options, done)
109
+ }
110
+
111
+ return done(null, {
112
+ cpu: cpu,
113
+ memory: memory,
114
+ ctime: stat.utime + stat.stime,
115
+ elapsed: stat.uptime - stat.start,
116
+ timestamp: date,
117
+ pid: pid,
118
+ ppid: stat.ppid
119
+ })
120
+ })
121
+ })
122
+ }
123
+
124
+ function procfile (pids, options, done) {
125
+ updateCpu(cpuInfo, function (err, result) {
126
+ if (err) return done(err)
127
+
128
+ cpuInfo = result
129
+ var fns = {}
130
+
131
+ pids.forEach(function (pid, i) {
132
+ fns[pid] = function (cb) {
133
+ readProcFile(pid, options, cb)
134
+ }
135
+ })
136
+
137
+ parallel(fns, { graceful: true }, done)
138
+ })
139
+ }
140
+
141
+ module.exports = procfile
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/ps.js ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ var os = require('os')
4
+ var bin = require('./bin')
5
+ var history = require('./history')
6
+
7
+ var PLATFORM = os.platform()
8
+
9
+ function parseTime (timestr, centisec) {
10
+ var time = 0
11
+ var tpart = timestr.split(/-|:|\./)
12
+ var i = tpart.length - 1
13
+ if (i >= 0 && centisec && PLATFORM === 'darwin') {
14
+ time += parseInt(tpart[i--], 10) * 10
15
+ }
16
+ if (i >= 0) { // Seconds
17
+ time += parseInt(tpart[i--], 10) * 1000
18
+ }
19
+ if (i >= 0) { // Minutes
20
+ time += parseInt(tpart[i--], 10) * 60000
21
+ }
22
+ if (i >= 0) { // Hours
23
+ time += parseInt(tpart[i--], 10) * 3600000
24
+ }
25
+ if (i >= 0) { // Days
26
+ time += parseInt(tpart[i--], 10) * 86400000
27
+ }
28
+ return time
29
+ }
30
+
31
+ /**
32
+ * Get pid informations through ps command.
33
+ * @param {Number[]} pids
34
+ * @param {Object} options
35
+ * @param {Function} done(err, stat)
36
+ */
37
+ function ps (pids, options, done) {
38
+ var pArg = pids.join(',')
39
+ var args = ['-o', 'etime,pid,ppid,pcpu,rss,time', '-p', pArg]
40
+
41
+ if (PLATFORM === 'aix') {
42
+ args = ['-o', 'etime,pid,ppid,pcpu,rssize,time', '-p', pArg]
43
+ }
44
+
45
+ bin('ps', args, function (err, stdout, code) {
46
+ if (err) return done(err)
47
+ if (code === 1) {
48
+ const error = new Error('No matching pid found')
49
+ error.code = 'ENOENT'
50
+ return done(error)
51
+ }
52
+ if (code !== 0) {
53
+ return done(new Error('pidusage ps command exited with code ' + code))
54
+ }
55
+ var date = Date.now()
56
+
57
+ // Example of stdout on *nix.
58
+ // ELAPSED: format is [[dd-]hh:]mm:ss
59
+ // RSS: is counted as blocks of 1024 bytes
60
+ // TIME: format is [[dd-]hh:]mm:ss
61
+ // %CPU: goes from 0 to vcore * 100
62
+ //
63
+ // Refs: http://www.manpages.info/linux/ps.1.html
64
+ // NB: The columns are returned in the order given inside the -o option
65
+ //
66
+ // ELAPSED PID PPID %CPU RSS TIME
67
+ // 2-40:50:53 430 1 3.0 5145 1-02:03:04
68
+ // 40:50:53 432 430 0.0 2364 1-01:02:03
69
+ // 01:50:50 727 1 10.0 348932 14:27
70
+ // 00:20 7166 1 0.1 3756 0:00
71
+
72
+ // Example of stdout on Darwin
73
+ // ELAPSED: format is [[dd-]hh:]mm:ss
74
+ // RSS: is counted as blocks of 1024 bytes
75
+ // TIME: format is [[dd-]hh:]mm:ss.cc (cc are centiseconds)
76
+ // %CPU: goes from 0 to vcore * 100
77
+ //
78
+ // Refs: https://ss64.com/osx/ps.html
79
+ // NB: The columns are returned in the order given inside the -o option
80
+ //
81
+ // ELAPSED PID PPID %CPU RSS TIME
82
+ // 2-40:50:53 430 1 3.0 5145 1-02:03:04.07
83
+ // 40:50:53 432 430 0.0 2364 1-01:02:03.10
84
+ // 01:50:50 727 1 10.0 348932 14:27.26
85
+ // 00:20 7166 1 0.1 3756 0:00.02
86
+
87
+ stdout = stdout.split(os.EOL)
88
+
89
+ var statistics = {}
90
+ for (var i = 1; i < stdout.length; i++) {
91
+ var line = stdout[i].trim().split(/\s+/)
92
+
93
+ if (!line || line.length !== 6) {
94
+ continue
95
+ }
96
+
97
+ var pid = parseInt(line[1], 10)
98
+ var hst = history.get(pid, options.maxage)
99
+ if (hst === undefined) hst = {}
100
+
101
+ var ppid = parseInt(line[2], 10)
102
+ var memory = parseInt(line[4], 10) * 1024
103
+ var etime = parseTime(line[0])
104
+ var ctime = parseTime(line[5], true)
105
+
106
+ var total = (ctime - (hst.ctime || 0))
107
+ // time elapsed between calls in seconds
108
+ var seconds = Math.abs(hst.elapsed !== undefined ? etime - hst.elapsed : etime)
109
+ var cpu = seconds > 0 ? (total / seconds) * 100 : 0
110
+
111
+ statistics[pid] = {
112
+ cpu: cpu,
113
+ memory: memory,
114
+ ppid: ppid,
115
+ pid: pid,
116
+ ctime: ctime,
117
+ elapsed: etime,
118
+ timestamp: date
119
+ }
120
+
121
+ history.set(pid, statistics[pid], options.maxage)
122
+ }
123
+
124
+ done(null, statistics)
125
+ })
126
+ }
127
+
128
+ module.exports = ps
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/stats.js ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ var fs = require('fs')
4
+ var os = require('os')
5
+
6
+ var platformToMethod = {
7
+ aix: 'ps',
8
+ android: 'procfile',
9
+ alpine: 'procfile',
10
+ darwin: 'ps',
11
+ freebsd: 'ps',
12
+ linux: 'procfile',
13
+ netbsd: 'procfile',
14
+ sunos: 'ps',
15
+ win: 'wmic'
16
+ }
17
+
18
+ var ps = require('./ps')
19
+ var platform = os.platform()
20
+
21
+ if (fs.existsSync('/etc/alpine-release')) {
22
+ platform = 'alpine'
23
+ }
24
+
25
+ if (platform.match(/^win/)) {
26
+ platform = 'win'
27
+ }
28
+
29
+ var stat
30
+ try {
31
+ stat = require('./' + platformToMethod[platform])
32
+ } catch (err) {}
33
+
34
+ /**
35
+ * @callback pidCallback
36
+ * @param {Error} err A possible error.
37
+ * @param {Object} statistics The object containing the statistics.
38
+ */
39
+
40
+ /**
41
+ * Get pid informations.
42
+ * @public
43
+ * @param {Number|Number[]|String|String[]} pids A pid or a list of pids.
44
+ * @param {Object} [options={}] Options object
45
+ * @param {pidCallback} callback Called when the statistics are ready.
46
+ */
47
+ function get (pids, options, callback) {
48
+ var fn = stat
49
+ if (platform !== 'win' && options.usePs === true) {
50
+ fn = ps
51
+ }
52
+
53
+ if (stat === undefined) {
54
+ return callback(new Error(os.platform() + ' is not supported yet, please open an issue (https://github.com/soyuka/pidusage)'))
55
+ }
56
+
57
+ var single = false
58
+ if (!Array.isArray(pids)) {
59
+ single = true
60
+ pids = [pids]
61
+ }
62
+
63
+ if (pids.length === 0) {
64
+ return callback(new TypeError('You must provide at least one pid'))
65
+ }
66
+
67
+ for (var i = 0; i < pids.length; i++) {
68
+ pids[i] = parseInt(pids[i], 10)
69
+ if (isNaN(pids[i]) || pids[i] < 0) {
70
+ return callback(new TypeError('One of the pids provided is invalid'))
71
+ }
72
+ }
73
+
74
+ fn(pids, options, function (err, stats) {
75
+ if (err) {
76
+ return callback(err)
77
+ }
78
+
79
+ if (single) {
80
+ callback(null, stats[pids[0]])
81
+ } else {
82
+ callback(null, stats)
83
+ }
84
+ })
85
+ }
86
+
87
+ module.exports = get
ndcc/lib/pm2-sysmonit/node_modules/pidusage/lib/wmic.js ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ var os = require('os')
4
+ var bin = require('./bin')
5
+ var history = require('./history')
6
+
7
+ function parseDate (datestr) {
8
+ var year = datestr.substring(0, 4)
9
+ var month = datestr.substring(4, 6)
10
+ var day = datestr.substring(6, 8)
11
+ var hour = datestr.substring(8, 10)
12
+ var minutes = datestr.substring(10, 12)
13
+ var seconds = datestr.substring(12, 14)
14
+ var useconds = datestr.substring(15, 21)
15
+ var sign = datestr.substring(21, 22)
16
+ var tmz = parseInt(datestr.substring(22, 25), 10)
17
+ var tmzh = Math.floor(tmz / 60)
18
+ var tmzm = tmz % 60
19
+
20
+ return new Date(
21
+ year + '-' + month + '-' + day + 'T' + hour +
22
+ ':' + minutes + ':' + seconds +
23
+ '.' + useconds +
24
+ sign + (tmzh > 9 ? tmzh : '0' + tmzh) + '' + (tmzm > 9 ? tmzm : '0' + tmzm)
25
+ )
26
+ }
27
+
28
+ /**
29
+ * Get pid informations through wmic command.
30
+ * @param {Number[]} pids
31
+ * @param {Object} options
32
+ * @param {Function} done(err, stat)
33
+ */
34
+ function wmic (pids, options, done) {
35
+ var whereClause = 'ProcessId=' + pids[0]
36
+ for (var i = 1; i < pids.length; i++) {
37
+ whereClause += ' or ' + 'ProcessId=' + pids[i]
38
+ }
39
+
40
+ var args = [
41
+ 'PROCESS',
42
+ 'where',
43
+ '"' + whereClause + '"',
44
+ 'get',
45
+ 'CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize'
46
+ ]
47
+
48
+ bin('wmic', args, { windowsHide: true, windowsVerbatimArguments: true }, function (err, stdout, code) {
49
+ if (err) {
50
+ if (err.message.indexOf('No Instance(s) Available.') !== -1) {
51
+ const error = new Error('No matching pid found')
52
+ error.code = 'ENOENT'
53
+ return done(error)
54
+ }
55
+ return done(err)
56
+ }
57
+ if (code !== 0) {
58
+ return done(new Error('pidusage wmic command exited with code ' + code))
59
+ }
60
+ var date = Date.now()
61
+
62
+ // Note: On Windows the returned value includes fractions of a second.
63
+ // Use Math.floor() to get whole seconds.
64
+ var uptime = Math.floor(os.uptime())
65
+
66
+ // Example of stdout on Windows 10
67
+ // CreationDate: is in the format yyyymmddHHMMSS.mmmmmmsUUU
68
+ // KernelModeTime: is in units of 100 ns
69
+ // UserModeTime: is in units of 100 ns
70
+ // WorkingSetSize: is in bytes
71
+ //
72
+ // Refs: https://superuser.com/a/937401/470946
73
+ // Refs: https://msdn.microsoft.com/en-us/library/aa394372(v=vs.85).aspx
74
+ // NB: The columns are returned in lexicographical order
75
+ //
76
+ // CreationDate KernelModeTime ParentProcessId ProcessId UserModeTime WorkingSetSize
77
+ // 20150329221650.080654+060 153750000 0 777 8556250000 110821376
78
+
79
+ stdout = stdout.split(os.EOL)
80
+
81
+ var again = false
82
+ var statistics = {}
83
+ for (var i = 1; i < stdout.length; i++) {
84
+ var line = stdout[i].trim().split(/\s+/)
85
+
86
+ if (!line || line.length !== 6) {
87
+ continue
88
+ }
89
+
90
+ var creation = parseDate(line[0])
91
+ var ppid = parseInt(line[2], 10)
92
+ var pid = parseInt(line[3], 10)
93
+ var kerneltime = Math.round(parseInt(line[1], 10) / 10000)
94
+ var usertime = Math.round(parseInt(line[4], 10) / 10000)
95
+ var memory = parseInt(line[5], 10)
96
+
97
+ var hst = history.get(pid, options.maxage)
98
+ if (hst === undefined) {
99
+ again = true
100
+ hst = { ctime: kerneltime + usertime, uptime: uptime }
101
+ }
102
+
103
+ // process usage since last call
104
+ var total = (kerneltime + usertime - hst.ctime) / 1000
105
+ // time elapsed between calls in seconds
106
+ var seconds = uptime - hst.uptime
107
+ var cpu = seconds > 0 ? (total / seconds) * 100 : 0
108
+
109
+ history.set(pid, { ctime: usertime + kerneltime, uptime: uptime }, options.maxage)
110
+
111
+ statistics[pid] = {
112
+ cpu: cpu,
113
+ memory: memory,
114
+ ppid: ppid,
115
+ pid: pid,
116
+ ctime: usertime + kerneltime,
117
+ elapsed: date - creation.getTime(),
118
+ timestamp: date
119
+ }
120
+ }
121
+
122
+ if (again) {
123
+ return wmic(pids, options, function (err, stats) {
124
+ if (err) return done(err)
125
+ done(null, Object.assign(statistics, stats))
126
+ })
127
+ }
128
+ done(null, statistics)
129
+ })
130
+ }
131
+
132
+ module.exports = wmic
ndcc/lib/pm2-sysmonit/node_modules/pidusage/package.json ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "pidusage",
3
+ "version": "2.0.21",
4
+ "description": "Cross-platform process cpu % and memory usage of a PID",
5
+ "license": "MIT",
6
+ "homepage": "https://github.com/soyuka/pidusage",
7
+ "repository": "github:soyuka/pidusage",
8
+ "bugs": {
9
+ "url": "https://github.com/soyuka/pidusage/issues"
10
+ },
11
+ "author": "soyuka",
12
+ "contributors": [
13
+ "Simone Primarosa <simonepri@outlook.com> (https://simoneprimarosa.com)"
14
+ ],
15
+ "main": "index.js",
16
+ "files": [
17
+ "lib",
18
+ "index.js"
19
+ ],
20
+ "engines": {
21
+ "node": ">=8"
22
+ },
23
+ "scripts": {
24
+ "lint": "standard",
25
+ "test": "nyc ava -m \"!*benchmark*\"",
26
+ "alpine": "docker run -v $(pwd):/var/pidusage pidusage:latest npm test",
27
+ "coverage": "codecov",
28
+ "bench": "ava -m \"*benchmark*\""
29
+ },
30
+ "dependencies": {
31
+ "safe-buffer": "^5.2.1"
32
+ },
33
+ "devDependencies": {
34
+ "ava": "^3.10.1",
35
+ "codecov": "^3.7.0",
36
+ "mockdate": "^2.0.5",
37
+ "mockery": "^2.1.0",
38
+ "nyc": "^15.1.0",
39
+ "pify": "^3.0.0",
40
+ "standard": "^14.3.4",
41
+ "string-to-stream": "^1.1.1",
42
+ "through": "^2.3.8",
43
+ "time-span": "^2.0.0"
44
+ },
45
+ "keywords": [
46
+ "pid",
47
+ "usage",
48
+ "ps",
49
+ "cpu",
50
+ "memory",
51
+ "proc"
52
+ ],
53
+ "ava": {
54
+ "verbose": true
55
+ },
56
+ "nyc": {
57
+ "reporter": [
58
+ "lcovonly",
59
+ "text"
60
+ ]
61
+ }
62
+ }
ndcc/lib/pm2-sysmonit/package.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "pm2-sysmonit",
3
+ "version": "1.2.8",
4
+ "description": "PM2.io System Monitoring",
5
+ "main": "index.js",
6
+ "scripts": {},
7
+ "author": "",
8
+ "license": "Apache",
9
+ "apps": [
10
+ {
11
+ "name": "pm2-sysmonit",
12
+ "script": "./index.js",
13
+ "max_memory_restart": "150M"
14
+ }
15
+ ],
16
+ "dependencies": {
17
+ "async": "^3.2.0",
18
+ "debug": "^4.3.1",
19
+ "pidusage": "^2.0.21",
20
+ "systeminformation": "^5.7",
21
+ "tx2": "~1.0.4"
22
+ }
23
+ }
ndcc/lib/pm2-sysmonit/src/MeanCalc.js ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ class MeanCalc {
3
+ constructor(count) {
4
+ this.metrics = []
5
+ this.count = count
6
+ }
7
+
8
+ inspect() {
9
+ return this.val()
10
+ }
11
+
12
+ add(value) {
13
+ if (this.metrics.length >= this.count) {
14
+ this.metrics.shift()
15
+ }
16
+ this.metrics.push(value)
17
+ }
18
+
19
+ val() {
20
+ if (this.metrics.length == 0) return 0
21
+ let sum = this.metrics.reduce((prev, curr) => curr += prev)
22
+ return Math.floor((sum / this.metrics.length) * 1000) / 1000
23
+ }
24
+ }
25
+
26
+ module.exports = MeanCalc
ndcc/lib/pm2-sysmonit/src/SystemInfos.js ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const sysinfo = require('systeminformation')
3
+ const psList = require('./psList.js')
4
+ const async = require('async')
5
+ const MeanCalc = require('./MeanCalc.js')
6
+ const DEFAULT_CONVERSION = 1024 * 1024
7
+ const os = require('os')
8
+ const fs = require('fs')
9
+ const debug = require('debug')('pm2:sysinfos')
10
+
11
+ class SystemInfo {
12
+ constructor() {
13
+ this.infos = {
14
+ baseboard: {
15
+ model: null,
16
+ version: null
17
+ },
18
+ cpu: {
19
+ manufacturer: null,
20
+ brand: null,
21
+ speedmax: null,
22
+ cores: null,
23
+ physicalCores: null,
24
+ processors: null,
25
+ temperature: null,
26
+ load: null,
27
+ loads: null
28
+ },
29
+ graphics: {
30
+ model: null,
31
+ driverVersion: null,
32
+ memTotal: null,
33
+ memUsed: null,
34
+ temperature: null
35
+ },
36
+ mem: {
37
+ total: null,
38
+ free: null,
39
+ active: null,
40
+ usage: null
41
+ },
42
+ os: {
43
+ platform: null,
44
+ distro: null,
45
+ release: null,
46
+ codename: null,
47
+ kernel: null,
48
+ arch: null,
49
+ },
50
+ fd: {
51
+ opened: null,
52
+ max: null
53
+ },
54
+ storage: {
55
+ io: {
56
+ read: new MeanCalc(15),
57
+ write: new MeanCalc(15)
58
+ },
59
+ physical_disks: [{
60
+ device: null,
61
+ type: null,
62
+ name: null,
63
+ interfaceType: null,
64
+ vendor: null
65
+ }],
66
+ filesystems: [{
67
+ }]
68
+ },
69
+ connections: ['source_ip:source_port-dest_ip:dest_port-proc_name'],
70
+ default_interface: null,
71
+ network: {},
72
+ // Procs
73
+ containers: [],
74
+ processes: {
75
+ cpu_sorted: null,
76
+ mem_sorted: null
77
+ },
78
+ services: {
79
+ running: null,
80
+ stopped: null
81
+ }
82
+ }
83
+ }
84
+
85
+ // Cast MeanCalc and other object to real value
86
+ // This method retrieve the machine snapshot well formated
87
+ report() {
88
+ var report = JSON.parse(JSON.stringify(this.infos))
89
+
90
+ Object.keys(report.network).forEach(iname => {
91
+ report.network[iname] = {
92
+ ip4: this.infos.network[iname].ip4,
93
+ ip6: this.infos.network[iname].ip6,
94
+ tx_5: this.infos.network[iname].tx_5.val(),
95
+ rx_5: this.infos.network[iname].rx_5.val(),
96
+ rx_errors_60: this.infos.network[iname].rx_errors_60.val(),
97
+ tx_errors_60: this.infos.network[iname].tx_errors_60.val(),
98
+ rx_dropped_60: this.infos.network[iname].rx_dropped_60.val(),
99
+ tx_dropped_60: this.infos.network[iname].tx_dropped_60.val()
100
+ }
101
+ })
102
+
103
+ report.storage.io.read = this.infos.storage.io.read.val()
104
+ report.storage.io.write = this.infos.storage.io.write.val()
105
+ return report
106
+ }
107
+
108
+ query(cb) {
109
+ if (this.process.connected == true) {
110
+ try {
111
+ this.process.send('query')
112
+ } catch(e) {
113
+ return cb(new Error('not ready yet'), null)
114
+ }
115
+ }
116
+ else
117
+ return cb(new Error('not ready yet'), null)
118
+
119
+ var res = (msg) => {
120
+ try {
121
+ msg = JSON.parse(msg)
122
+ }
123
+ catch (e) {
124
+ }
125
+
126
+ if (msg.cmd == 'query:res') {
127
+ listener.removeListener('message', res)
128
+ return cb(null, msg.data)
129
+ }
130
+ }
131
+
132
+ var listener = this.process.on('message', res)
133
+ }
134
+
135
+ startCollection() {
136
+ this.staticInformations()
137
+
138
+ var dockerCollection, processCollection, memCollection,
139
+ servicesCollection, graphicsCollection
140
+
141
+ (dockerCollection = () => {
142
+ this.dockerSummary(() => {
143
+ setTimeout(dockerCollection.bind(this), 5000)
144
+ })
145
+ })();
146
+
147
+ (processCollection = () => {
148
+ this.processesSummary(() => {
149
+ setTimeout(processCollection.bind(this), 5000)
150
+ })
151
+ })();
152
+
153
+ (graphicsCollection = () => {
154
+ this.graphicsInformations(() => {
155
+ setTimeout(graphicsCollection.bind(this), 20000)
156
+ })
157
+ })();
158
+
159
+ (servicesCollection = () => {
160
+ this.servicesSummary(() => {
161
+ setTimeout(servicesCollection.bind(this), 60000)
162
+ })
163
+ })();
164
+
165
+ (memCollection = () => {
166
+ this.memStats(() => {
167
+ setTimeout(memCollection.bind(this), 1000)
168
+ })
169
+ })();
170
+
171
+ //this.networkConnectionsWorker()
172
+ this.disksStatsWorker()
173
+ this.networkStatsWorker()
174
+
175
+ this.cpuStatsWorker()
176
+ this.fdStatsWorker()
177
+
178
+ // Systeminfo receive command
179
+ process.on('message', (cmd) => {
180
+ if (cmd == 'query') {
181
+ try {
182
+ var res = JSON.stringify({
183
+ cmd: 'query:res',
184
+ data: this.report()
185
+ })
186
+ process.send(res)
187
+ } catch (e) {
188
+ console.error('Could not retrieve system informations', e)
189
+ }
190
+ }
191
+ else if (cmd == 'pong') {
192
+ clearTimeout(this.ping_timeout)
193
+ }
194
+ })
195
+
196
+ }
197
+
198
+ staticInformations() {
199
+ var getCPU = () => {
200
+ return sysinfo.cpu()
201
+ .then(data => {
202
+ this.infos.cpu = {
203
+ brand: data.manufacturer,
204
+ model: data.brand,
205
+ speed: data.speedmax,
206
+ cores: data.cores,
207
+ physicalCores: data.physicalCores
208
+ }
209
+ })
210
+ }
211
+
212
+ var getBaseboard = () => {
213
+ return sysinfo.system()
214
+ .then(data => {
215
+ this.infos.baseboard = {
216
+ manufacturer: data.manufacturer,
217
+ model: data.model,
218
+ version: data.version
219
+ }
220
+ })
221
+ }
222
+
223
+
224
+ var getDefaultNetInterface = () => {
225
+ return sysinfo.networkInterfaceDefault()
226
+ .then(iface => {
227
+ this.infos.default_interface = iface
228
+ })
229
+ }
230
+
231
+ var getOsInfo = () => {
232
+ return sysinfo.osInfo()
233
+ .then(data => {
234
+ this.infos.os = {
235
+ platform: data.platform,
236
+ distro: data.distro,
237
+ release: data.release,
238
+ codename: data.codename,
239
+ kernel: data.kernel,
240
+ arch: data.arch
241
+ }
242
+ })
243
+ }
244
+
245
+ var diskLayout = () => {
246
+ this.infos.storage.physical_disks = []
247
+
248
+ return sysinfo.diskLayout()
249
+ .then(disks => {
250
+ disks.forEach((disk) => {
251
+ this.infos.storage.physical_disks.push({
252
+ device: disk.device,
253
+ type: disk.type,
254
+ name: disk.name,
255
+ interfaceType: disk.interfaceType,
256
+ vendor: disk.vendor
257
+ })
258
+ })
259
+ })
260
+ }
261
+
262
+ getBaseboard()
263
+ .then(getCPU)
264
+ .then(getOsInfo)
265
+ .then(diskLayout)
266
+ .then(getDefaultNetInterface)
267
+ .catch(e => {
268
+ debug(`Error when trying to retrieve static informations`, e)
269
+ })
270
+ }
271
+
272
+ dockerSummary(cb = () => {}) {
273
+ sysinfo.dockerContainers('all')
274
+ .then(containers => {
275
+ var non_exited_containers = containers.filter(container => container.state != 'exited')
276
+ var new_containers = []
277
+
278
+ async.forEach(non_exited_containers, (container, next) => {
279
+ sysinfo.dockerContainerStats(container.id)
280
+ .then(stats => {
281
+ var meta = container
282
+
283
+ stats[0].cpu_percent = (stats[0].cpu_percent).toFixed(1)
284
+ stats[0].mem_percent = (stats[0].mem_percent).toFixed(1)
285
+ stats[0].netIO.tx = (stats[0].netIO.tx / DEFAULT_CONVERSION).toFixed(1)
286
+ stats[0].netIO.rx = (stats[0].netIO.rx / DEFAULT_CONVERSION).toFixed(1)
287
+
288
+ stats[0].blockIO.w = (stats[0].blockIO.w / DEFAULT_CONVERSION).toFixed(1)
289
+ stats[0].blockIO.r = (stats[0].blockIO.r / DEFAULT_CONVERSION).toFixed(1)
290
+
291
+ meta.stats = Array.isArray(stats) == true ? stats[0] : null
292
+ new_containers.push(meta)
293
+ next()
294
+ })
295
+ .catch(e => {
296
+ debug(e)
297
+ next()
298
+ })
299
+ }, (err) => {
300
+ if (err)
301
+ debug(err)
302
+ this.infos.containers = new_containers.sort((a, b) => {
303
+ var textA = a.name.toUpperCase();
304
+ var textB = b.name.toUpperCase();
305
+ return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
306
+ })
307
+ return cb()
308
+ })
309
+ })
310
+ .catch(e => {
311
+ debug(e)
312
+ return cb()
313
+ })
314
+ }
315
+
316
+ servicesSummary() {
317
+ sysinfo.services('*')
318
+ .then(services => {
319
+ this.infos.services.running = services.filter(service => service.running === true)
320
+ this.infos.services.stopped = services.filter(service => service.running === false)
321
+ })
322
+ .catch(e => {
323
+ debug(e)
324
+ })
325
+ }
326
+
327
+ processesSummary(cb) {
328
+ psList()
329
+ .then(processes => {
330
+ this.infos.processes.cpu_sorted = processes
331
+ .filter(a => !(a.cmd.includes('SystemInfo') && a.cmd.includes('PM2')))
332
+ .sort((a, b) => b.cpu - a.cpu).slice(0, 5)
333
+ this.infos.processes.mem_sorted = processes
334
+ .filter(a => !(a.cmd.includes('SystemInfo') && a.cmd.includes('PM2')))
335
+ .sort((a, b) => b.memory - a.memory).slice(0, 5)
336
+ return cb()
337
+ })
338
+ .catch(e => {
339
+ console.error(`Error when retrieving process list`, e)
340
+ return cb()
341
+ })
342
+ }
343
+
344
+ graphicsInformations(cb) {
345
+ sysinfo.graphics()
346
+ .then(data => {
347
+ if (!data) return cb()
348
+ let cg1 = data.controllers[0]
349
+ if (!cg1) return cb()
350
+
351
+ this.infos.graphics = {
352
+ model: cg1.model,
353
+ driverVersion: cg1.driverVersion,
354
+ memTotal: cg1.memoryTotal,
355
+ memUsed: cg1.memoryUsed,
356
+ temperature: cg1.temperatureGpu
357
+ }
358
+ return cb()
359
+ })
360
+ .catch(e => {
361
+ console.error(`Error while retrieving graphics informations`)
362
+ console.error(e)
363
+ return cb()
364
+ })
365
+ }
366
+
367
+ cpuStatsWorker() {
368
+ var cpuTempCollection, cpuLoad
369
+
370
+ (cpuTempCollection = () => {
371
+ sysinfo.cpuTemperature()
372
+ .then(data => {
373
+ this.infos.cpu.temperature = (data.main).toFixed(1)
374
+ setTimeout(cpuTempCollection.bind(this), 5000)
375
+ })
376
+ .catch(e => {
377
+ setTimeout(cpuTempCollection.bind(this), 5000)
378
+ })
379
+ })();
380
+
381
+ (cpuLoad = () => {
382
+ sysinfo.currentLoad()
383
+ .then(data => {
384
+ this.infos.cpu.load = data.currentLoad.toFixed(1)
385
+ this.infos.cpu.loads = data.cpus.map(cpu => Math.floor(cpu.load)).join('|')
386
+ setTimeout(cpuLoad.bind(this), 1000)
387
+ })
388
+ .catch(e => {
389
+ setTimeout(cpuLoad.bind(this), 1000)
390
+ })
391
+ })();
392
+ }
393
+
394
+ memStats(cb) {
395
+ sysinfo.mem()
396
+ .then(data => {
397
+ this.infos.mem.total = (data.total / DEFAULT_CONVERSION / 1024).toFixed(2)
398
+ this.infos.mem.free = (data.free / DEFAULT_CONVERSION / 1024).toFixed(2)
399
+ this.infos.mem.active = (data.active / DEFAULT_CONVERSION / 1024).toFixed(2)
400
+ this.infos.mem.available = (data.available / DEFAULT_CONVERSION / 1024).toFixed(2)
401
+ this.infos.mem.usage = ((data.active / data.total) * 100).toFixed(1)
402
+ return cb()
403
+ })
404
+ .catch(e => {
405
+ console.error(`Error while retrieving memory info`)
406
+ console.error(e)
407
+ return cb()
408
+ })
409
+ }
410
+
411
+ networkConnectionsWorker() {
412
+ var retrieveConn
413
+
414
+ (retrieveConn = () => {
415
+ sysinfo.networkConnections()
416
+ .then(conns => {
417
+ this.infos.connections = conns
418
+ .filter(conn => conn.localport != '443' && conn.peerport != '443')
419
+ .map(conn => `${conn.localaddress}:${conn.localport}-${conn.peeraddress}:${conn.peerport}-${conn.proc ? conn.proc : 'unknown'}`)
420
+ setTimeout(retrieveConn.bind(this), 10 * 1000)
421
+ })
422
+ .catch(e => {
423
+ console.error(`Error while retrieving filesystems info`)
424
+ console.error(e)
425
+ setTimeout(retrieveConn.bind(this), 10 * 1000)
426
+ })
427
+ })();
428
+ }
429
+
430
+ disksStatsWorker() {
431
+ var rx = 0
432
+ var wx = 0
433
+ var started = false
434
+ var fsSizeCollection, ioCollection
435
+
436
+ (fsSizeCollection = () => {
437
+ sysinfo.fsSize()
438
+ .then(fss => {
439
+ // Get only partition of > 800 and not /boot
440
+ var fse = fss.filter(fs => ((fs.size / (1024 * 1024)) > 800) && fs.mount != '/boot' && !fs.mount.includes('efi'))
441
+ this.infos.storage.filesystems = fse
442
+ setTimeout(fsSizeCollection.bind(this), 30 * 1000)
443
+ })
444
+ .catch(e => {
445
+ console.error(`Error while retrieving filesystem infos (FSSIZE)`, e)
446
+ setTimeout(fsSizeCollection.bind(this), 10 * 1000)
447
+ })
448
+ })();
449
+
450
+ (ioCollection = () => {
451
+ sysinfo.fsStats()
452
+ .then(fs_stats => {
453
+ var new_rx = fs_stats.rx
454
+ var new_wx = fs_stats.wx
455
+
456
+ var read = ((new_rx - rx) / DEFAULT_CONVERSION).toFixed(3)
457
+ var write = ((new_wx - wx) / DEFAULT_CONVERSION).toFixed(3)
458
+
459
+ if (started == true) {
460
+ this.infos.storage.io.read.add(parseFloat(read))
461
+ this.infos.storage.io.write.add(parseFloat(write))
462
+ }
463
+
464
+ rx = new_rx
465
+ wx = new_wx
466
+ started = true
467
+ setTimeout(ioCollection.bind(this), 1000)
468
+ })
469
+ .catch(e => {
470
+ console.error(`Error while getting network statistics`, e)
471
+ setTimeout(ioCollection.bind(this), 1000)
472
+ })
473
+ })();
474
+ }
475
+
476
+ fdStatsWorker() {
477
+ var getFDOpened = () => {
478
+ sysinfo.fsOpenFiles()
479
+ .then(open_files => {
480
+ this.infos.fd.opened = open_files.allocated
481
+ this.infos.fd.max = open_files.max
482
+ })
483
+ .catch(e => {
484
+ console.error(`Could not retrieve fds`)
485
+ console.error(e)
486
+ })
487
+ }
488
+
489
+ setInterval(() => {
490
+ getFDOpened()
491
+ }, 5000)
492
+
493
+ getFDOpened()
494
+ }
495
+
496
+ networkStatsWorker() {
497
+ var latencyCollection, networkStatsCollection
498
+ var self = this
499
+
500
+ function grabStats(inter) {
501
+ let started = false
502
+ let rx = 0
503
+ let tx = 0
504
+ let rx_e = 0
505
+ let tx_e = 0
506
+ let rx_d = 0
507
+ let tx_d = 0
508
+ let net_interface = inter.iface;
509
+
510
+ function networkStatsCollection(net_interface) {
511
+
512
+ self.infos.network[net_interface] = {
513
+ ip4: inter.ip4,
514
+ ip6: inter.ip6,
515
+ latency: new MeanCalc(5),
516
+ tx_5: new MeanCalc(5),
517
+ rx_5: new MeanCalc(5),
518
+ rx_errors_60: new MeanCalc(60),
519
+ tx_errors_60: new MeanCalc(60),
520
+ tx_dropped_60: new MeanCalc(60),
521
+ rx_dropped_60: new MeanCalc(60)
522
+ }
523
+
524
+ sysinfo.networkStats(net_interface)
525
+ .then((net) => {
526
+ let new_rx = (net[0].rx_bytes - rx) / DEFAULT_CONVERSION
527
+ let new_tx = (net[0].tx_bytes - tx) / DEFAULT_CONVERSION
528
+ rx = net[0].rx_bytes
529
+ tx = net[0].tx_bytes
530
+
531
+ let new_rx_e = (net[0].rx_errors - rx_e) / DEFAULT_CONVERSION
532
+ let new_tx_e = (net[0].tx_errors - tx_e) / DEFAULT_CONVERSION
533
+ rx_e = net[0].rx_errors
534
+ tx_e = net[0].tx_errors
535
+
536
+ let new_rx_d = (net[0].rx_dropped - rx_d) / DEFAULT_CONVERSION
537
+ let new_tx_d = (net[0].tx_dropped - tx_d) / DEFAULT_CONVERSION
538
+ rx_d = net[0].rx_dropped
539
+ tx_d = net[0].tx_dropped
540
+
541
+ if (started == true) {
542
+ self.infos.network[net_interface].rx_5.add(new_rx)
543
+ self.infos.network[net_interface].tx_5.add(new_tx)
544
+ self.infos.network[net_interface].rx_errors_60.add(new_rx_e)
545
+ self.infos.network[net_interface].tx_errors_60.add(new_tx_e)
546
+ self.infos.network[net_interface].rx_dropped_60.add(new_rx_d)
547
+ self.infos.network[net_interface].tx_dropped_60.add(new_tx_d)
548
+ }
549
+ started = true
550
+ setTimeout(() => {
551
+ networkStatsCollection(net_interface)
552
+ }, 1000)
553
+ })
554
+ .catch(e => {
555
+ console.error(`Error on retrieving network stats`, e)
556
+ setTimeout(() => {
557
+ networkStatsCollection(net_interface)
558
+ }, 1000)
559
+ })
560
+ }
561
+
562
+ networkStatsCollection(net_interface)
563
+ }
564
+
565
+ sysinfo.networkInterfaces()
566
+ .then(interfaces => {
567
+ interfaces.forEach(inter => {
568
+ if (inter.ip4 == '127.0.0.1') return
569
+ grabStats(inter)
570
+ })
571
+ })
572
+ .catch(e => {
573
+ console.error(`Cannot retrieve interfaces`)
574
+ console.error(e)
575
+ })
576
+
577
+
578
+ // (latencyCollection = () => {
579
+ // sysinfo.inetLatency()
580
+ // .then(latency => {
581
+ // this.infos.network.latency.add(latency)
582
+ // setTimeout(latencyCollection.bind(this), 2000)
583
+ // })
584
+ // .catch(e => {
585
+ // debug(e)
586
+ // setTimeout(latencyCollection.bind(this), 2000)
587
+ // })
588
+ // })()
589
+
590
+
591
+
592
+ }
593
+ }
594
+
595
+ module.exports = SystemInfo
596
+
597
+ if (require.main === module) {
598
+ var sys = new SystemInfo()
599
+ sys.startCollection()
600
+
601
+ setInterval(() => {
602
+ console.log(JSON.stringify(sys.report(), null, 2))
603
+ }, 5000)
604
+ }
ndcc/lib/pm2-sysmonit/src/fastlist.exe ADDED
Binary file (45.1 kB). View file
 
ndcc/lib/pm2-sysmonit/src/pm2.js ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const fs = require('fs')
3
+ const path = require('path')
4
+ const pidusage = require('pidusage')
5
+
6
+ class PM2Monitoring {
7
+ constructor() {
8
+ this.pm2_monitoring = { cpu: 0, mem: 0 }
9
+ this.pm2_agent_monitoring = { cpu: 0, mem: 0 }
10
+ }
11
+
12
+ startCollection() {
13
+ setInterval(() => {
14
+ this.monitorPM2Agent()
15
+ this.monitorPM2()
16
+ }, 900)
17
+ }
18
+
19
+ getDefaultPM2Home() {
20
+ var PM2_ROOT_PATH;
21
+
22
+ if (process.env.PM2_HOME)
23
+ PM2_ROOT_PATH = process.env.PM2_HOME;
24
+ else if (process.env.HOME && !process.env.HOMEPATH)
25
+ PM2_ROOT_PATH = path.resolve(process.env.HOME, '.pm2');
26
+ else if (process.env.HOME || process.env.HOMEPATH)
27
+ PM2_ROOT_PATH = path.resolve(process.env.HOMEDRIVE, process.env.HOME || process.env.HOMEPATH, '.pm2');
28
+ else {
29
+ console.error('[PM2][Initialization] Environment variable HOME (Linux) or HOMEPATH (Windows) are not set!');
30
+ console.error('[PM2][Initialization] Defaulting to /etc/.pm2');
31
+ PM2_ROOT_PATH = path.resolve('/etc', '.pm2');
32
+ }
33
+
34
+ return PM2_ROOT_PATH;
35
+ }
36
+
37
+
38
+ report() {
39
+ return {
40
+ pm2: this.pm2_monitoring,
41
+ agent: this.pm2_agent_monitoring
42
+ }
43
+ }
44
+
45
+ monitorPM2() {
46
+ let pm2_pid_file = path.join(this.getDefaultPM2Home(), 'pm2.pid')
47
+
48
+ fs.readFile(pm2_pid_file, (err, pm2_pid) => {
49
+ if (err) return console.error(`Could not read ${pm2_pid_file}`)
50
+ if (!pm2_pid) return console.error(`PID is null`)
51
+
52
+ pm2_pid = parseInt(pm2_pid)
53
+
54
+ pidusage(pm2_pid, (err, stats) => {
55
+ if (err) return console.error(err)
56
+ this.pm2_monitoring = {
57
+ cpu: stats.cpu.toFixed(1),
58
+ mem: (stats.memory / 1024 / 1024).toFixed(1)
59
+ }
60
+ })
61
+ })
62
+ }
63
+
64
+ monitorPM2Agent() {
65
+ let pm2_agent_pid_file = path.join(this.getDefaultPM2Home(), 'agent.pid')
66
+
67
+ fs.readFile(pm2_agent_pid_file, (err, pm2_agent_pid) => {
68
+ if (err) return
69
+ if (!pm2_agent_pid) return
70
+
71
+ pidusage(pm2_agent_pid, (err, stats) => {
72
+ if (err) return
73
+ this.pm2_agent_monitoring = {
74
+ cpu: stats.cpu.toFixed(1),
75
+ mem: (stats.memory / 1024 / 1024).toFixed(1)
76
+ }
77
+ })
78
+ })
79
+ }
80
+
81
+ }
82
+
83
+ module.exports = PM2Monitoring
ndcc/lib/pm2-sysmonit/src/psList.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const util = require('util');
3
+ const path = require('path');
4
+ const childProcess = require('child_process');
5
+
6
+ const TEN_MEGABYTES = 1000 * 1000 * 10;
7
+ const execFile = util.promisify(childProcess.execFile);
8
+
9
+ const windows = async () => {
10
+ // Source: https://github.com/MarkTiedemann/fastlist
11
+ const bin = path.join(__dirname, 'fastlist.exe');
12
+
13
+ const {stdout} = await execFile(bin, {maxBuffer: TEN_MEGABYTES});
14
+
15
+ return stdout
16
+ .trim()
17
+ .split('\r\n')
18
+ .map(line => line.split('\t'))
19
+ .map(([name, pid, ppid]) => ({
20
+ name,
21
+ pid: Number.parseInt(pid, 10),
22
+ ppid: Number.parseInt(ppid, 10)
23
+ }));
24
+ };
25
+
26
+ const main = async (options = {}) => {
27
+ const flags = (options.all === false ? '' : 'a') + 'wwxo';
28
+ const ret = {};
29
+
30
+ await Promise.all(['comm', 'args', 'ppid', 'uid', '%cpu', '%mem'].map(async cmd => {
31
+ const {stdout} = await execFile('ps', [flags, `pid,${cmd}`], {maxBuffer: TEN_MEGABYTES});
32
+
33
+ for (let line of stdout.trim().split('\n').slice(1)) {
34
+ line = line.trim();
35
+ const [pid] = line.split(' ', 1);
36
+ const val = line.slice(pid.length + 1).trim();
37
+
38
+ if (ret[pid] === undefined) {
39
+ ret[pid] = {};
40
+ }
41
+
42
+ ret[pid][cmd] = val;
43
+ }
44
+ }));
45
+
46
+ // Filter out inconsistencies as there might be race
47
+ // issues due to differences in `ps` between the spawns
48
+ return Object.entries(ret)
49
+ .filter(([, value]) => value.comm && value.args && value.ppid && value.uid && value['%cpu'] && value['%mem'])
50
+ .map(([key, value]) => ({
51
+ pid: Number.parseInt(key, 10),
52
+ name: path.basename(value.comm),
53
+ cmd: value.args,
54
+ ppid: Number.parseInt(value.ppid, 10),
55
+ uid: Number.parseInt(value.uid, 10),
56
+ cpu: Number.parseFloat(value['%cpu']),
57
+ memory: Number.parseFloat(value['%mem'])
58
+ }));
59
+ };
60
+
61
+ module.exports = process.platform === 'win32' ? windows : main;
62
+ // TODO: remove this in the next major version
63
+ module.exports.default = module.exports;
ndcc/lib/sample-apps/http-server/api.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+ var http = require('http');
3
+
4
+ var server = http.createServer(function(req, res) {
5
+ res.writeHead(200);
6
+ res.end('hey');
7
+ }).listen(process.env.PORT || 8000, function() {
8
+ console.log('App listening on port %d', server.address().port);
9
+ });
ndcc/lib/sample-apps/http-server/ecosystem.config.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ apps : [{
3
+ name: 'API',
4
+ script: 'api.js',
5
+ instances: 4,
6
+ max_memory_restart: '1G',
7
+ env: {
8
+ NODE_ENV: 'development'
9
+ },
10
+ env_production: {
11
+ NODE_ENV: 'production'
12
+ }
13
+ }]
14
+ };
ndcc/lib/sample-apps/http-server/package.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "simple-http-server",
3
+ "version": "1.0.0",
4
+ "description": "Simple HTTP server that can be used in cluster mode",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "",
10
+ "license": "ISC"
11
+ }
ndcc/lib/sample-apps/pm2-plus-metrics-actions/custom-metrics.js ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const io = require('@pm2/io')
3
+
4
+ // Straight Metric
5
+ var user_count = 10
6
+
7
+ const users = io.metric({
8
+ name: 'CM: Realtime user',
9
+ value: () => {
10
+ return user_count
11
+ }
12
+ })
13
+
14
+ // or users.set(user_count)
15
+
16
+ // Counter (.inc() .dec())
17
+ const currentReq = io.counter({
18
+ name: 'CM: Current Processing',
19
+ type: 'counter'
20
+ })
21
+
22
+ setInterval(() => {
23
+ currentReq.inc()
24
+ }, 1000)
25
+
26
+ // Meter
27
+ const reqsec = io.meter({
28
+ name: 'CM: req/sec'
29
+ })
30
+
31
+ setInterval(() => {
32
+ reqsec.mark()
33
+ }, 100)
34
+
35
+
36
+ // Histogram
37
+ const latency = io.histogram({
38
+ name: 'CM: latency'
39
+ });
40
+
41
+ var latencyValue = 0;
42
+
43
+ setInterval(() => {
44
+ latencyValue = Math.round(Math.random() * 100);
45
+ latency.update(latencyValue);
46
+ }, 100)
47
+
48
+
49
+ ////////////////////
50
+ // Custom Actions //
51
+ ////////////////////
52
+
53
+ io.action('add user', (done) => {
54
+ user_count++
55
+ done({success:true})
56
+ })
57
+
58
+ io.action('remove user', (done) => {
59
+ user_count++
60
+ done({success:true})
61
+ })
62
+
63
+ io.action('with params', (arg, done) => {
64
+ console.log(arg)
65
+ done({success:arg})
66
+ })
ndcc/lib/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ apps : [{
3
+ name: 'Custom Metrics',
4
+ script: 'custom-metrics.js',
5
+ env: {
6
+ NODE_ENV: 'development'
7
+ },
8
+ env_production: {
9
+ NODE_ENV: 'production'
10
+ }
11
+ }]
12
+ };
ndcc/lib/sample-apps/pm2-plus-metrics-actions/package.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "pm2-plus-custom-metrics",
3
+ "version": "1.0.0",
4
+ "description": "Example that shows how to use pm2+ custom metrics",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "author": "",
10
+ "license": "ISC"
11
+ }
ndcc/lib/sample-apps/python-app/echo.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ import time
3
+
4
+ while 1:
5
+ print("Start : %s" % time.ctime())
6
+ print("second line")
7
+ time.sleep(1)