diff --git a/package-lock.json b/package-lock.json index 85e877e134..bbee0bd547 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1304,7 +1304,6 @@ }, "node_modules/@clack/prompts/node_modules/is-unicode-supported": { "version": "1.3.0", - "extraneous": true, "inBundle": true, "license": "MIT", "engines": { @@ -9933,6 +9932,40 @@ "node": ">=10.2.0" } }, + "node_modules/engine.io-client": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.5.4.tgz", + "integrity": "sha512-GeZeeRjpD2qf49cZQ0Wvh/8NJNfeXkXXcoGh+F77oEAgo9gUHwT1fCRxSNU+YEEaysOJTnsFHmM5oAcPy4ntvQ==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1", + "xmlhttprequest-ssl": "~2.0.0" + } + }, + "node_modules/engine.io-client/node_modules/ws": { + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/engine.io-parser": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", @@ -15468,6 +15501,12 @@ "tslib": "^2.0.3" } }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "license": "MIT" + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -17299,6 +17338,21 @@ } } }, + "node_modules/socket.io-client": { + "version": "4.7.2", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.7.2.tgz", + "integrity": "sha512-vtA0uD4ibrYD793SOIAwlo8cj6haOeMHrGvwPxJsxH7CeIksqJ+3Zc06RvWTIFgiSqx4A3sOnTXpfAEE2Zyz6w==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/socket.io-parser": { "version": "4.2.6", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz", @@ -19190,6 +19244,14 @@ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "license": "MIT" }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", + "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", @@ -20194,7 +20256,9 @@ "license": "Apache-2.0", "dependencies": { "@heyputer/kv.js": "^0.2.1", - "open": "^10.2.0" + "open": "^10.2.0", + "path-browserify": "1.0.1", + "socket.io-client": "4.7.2" }, "devDependencies": { "@playwright/test": "^1.49.0", diff --git a/src/puter-js/package.json b/src/puter-js/package.json index d0661464b3..f6a377d86e 100644 --- a/src/puter-js/package.json +++ b/src/puter-js/package.json @@ -51,6 +51,8 @@ }, "dependencies": { "@heyputer/kv.js": "^0.2.1", - "open": "^10.2.0" + "open": "^10.2.0", + "path-browserify": "1.0.1", + "socket.io-client": "4.7.2" } } diff --git a/src/puter-js/src/index.js b/src/puter-js/src/index.js index b240b9bbee..4af1f3da01 100644 --- a/src/puter-js/src/index.js +++ b/src/puter-js/src/index.js @@ -2,7 +2,7 @@ import kvjs from '@heyputer/kv.js'; import APICallLogger from './lib/APICallLogger.js'; import { fetchUrl } from './lib/networkUtils.js'; import { isStoredTokenUsableForOrigin } from './lib/authTokenOrigin.js'; -import path from './lib/path.js'; +import path from 'path-browserify'; import localStorageMemory from './lib/polyfills/localStorage.js'; import xhrshim from './lib/polyfills/xhrshim.js'; import * as utils from './lib/utils.js'; @@ -1665,7 +1665,6 @@ globalThis.addEventListener && '*', ); } else if (event.data.msg === 'puter.token') { - // puterDialog.close(); // Set the authToken property puter.setAuthToken(event.data.token); // update appID only when token does not include app identity @@ -1678,12 +1677,8 @@ globalThis.addEventListener && puter.setAppID(fallbackAppID); } } - // Remove the event listener to avoid memory leaks - // window.removeEventListener('message', messageListener); puter.puterAuthState.authGranted = true; - // Resolve the promise - // resolve(); // Call onAuth callback if (puter.onAuth && typeof puter.onAuth === 'function') { diff --git a/src/puter-js/src/lib/RequestError.js b/src/puter-js/src/lib/RequestError.js deleted file mode 100644 index 5c295a1ea8..0000000000 --- a/src/puter-js/src/lib/RequestError.js +++ /dev/null @@ -1,6 +0,0 @@ -export class RequestError extends Error { - constructor (message) { - super(message); - this.name = 'RequestError'; // thanks minifier - } -} diff --git a/src/puter-js/src/lib/path.js b/src/puter-js/src/lib/path.js deleted file mode 100644 index b62d1859a4..0000000000 --- a/src/puter-js/src/lib/path.js +++ /dev/null @@ -1,568 +0,0 @@ -// import {cwd} from './env.js' -let cwd; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -//'use strict'; - -const - CHAR_UPPERCASE_A = 65, - CHAR_LOWERCASE_A = 97, - CHAR_UPPERCASE_Z = 90, - CHAR_LOWERCASE_Z = 122, - CHAR_DOT = 46, - CHAR_FORWARD_SLASH = 47, - CHAR_BACKWARD_SLASH = 92, - CHAR_COLON = 58, - CHAR_QUESTION_MARK = 63; - -function isPathSeparator (code) { - return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; -} - -function isPosixPathSeparator (code) { - return code === CHAR_FORWARD_SLASH; -} - -// Resolves . and .. elements in a path with directory names -function normalizeString (path, allowAboveRoot, separator, isPathSeparator) { - let res = ''; - let lastSegmentLength = 0; - let lastSlash = -1; - let dots = 0; - let code = 0; - for ( let i = 0; i <= path.length; ++i ) { - if ( i < path.length ) - { - code = path.charCodeAt(i); - } - else if ( isPathSeparator(code) ) - { - break; - } - else - { - code = CHAR_FORWARD_SLASH; - } - - if ( isPathSeparator(code) ) { - if ( lastSlash === i - 1 || dots === 1 ) { - // NOOP - } else if ( dots === 2 ) { - if ( res.length < 2 || lastSegmentLength !== 2 || - res.charCodeAt(res.length - 1) !== CHAR_DOT || - res.charCodeAt(res.length - 2) !== CHAR_DOT ) { - if ( res.length > 2 ) { - const lastSlashIndex = res.lastIndexOf(separator); - if ( lastSlashIndex === -1 ) { - res = ''; - lastSegmentLength = 0; - } else { - res = res.slice(0, lastSlashIndex); - lastSegmentLength = - res.length - 1 - res.lastIndexOf(res, separator); - } - lastSlash = i; - dots = 0; - continue; - } else if ( res.length !== 0 ) { - res = ''; - lastSegmentLength = 0; - lastSlash = i; - dots = 0; - continue; - } - } - if ( allowAboveRoot ) { - res += res.length > 0 ? `${separator}..` : '..'; - lastSegmentLength = 2; - } - } else { - if ( res.length > 0 ) - { - res += `${separator}${path.slice(lastSlash + 1, i)}`; - } - else - { - res = path.slice(lastSlash + 1, i); - } - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i; - dots = 0; - } else if ( code === CHAR_DOT && dots !== -1 ) { - ++dots; - } else { - dots = -1; - } - } - return res; -} - -const path = { - // path.resolve([from ...], to) - resolve (...args) { - let resolvedPath = ''; - let resolvedAbsolute = false; - - for ( let i = args.length - 1; i >= -1 && !resolvedAbsolute; i-- ) { - // orig const path = i >= 0 ? args[i] : posixCwd(); - const path = i >= 0 ? args[i] : (cwd !== undefined ? cwd : '/'); - // const path = i >= 0 ? args[i] : '/'; - - // Skip empty entries - if ( path.length === 0 ) { - continue; - } - - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = - path.charCodeAt(0) === CHAR_FORWARD_SLASH; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); - - if ( resolvedAbsolute ) { - return `/${resolvedPath}`; - } - return resolvedPath.length > 0 ? resolvedPath : '.'; - }, - - normalize (path) { - if ( path.length === 0 ) - { - return '.'; - } - - const isAbsolute = - path.charCodeAt(0) === CHAR_FORWARD_SLASH; - const trailingSeparator = - path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; - - // Normalize the path - path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator); - - if ( path.length === 0 ) { - if ( isAbsolute ) - { - return '/'; - } - return trailingSeparator ? './' : '.'; - } - if ( trailingSeparator ) - { - path += '/'; - } - - return isAbsolute ? `/${path}` : path; - }, - - isAbsolute (path) { - return path.length > 0 && - path.charCodeAt(0) === CHAR_FORWARD_SLASH; - }, - - join (...args) { - if ( args.length === 0 ) - { - return '.'; - } - let joined; - for ( let i = 0; i < args.length; ++i ) { - const arg = args[i]; - if ( arg.length > 0 ) { - if ( joined === undefined ) - { - joined = arg; - } - else - { - joined += `/${arg}`; - } - } - } - if ( joined === undefined ) - { - return '.'; - } - return path.normalize(joined); - }, - - relative (from, to) { - if ( from === to ) - { - return ''; - } - - // Trim leading forward slashes. - from = path.resolve(from); - to = path.resolve(to); - - if ( from === to ) - { - return ''; - } - - const fromStart = 1; - const fromEnd = from.length; - const fromLen = fromEnd - fromStart; - const toStart = 1; - const toLen = to.length - toStart; - - // Compare paths to find the longest common path from root - const length = (fromLen < toLen ? fromLen : toLen); - let lastCommonSep = -1; - let i = 0; - for ( ; i < length; i++ ) { - const fromCode = from.charCodeAt(fromStart + i); - if ( fromCode !== to.charCodeAt(toStart + i) ) - { - break; - } - else if ( fromCode === CHAR_FORWARD_SLASH ) - { - lastCommonSep = i; - } - } - if ( i === length ) { - if ( toLen > length ) { - if ( to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH ) { - // We get here if `from` is the exact base path for `to`. - // For example: from='/foo/bar'; to='/foo/bar/baz' - return to.slice(toStart + i + 1); - } - if ( i === 0 ) { - // We get here if `from` is the root - // For example: from='/'; to='/foo' - return to.slice(toStart + i); - } - } else if ( fromLen > length ) { - if ( from.charCodeAt(fromStart + i) === - CHAR_FORWARD_SLASH ) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; - } else if ( i === 0 ) { - // We get here if `to` is the root. - // For example: from='/foo/bar'; to='/' - lastCommonSep = 0; - } - } - } - - let out = ''; - // Generate the relative path based on the path difference between `to` - // and `from`. - for ( i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i ) { - if ( i === fromEnd || - from.charCodeAt(i) === CHAR_FORWARD_SLASH ) { - out += out.length === 0 ? '..' : '/..'; - } - } - - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts. - return `${out}${to.slice(toStart + lastCommonSep)}`; - }, - - toNamespacedPath (path) { - // Non-op on posix systems - return path; - }, - - dirname (path) { - if ( path.length === 0 ) - { - return '.'; - } - const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let end = -1; - let matchedSlash = true; - for ( let i = path.length - 1; i >= 1; --i ) { - if ( path.charCodeAt(i) === CHAR_FORWARD_SLASH ) { - if ( ! matchedSlash ) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; - } - } - - if ( end === -1 ) - { - return hasRoot ? '/' : '.'; - } - if ( hasRoot && end === 1 ) - { - return '//'; - } - return path.slice(0, end); - }, - - basename (path, ext) { - let start = 0; - let end = -1; - let matchedSlash = true; - - if ( ext !== undefined && ext.length > 0 && ext.length <= path.length ) { - if ( ext === path ) - { - return ''; - } - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for ( let i = path.length - 1; i >= 0; --i ) { - const code = path.charCodeAt(i); - if ( code === CHAR_FORWARD_SLASH ) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if ( ! matchedSlash ) { - start = i + 1; - break; - } - } else { - if ( firstNonSlashEnd === -1 ) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if ( extIdx >= 0 ) { - // Try to match the explicit extension - if ( code === ext.charCodeAt(extIdx) ) { - if ( --extIdx === -1 ) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - - if ( start === end ) - { - end = firstNonSlashEnd; - } - else if ( end === -1 ) - { - end = path.length; - } - return path.slice(start, end); - } - for ( let i = path.length - 1; i >= 0; --i ) { - if ( path.charCodeAt(i) === CHAR_FORWARD_SLASH ) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if ( ! matchedSlash ) { - start = i + 1; - break; - } - } else if ( end === -1 ) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - - if ( end === -1 ) - { - return ''; - } - return path.slice(start, end); - }, - - extname (path) { - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - for ( let i = path.length - 1; i >= 0; --i ) { - const code = path.charCodeAt(i); - if ( code === CHAR_FORWARD_SLASH ) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if ( ! matchedSlash ) { - startPart = i + 1; - break; - } - continue; - } - if ( end === -1 ) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if ( code === CHAR_DOT ) { - // If this is our first dot, mark it as the start of our extension - if ( startDot === -1 ) - { - startDot = i; - } - else if ( preDotState !== 1 ) - { - preDotState = 1; - } - } else if ( startDot !== -1 ) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1) ) { - return ''; - } - return path.slice(startDot, end); - }, - - format: _format.bind(null, '/'), - - parse (path) { - const ret = { root: '', dir: '', base: '', ext: '', name: '' }; - if ( path.length === 0 ) - { - return ret; - } - const isAbsolute = - path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let start; - if ( isAbsolute ) { - ret.root = '/'; - start = 1; - } else { - start = 0; - } - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Get non-dir info - for ( ; i >= start; --i ) { - const code = path.charCodeAt(i); - if ( code === CHAR_FORWARD_SLASH ) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if ( ! matchedSlash ) { - startPart = i + 1; - break; - } - continue; - } - if ( end === -1 ) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if ( code === CHAR_DOT ) { - // If this is our first dot, mark it as the start of our extension - if ( startDot === -1 ) - { - startDot = i; - } - else if ( preDotState !== 1 ) - { - preDotState = 1; - } - } else if ( startDot !== -1 ) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( end !== -1 ) { - const start = startPart === 0 && isAbsolute ? 1 : startPart; - if ( startDot === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && - startDot === end - 1 && - startDot === startPart + 1) ) { - ret.base = ret.name = path.slice(start, end); - } else { - ret.name = path.slice(start, startDot); - ret.base = path.slice(start, end); - ret.ext = path.slice(startDot, end); - } - } - - if ( startPart > 0 ) - { - ret.dir = path.slice(0, startPart - 1); - } - else if ( isAbsolute ) - { - ret.dir = '/'; - } - - return ret; - }, - - sep: '/', - delimiter: ':', - win32: null, - posix: null, -}; - -function _format (sep, pathObject) { - validateObject(pathObject, 'pathObject'); - const dir = pathObject.dir || pathObject.root; - const base = pathObject.base || - `${pathObject.name || ''}${pathObject.ext || ''}`; - if ( ! dir ) { - return base; - } - return dir === pathObject.root ? `${dir}${base}` : `${dir}${sep}${base}`; -} - -export default path; \ No newline at end of file diff --git a/src/puter-js/src/lib/socket.io/socket.io.esm.min.js b/src/puter-js/src/lib/socket.io/socket.io.esm.min.js deleted file mode 100644 index 4cdde60574..0000000000 --- a/src/puter-js/src/lib/socket.io/socket.io.esm.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Socket.IO v4.7.2 - * (c) 2014-2023 Guillermo Rauch - * Released under the MIT License. - */ -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>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 v(t){return t.reduce(((t,e)=>t+e.length),0)}function w(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let n=0;for(let i=0;i(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(""),N=64,S={};let x,L=0,q=0;function P(t){let e="";do{e=B[t%N]+e,t=Math.floor(t/N)}while(t>0);return e}function j(){const t=P(+new Date);return t!==x?(L=0,x=t):t+"."+P(L++)}for(;q{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{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(v(n)<1)break;const t=w(n,1);o=128==(128&t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(v(n)<2)break;const t=w(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(v(n)<8)break;const t=w(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(v(n)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{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{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{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{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=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"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=0&&t.num{delete this.acks[t];for(let e=0;e{this.io.clearTimeoutFn(i),e.apply(this,[null,...t])}}emitWithAck(t,...e){const s=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,i)=>{e.push(((t,e)=>s?t?i(t):n(e):n(t))),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)}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&&(e.apply(this,t.data),delete this.acks[t.id])}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;s0&&t.jitter<=1?t.jitter:0,this.attempts=0}vt.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)},vt.prototype.reset=function(){this.attempts=0},vt.prototype.setMin=function(t){this.ms=t},vt.prototype.setMax=function(t){this.max=t},vt.prototype.setJitter=function(t){this.jitter=t};class wt 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 vt({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;st())),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 wt(n,e):(kt[i]||(kt[i]=new wt(n,e)),a=kt[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(_t,{Manager:wt,Socket:bt,io:_t,connect:_t});export{wt as Manager,bt as Socket,_t as connect,_t as default,_t as io,ut as protocol}; -//# sourceMappingURL=socket.io.esm.min.js.map diff --git a/src/puter-js/src/lib/socket.io/socket.io.js b/src/puter-js/src/lib/socket.io/socket.io.js deleted file mode 100644 index 5a92745c23..0000000000 --- a/src/puter-js/src/lib/socket.io/socket.io.js +++ /dev/null @@ -1,4385 +0,0 @@ -/*! - * Socket.IO v4.7.2 - * (c) 2014-2023 Guillermo Rauch - * Released under the MIT License. - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.io = factory()); -})(this, (function () { 'use strict'; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { - return typeof obj; - } : function (obj) { - return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }, _typeof(obj); - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - Object.defineProperty(Constructor, "prototype", { - writable: false - }); - return Constructor; - } - function _extends() { - _extends = Object.assign ? Object.assign.bind() : function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - return target; - }; - return _extends.apply(this, arguments); - } - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - Object.defineProperty(subClass, "prototype", { - writable: false - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - return _setPrototypeOf(o, p); - } - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } - } - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct.bind(); - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - return _construct.apply(null, arguments); - } - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - _cache.set(Class, Wrapper); - } - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - return _wrapNativeSuper(Class); - } - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - return self; - } - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - return _assertThisInitialized(self); - } - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = _getPrototypeOf(object); - if (object === null) break; - } - return object; - } - function _get() { - if (typeof Reflect !== "undefined" && Reflect.get) { - _get = Reflect.get.bind(); - } else { - _get = function _get(target, property, receiver) { - var base = _superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - if (desc.get) { - return desc.get.call(arguments.length < 3 ? target : receiver); - } - return desc.value; - }; - } - return _get.apply(this, arguments); - } - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; - } - function _createForOfIteratorHelper(o, allowArrayLike) { - var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; - if (!it) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - var F = function () {}; - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = it.call(o); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; - } - function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== undefined) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); - } - function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); - } - - var PACKET_TYPES = Object.create(null); // no Map = no polyfill - PACKET_TYPES["open"] = "0"; - PACKET_TYPES["close"] = "1"; - PACKET_TYPES["ping"] = "2"; - PACKET_TYPES["pong"] = "3"; - PACKET_TYPES["message"] = "4"; - PACKET_TYPES["upgrade"] = "5"; - PACKET_TYPES["noop"] = "6"; - var PACKET_TYPES_REVERSE = Object.create(null); - Object.keys(PACKET_TYPES).forEach(function (key) { - PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key; - }); - var ERROR_PACKET = { - type: "error", - data: "parser error" - }; - - var withNativeBlob$1 = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]"; - var withNativeArrayBuffer$2 = typeof ArrayBuffer === "function"; - // ArrayBuffer.isView method is not defined in IE10 - var isView$1 = function isView(obj) { - return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer; - }; - var encodePacket = function encodePacket(_ref, supportsBinary, callback) { - var type = _ref.type, - data = _ref.data; - if (withNativeBlob$1 && data instanceof Blob) { - if (supportsBinary) { - return callback(data); - } else { - return encodeBlobAsBase64(data, callback); - } - } else if (withNativeArrayBuffer$2 && (data instanceof ArrayBuffer || isView$1(data))) { - if (supportsBinary) { - return callback(data); - } else { - return encodeBlobAsBase64(new Blob([data]), callback); - } - } - // plain string - return callback(PACKET_TYPES[type] + (data || "")); - }; - var encodeBlobAsBase64 = function encodeBlobAsBase64(data, callback) { - var fileReader = new FileReader(); - fileReader.onload = function () { - var content = fileReader.result.split(",")[1]; - callback("b" + (content || "")); - }; - return fileReader.readAsDataURL(data); - }; - function toArray(data) { - if (data instanceof Uint8Array) { - return data; - } else if (data instanceof ArrayBuffer) { - return new Uint8Array(data); - } else { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength); - } - } - var TEXT_ENCODER; - function encodePacketToBinary(packet, callback) { - if (withNativeBlob$1 && packet.data instanceof Blob) { - return packet.data.arrayBuffer().then(toArray).then(callback); - } else if (withNativeArrayBuffer$2 && (packet.data instanceof ArrayBuffer || isView$1(packet.data))) { - return callback(toArray(packet.data)); - } - encodePacket(packet, false, function (encoded) { - if (!TEXT_ENCODER) { - TEXT_ENCODER = new TextEncoder(); - } - callback(TEXT_ENCODER.encode(encoded)); - }); - } - - // imported from https://github.com/socketio/base64-arraybuffer - var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - // Use a lookup table to find the index. - var lookup$1 = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256); - for (var i$1 = 0; i$1 < chars.length; i$1++) { - lookup$1[chars.charCodeAt(i$1)] = i$1; - } - var decode$1 = function decode(base64) { - var bufferLength = base64.length * 0.75, - len = base64.length, - i, - p = 0, - encoded1, - encoded2, - encoded3, - encoded4; - if (base64[base64.length - 1] === '=') { - bufferLength--; - if (base64[base64.length - 2] === '=') { - bufferLength--; - } - } - var arraybuffer = new ArrayBuffer(bufferLength), - bytes = new Uint8Array(arraybuffer); - for (i = 0; i < len; i += 4) { - encoded1 = lookup$1[base64.charCodeAt(i)]; - encoded2 = lookup$1[base64.charCodeAt(i + 1)]; - encoded3 = lookup$1[base64.charCodeAt(i + 2)]; - encoded4 = lookup$1[base64.charCodeAt(i + 3)]; - bytes[p++] = encoded1 << 2 | encoded2 >> 4; - bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; - bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; - } - return arraybuffer; - }; - - var withNativeArrayBuffer$1 = typeof ArrayBuffer === "function"; - var decodePacket = function decodePacket(encodedPacket, binaryType) { - if (typeof encodedPacket !== "string") { - return { - type: "message", - data: mapBinary(encodedPacket, binaryType) - }; - } - var type = encodedPacket.charAt(0); - if (type === "b") { - return { - type: "message", - data: decodeBase64Packet(encodedPacket.substring(1), binaryType) - }; - } - var packetType = PACKET_TYPES_REVERSE[type]; - if (!packetType) { - return ERROR_PACKET; - } - return encodedPacket.length > 1 ? { - type: PACKET_TYPES_REVERSE[type], - data: encodedPacket.substring(1) - } : { - type: PACKET_TYPES_REVERSE[type] - }; - }; - var decodeBase64Packet = function decodeBase64Packet(data, binaryType) { - if (withNativeArrayBuffer$1) { - var decoded = decode$1(data); - return mapBinary(decoded, binaryType); - } else { - return { - base64: true, - data: data - }; // fallback for old browsers - } - }; - - var mapBinary = function mapBinary(data, binaryType) { - switch (binaryType) { - case "blob": - if (data instanceof Blob) { - // from WebSocket + binaryType "blob" - return data; - } else { - // from HTTP long-polling or WebTransport - return new Blob([data]); - } - case "arraybuffer": - default: - if (data instanceof ArrayBuffer) { - // from HTTP long-polling (base64) or WebSocket + binaryType "arraybuffer" - return data; - } else { - // from WebTransport (Uint8Array) - return data.buffer; - } - } - }; - - var SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text - var encodePayload = function encodePayload(packets, callback) { - // some packets may be added to the array while encoding, so the initial length must be saved - var length = packets.length; - var encodedPackets = new Array(length); - var count = 0; - packets.forEach(function (packet, i) { - // force base64 encoding for binary packets - encodePacket(packet, false, function (encodedPacket) { - encodedPackets[i] = encodedPacket; - if (++count === length) { - callback(encodedPackets.join(SEPARATOR)); - } - }); - }); - }; - var decodePayload = function decodePayload(encodedPayload, binaryType) { - var encodedPackets = encodedPayload.split(SEPARATOR); - var packets = []; - for (var i = 0; i < encodedPackets.length; i++) { - var decodedPacket = decodePacket(encodedPackets[i], binaryType); - packets.push(decodedPacket); - if (decodedPacket.type === "error") { - break; - } - } - return packets; - }; - function createPacketEncoderStream() { - return new TransformStream({ - transform: function transform(packet, controller) { - encodePacketToBinary(packet, function (encodedPacket) { - var payloadLength = encodedPacket.length; - var header; - // inspired by the WebSocket format: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#decoding_payload_length - if (payloadLength < 126) { - header = new Uint8Array(1); - new DataView(header.buffer).setUint8(0, payloadLength); - } else if (payloadLength < 65536) { - header = new Uint8Array(3); - var view = new DataView(header.buffer); - view.setUint8(0, 126); - view.setUint16(1, payloadLength); - } else { - header = new Uint8Array(9); - var _view = new DataView(header.buffer); - _view.setUint8(0, 127); - _view.setBigUint64(1, BigInt(payloadLength)); - } - // first bit indicates whether the payload is plain text (0) or binary (1) - if (packet.data && typeof packet.data !== "string") { - header[0] |= 0x80; - } - controller.enqueue(header); - controller.enqueue(encodedPacket); - }); - } - }); - } - var TEXT_DECODER; - function totalLength(chunks) { - return chunks.reduce(function (acc, chunk) { - return acc + chunk.length; - }, 0); - } - function concatChunks(chunks, size) { - if (chunks[0].length === size) { - return chunks.shift(); - } - var buffer = new Uint8Array(size); - var j = 0; - for (var i = 0; i < size; i++) { - buffer[i] = chunks[0][j++]; - if (j === chunks[0].length) { - chunks.shift(); - j = 0; - } - } - if (chunks.length && j < chunks[0].length) { - chunks[0] = chunks[0].slice(j); - } - return buffer; - } - function createPacketDecoderStream(maxPayload, binaryType) { - if (!TEXT_DECODER) { - TEXT_DECODER = new TextDecoder(); - } - var chunks = []; - var state = 0 /* READ_HEADER */; - var expectedLength = -1; - var isBinary = false; - return new TransformStream({ - transform: function transform(chunk, controller) { - chunks.push(chunk); - while (true) { - if (state === 0 /* READ_HEADER */) { - if (totalLength(chunks) < 1) { - break; - } - var header = concatChunks(chunks, 1); - isBinary = (header[0] & 0x80) === 0x80; - expectedLength = header[0] & 0x7f; - if (expectedLength < 126) { - state = 3 /* READ_PAYLOAD */; - } else if (expectedLength === 126) { - state = 1 /* READ_EXTENDED_LENGTH_16 */; - } else { - state = 2 /* READ_EXTENDED_LENGTH_64 */; - } - } else if (state === 1 /* READ_EXTENDED_LENGTH_16 */) { - if (totalLength(chunks) < 2) { - break; - } - var headerArray = concatChunks(chunks, 2); - expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0); - state = 3 /* READ_PAYLOAD */; - } else if (state === 2 /* READ_EXTENDED_LENGTH_64 */) { - if (totalLength(chunks) < 8) { - break; - } - var _headerArray = concatChunks(chunks, 8); - var view = new DataView(_headerArray.buffer, _headerArray.byteOffset, _headerArray.length); - var n = view.getUint32(0); - if (n > Math.pow(2, 53 - 32) - 1) { - // the maximum safe integer in JavaScript is 2^53 - 1 - controller.enqueue(ERROR_PACKET); - break; - } - expectedLength = n * Math.pow(2, 32) + view.getUint32(4); - state = 3 /* READ_PAYLOAD */; - } else { - if (totalLength(chunks) < expectedLength) { - break; - } - var data = concatChunks(chunks, expectedLength); - controller.enqueue(decodePacket(isBinary ? data : TEXT_DECODER.decode(data), binaryType)); - state = 0 /* READ_HEADER */; - } - - if (expectedLength === 0 || expectedLength > maxPayload) { - controller.enqueue(ERROR_PACKET); - break; - } - } - } - }); - } - var protocol$1 = 4; - - /** - * Initialize a new `Emitter`. - * - * @api public - */ - - function Emitter(obj) { - if (obj) return mixin(obj); - } - - /** - * Mixin the emitter properties. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - - function mixin(obj) { - for (var key in Emitter.prototype) { - obj[key] = Emitter.prototype[key]; - } - return obj; - } - - /** - * Listen on the given `event` with `fn`. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) { - this._callbacks = this._callbacks || {}; - (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn); - return this; - }; - - /** - * Adds an `event` listener that will be invoked a single - * time then automatically removed. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.once = function (event, fn) { - function on() { - this.off(event, on); - fn.apply(this, arguments); - } - on.fn = fn; - this.on(event, on); - return this; - }; - - /** - * Remove the given callback for `event` or all - * registered callbacks. - * - * @param {String} event - * @param {Function} fn - * @return {Emitter} - * @api public - */ - - Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) { - this._callbacks = this._callbacks || {}; - - // all - if (0 == arguments.length) { - this._callbacks = {}; - return this; - } - - // specific event - var callbacks = this._callbacks['$' + event]; - if (!callbacks) return this; - - // remove all handlers - if (1 == arguments.length) { - delete this._callbacks['$' + event]; - return this; - } - - // remove specific handler - var cb; - for (var i = 0; i < callbacks.length; i++) { - cb = callbacks[i]; - if (cb === fn || cb.fn === fn) { - callbacks.splice(i, 1); - break; - } - } - - // Remove event specific arrays for event types that no - // one is subscribed for to avoid memory leak. - if (callbacks.length === 0) { - delete this._callbacks['$' + event]; - } - return this; - }; - - /** - * Emit `event` with the given args. - * - * @param {String} event - * @param {Mixed} ... - * @return {Emitter} - */ - - Emitter.prototype.emit = function (event) { - this._callbacks = this._callbacks || {}; - var args = new Array(arguments.length - 1), - callbacks = this._callbacks['$' + event]; - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - if (callbacks) { - callbacks = callbacks.slice(0); - for (var i = 0, len = callbacks.length; i < len; ++i) { - callbacks[i].apply(this, args); - } - } - return this; - }; - - // alias used for reserved events (protected method) - Emitter.prototype.emitReserved = Emitter.prototype.emit; - - /** - * Return array of callbacks for `event`. - * - * @param {String} event - * @return {Array} - * @api public - */ - - Emitter.prototype.listeners = function (event) { - this._callbacks = this._callbacks || {}; - return this._callbacks['$' + event] || []; - }; - - /** - * Check if this emitter has `event` handlers. - * - * @param {String} event - * @return {Boolean} - * @api public - */ - - Emitter.prototype.hasListeners = function (event) { - return !!this.listeners(event).length; - }; - - var globalThisShim = function () { - if (typeof self !== "undefined") { - return self; - } else if (typeof window !== "undefined") { - return window; - } else { - return Function("return this")(); - } - }(); - - function pick(obj) { - for (var _len = arguments.length, attr = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - attr[_key - 1] = arguments[_key]; - } - return attr.reduce(function (acc, k) { - if (obj.hasOwnProperty(k)) { - acc[k] = obj[k]; - } - return acc; - }, {}); - } - // Keep a reference to the real timeout functions so they can be used when overridden - var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout; - var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout; - function installTimerFunctions(obj, opts) { - if (opts.useNativeTimers) { - obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim); - obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim); - } else { - obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim); - obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim); - } - } - // base64 encoded buffers are about 33% bigger (https://en.wikipedia.org/wiki/Base64) - var BASE64_OVERHEAD = 1.33; - // we could also have used `new Blob([obj]).size`, but it isn't supported in IE9 - function byteLength(obj) { - if (typeof obj === "string") { - return utf8Length(obj); - } - // arraybuffer or blob - return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD); - } - function utf8Length(str) { - var c = 0, - length = 0; - for (var i = 0, l = str.length; i < l; i++) { - c = str.charCodeAt(i); - if (c < 0x80) { - length += 1; - } else if (c < 0x800) { - length += 2; - } else if (c < 0xd800 || c >= 0xe000) { - length += 3; - } else { - i++; - length += 4; - } - } - return length; - } - - // imported from https://github.com/galkn/querystring - /** - * Compiles a querystring - * Returns string representation of the object - * - * @param {Object} - * @api private - */ - function encode$1(obj) { - var str = ''; - for (var i in obj) { - if (obj.hasOwnProperty(i)) { - if (str.length) str += '&'; - str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); - } - } - return str; - } - /** - * Parses a simple querystring into an object - * - * @param {String} qs - * @api private - */ - function decode(qs) { - var qry = {}; - var pairs = qs.split('&'); - for (var i = 0, l = pairs.length; i < l; i++) { - var pair = pairs[i].split('='); - qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); - } - return qry; - } - - var TransportError = /*#__PURE__*/function (_Error) { - _inherits(TransportError, _Error); - var _super = _createSuper(TransportError); - function TransportError(reason, description, context) { - var _this; - _classCallCheck(this, TransportError); - _this = _super.call(this, reason); - _this.description = description; - _this.context = context; - _this.type = "TransportError"; - return _this; - } - return _createClass(TransportError); - }( /*#__PURE__*/_wrapNativeSuper(Error)); - var Transport = /*#__PURE__*/function (_Emitter) { - _inherits(Transport, _Emitter); - var _super2 = _createSuper(Transport); - /** - * Transport abstract constructor. - * - * @param {Object} opts - options - * @protected - */ - function Transport(opts) { - var _this2; - _classCallCheck(this, Transport); - _this2 = _super2.call(this); - _this2.writable = false; - installTimerFunctions(_assertThisInitialized(_this2), opts); - _this2.opts = opts; - _this2.query = opts.query; - _this2.socket = opts.socket; - return _this2; - } - /** - * Emits an error. - * - * @param {String} reason - * @param description - * @param context - the error context - * @return {Transport} for chaining - * @protected - */ - _createClass(Transport, [{ - key: "onError", - value: function onError(reason, description, context) { - _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "error", new TransportError(reason, description, context)); - return this; - } - /** - * Opens the transport. - */ - }, { - key: "open", - value: function open() { - this.readyState = "opening"; - this.doOpen(); - return this; - } - /** - * Closes the transport. - */ - }, { - key: "close", - value: function close() { - if (this.readyState === "opening" || this.readyState === "open") { - this.doClose(); - this.onClose(); - } - return this; - } - /** - * Sends multiple packets. - * - * @param {Array} packets - */ - }, { - key: "send", - value: function send(packets) { - if (this.readyState === "open") { - this.write(packets); - } - } - /** - * Called upon open - * - * @protected - */ - }, { - key: "onOpen", - value: function onOpen() { - this.readyState = "open"; - this.writable = true; - _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "open"); - } - /** - * Called with data. - * - * @param {String} data - * @protected - */ - }, { - key: "onData", - value: function onData(data) { - var packet = decodePacket(data, this.socket.binaryType); - this.onPacket(packet); - } - /** - * Called with a decoded packet. - * - * @protected - */ - }, { - key: "onPacket", - value: function onPacket(packet) { - _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "packet", packet); - } - /** - * Called upon close. - * - * @protected - */ - }, { - key: "onClose", - value: function onClose(details) { - this.readyState = "closed"; - _get(_getPrototypeOf(Transport.prototype), "emitReserved", this).call(this, "close", details); - } - /** - * Pauses the transport, in order not to lose packets during an upgrade. - * - * @param onPause - */ - }, { - key: "pause", - value: function pause(onPause) {} - }, { - key: "createUri", - value: function createUri(schema) { - var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query); - } - }, { - key: "_hostname", - value: function _hostname() { - var hostname = this.opts.hostname; - return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]"; - } - }, { - key: "_port", - value: function _port() { - if (this.opts.port && (this.opts.secure && Number(this.opts.port !== 443) || !this.opts.secure && Number(this.opts.port) !== 80)) { - return ":" + this.opts.port; - } else { - return ""; - } - } - }, { - key: "_query", - value: function _query(query) { - var encodedQuery = encode$1(query); - return encodedQuery.length ? "?" + encodedQuery : ""; - } - }]); - return Transport; - }(Emitter); - - // imported from https://github.com/unshiftio/yeast - - var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split(''), - length = 64, - map = {}; - var seed = 0, - i = 0, - prev; - /** - * Return a string representing the specified number. - * - * @param {Number} num The number to convert. - * @returns {String} The string representation of the number. - * @api public - */ - function encode(num) { - var encoded = ''; - do { - encoded = alphabet[num % length] + encoded; - num = Math.floor(num / length); - } while (num > 0); - return encoded; - } - /** - * Yeast: A tiny growing id generator. - * - * @returns {String} A unique id. - * @api public - */ - function yeast() { - var now = encode(+new Date()); - if (now !== prev) return seed = 0, prev = now; - return now + '.' + encode(seed++); - } - // - // Map each character to its index. - // - for (; i < length; i++) map[alphabet[i]] = i; - - // imported from https://github.com/component/has-cors - var value = false; - try { - value = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); - } catch (err) { - // if XMLHttp support is disabled in IE then it will throw - // when trying to create - } - var hasCORS = value; - - // browser shim for xmlhttprequest module - function XHR(opts) { - var xdomain = opts.xdomain; - // XMLHttpRequest can be disabled on IE - try { - if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) { - return new XMLHttpRequest(); - } - } catch (e) {} - if (!xdomain) { - try { - return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP"); - } catch (e) {} - } - } - function createCookieJar() {} - - function empty() {} - var hasXHR2 = function () { - var xhr = new XHR({ - xdomain: false - }); - return null != xhr.responseType; - }(); - var Polling = /*#__PURE__*/function (_Transport) { - _inherits(Polling, _Transport); - var _super = _createSuper(Polling); - /** - * XHR Polling constructor. - * - * @param {Object} opts - * @package - */ - function Polling(opts) { - var _this; - _classCallCheck(this, Polling); - _this = _super.call(this, opts); - _this.polling = false; - if (typeof location !== "undefined") { - var isSSL = "https:" === location.protocol; - var port = location.port; - // some user agents have empty `location.port` - if (!port) { - port = isSSL ? "443" : "80"; - } - _this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port; - } - /** - * XHR supports binary - */ - var forceBase64 = opts && opts.forceBase64; - _this.supportsBinary = hasXHR2 && !forceBase64; - if (_this.opts.withCredentials) { - _this.cookieJar = createCookieJar(); - } - return _this; - } - _createClass(Polling, [{ - key: "name", - get: function get() { - return "polling"; - } - /** - * Opens the socket (triggers polling). We write a PING message to determine - * when the transport is open. - * - * @protected - */ - }, { - key: "doOpen", - value: function doOpen() { - this.poll(); - } - /** - * Pauses polling. - * - * @param {Function} onPause - callback upon buffers are flushed and transport is paused - * @package - */ - }, { - key: "pause", - value: function pause(onPause) { - var _this2 = this; - this.readyState = "pausing"; - var pause = function pause() { - _this2.readyState = "paused"; - onPause(); - }; - if (this.polling || !this.writable) { - var total = 0; - if (this.polling) { - total++; - this.once("pollComplete", function () { - --total || pause(); - }); - } - if (!this.writable) { - total++; - this.once("drain", function () { - --total || pause(); - }); - } - } else { - pause(); - } - } - /** - * Starts polling cycle. - * - * @private - */ - }, { - key: "poll", - value: function poll() { - this.polling = true; - this.doPoll(); - this.emitReserved("poll"); - } - /** - * Overloads onData to detect payloads. - * - * @protected - */ - }, { - key: "onData", - value: function onData(data) { - var _this3 = this; - var callback = function callback(packet) { - // if its the first message we consider the transport open - if ("opening" === _this3.readyState && packet.type === "open") { - _this3.onOpen(); - } - // if its a close packet, we close the ongoing requests - if ("close" === packet.type) { - _this3.onClose({ - description: "transport closed by the server" - }); - return false; - } - // otherwise bypass onData and handle the message - _this3.onPacket(packet); - }; - // decode payload - decodePayload(data, this.socket.binaryType).forEach(callback); - // if an event did not trigger closing - if ("closed" !== this.readyState) { - // if we got data we're not polling - this.polling = false; - this.emitReserved("pollComplete"); - if ("open" === this.readyState) { - this.poll(); - } - } - } - /** - * For polling, send a close packet. - * - * @protected - */ - }, { - key: "doClose", - value: function doClose() { - var _this4 = this; - var close = function close() { - _this4.write([{ - type: "close" - }]); - }; - if ("open" === this.readyState) { - close(); - } else { - // in case we're trying to close while - // handshaking is in progress (GH-164) - this.once("open", close); - } - } - /** - * Writes a packets payload. - * - * @param {Array} packets - data packets - * @protected - */ - }, { - key: "write", - value: function write(packets) { - var _this5 = this; - this.writable = false; - encodePayload(packets, function (data) { - _this5.doWrite(data, function () { - _this5.writable = true; - _this5.emitReserved("drain"); - }); - }); - } - /** - * Generates uri for connection. - * - * @private - */ - }, { - key: "uri", - value: function uri() { - var schema = this.opts.secure ? "https" : "http"; - var query = this.query || {}; - // cache busting is forced - if (false !== this.opts.timestampRequests) { - query[this.opts.timestampParam] = yeast(); - } - if (!this.supportsBinary && !query.sid) { - query.b64 = 1; - } - return this.createUri(schema, query); - } - /** - * Creates a request. - * - * @param {String} method - * @private - */ - }, { - key: "request", - value: function request() { - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _extends(opts, { - xd: this.xd, - cookieJar: this.cookieJar - }, this.opts); - return new Request(this.uri(), opts); - } - /** - * Sends data. - * - * @param {String} data to send. - * @param {Function} called upon flush. - * @private - */ - }, { - key: "doWrite", - value: function doWrite(data, fn) { - var _this6 = this; - var req = this.request({ - method: "POST", - data: data - }); - req.on("success", fn); - req.on("error", function (xhrStatus, context) { - _this6.onError("xhr post error", xhrStatus, context); - }); - } - /** - * Starts a poll cycle. - * - * @private - */ - }, { - key: "doPoll", - value: function doPoll() { - var _this7 = this; - var req = this.request(); - req.on("data", this.onData.bind(this)); - req.on("error", function (xhrStatus, context) { - _this7.onError("xhr poll error", xhrStatus, context); - }); - this.pollXhr = req; - } - }]); - return Polling; - }(Transport); - var Request = /*#__PURE__*/function (_Emitter) { - _inherits(Request, _Emitter); - var _super2 = _createSuper(Request); - /** - * Request constructor - * - * @param {Object} options - * @package - */ - function Request(uri, opts) { - var _this8; - _classCallCheck(this, Request); - _this8 = _super2.call(this); - installTimerFunctions(_assertThisInitialized(_this8), opts); - _this8.opts = opts; - _this8.method = opts.method || "GET"; - _this8.uri = uri; - _this8.data = undefined !== opts.data ? opts.data : null; - _this8.create(); - return _this8; - } - /** - * Creates the XHR object and sends the request. - * - * @private - */ - _createClass(Request, [{ - key: "create", - value: function create() { - var _this9 = this; - var _a; - var opts = pick(this.opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref"); - opts.xdomain = !!this.opts.xd; - var xhr = this.xhr = new XHR(opts); - try { - xhr.open(this.method, this.uri, true); - try { - if (this.opts.extraHeaders) { - xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true); - for (var i in this.opts.extraHeaders) { - if (this.opts.extraHeaders.hasOwnProperty(i)) { - xhr.setRequestHeader(i, this.opts.extraHeaders[i]); - } - } - } - } catch (e) {} - if ("POST" === this.method) { - try { - xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8"); - } catch (e) {} - } - try { - xhr.setRequestHeader("Accept", "*/*"); - } catch (e) {} - (_a = this.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr); - // ie6 check - if ("withCredentials" in xhr) { - xhr.withCredentials = this.opts.withCredentials; - } - if (this.opts.requestTimeout) { - xhr.timeout = this.opts.requestTimeout; - } - xhr.onreadystatechange = function () { - var _a; - if (xhr.readyState === 3) { - (_a = _this9.opts.cookieJar) === null || _a === void 0 ? void 0 : _a.parseCookies(xhr); - } - if (4 !== xhr.readyState) return; - if (200 === xhr.status || 1223 === xhr.status) { - _this9.onLoad(); - } else { - // make sure the `error` event handler that's user-set - // does not throw in the same tick and gets caught here - _this9.setTimeoutFn(function () { - _this9.onError(typeof xhr.status === "number" ? xhr.status : 0); - }, 0); - } - }; - xhr.send(this.data); - } catch (e) { - // Need to defer since .create() is called directly from the constructor - // and thus the 'error' event can only be only bound *after* this exception - // occurs. Therefore, also, we cannot throw here at all. - this.setTimeoutFn(function () { - _this9.onError(e); - }, 0); - return; - } - if (typeof document !== "undefined") { - this.index = Request.requestsCount++; - Request.requests[this.index] = this; - } - } - /** - * Called upon error. - * - * @private - */ - }, { - key: "onError", - value: function onError(err) { - this.emitReserved("error", err, this.xhr); - this.cleanup(true); - } - /** - * Cleans up house. - * - * @private - */ - }, { - key: "cleanup", - value: function cleanup(fromError) { - if ("undefined" === typeof this.xhr || null === this.xhr) { - return; - } - this.xhr.onreadystatechange = empty; - if (fromError) { - try { - this.xhr.abort(); - } catch (e) {} - } - if (typeof document !== "undefined") { - delete Request.requests[this.index]; - } - this.xhr = null; - } - /** - * Called upon load. - * - * @private - */ - }, { - key: "onLoad", - value: function onLoad() { - var data = this.xhr.responseText; - if (data !== null) { - this.emitReserved("data", data); - this.emitReserved("success"); - this.cleanup(); - } - } - /** - * Aborts the request. - * - * @package - */ - }, { - key: "abort", - value: function abort() { - this.cleanup(); - } - }]); - return Request; - }(Emitter); - Request.requestsCount = 0; - Request.requests = {}; - /** - * Aborts pending requests when unloading the window. This is needed to prevent - * memory leaks (e.g. when using IE) and to ensure that no spurious error is - * emitted. - */ - if (typeof document !== "undefined") { - // @ts-ignore - if (typeof attachEvent === "function") { - // @ts-ignore - attachEvent("onunload", unloadHandler); - } else if (typeof addEventListener === "function") { - var terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload"; - addEventListener(terminationEvent, unloadHandler, false); - } - } - function unloadHandler() { - for (var i in Request.requests) { - if (Request.requests.hasOwnProperty(i)) { - Request.requests[i].abort(); - } - } - } - - var nextTick = function () { - var isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function"; - if (isPromiseAvailable) { - return function (cb) { - return Promise.resolve().then(cb); - }; - } else { - return function (cb, setTimeoutFn) { - return setTimeoutFn(cb, 0); - }; - } - }(); - var WebSocket = globalThisShim.WebSocket || globalThisShim.MozWebSocket; - var usingBrowserWebSocket = true; - var defaultBinaryType = "arraybuffer"; - - // detect ReactNative environment - var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative"; - var WS = /*#__PURE__*/function (_Transport) { - _inherits(WS, _Transport); - var _super = _createSuper(WS); - /** - * WebSocket transport constructor. - * - * @param {Object} opts - connection options - * @protected - */ - function WS(opts) { - var _this; - _classCallCheck(this, WS); - _this = _super.call(this, opts); - _this.supportsBinary = !opts.forceBase64; - return _this; - } - _createClass(WS, [{ - key: "name", - get: function get() { - return "websocket"; - } - }, { - key: "doOpen", - value: function doOpen() { - if (!this.check()) { - // let probe timeout - return; - } - var uri = this.uri(); - var protocols = this.opts.protocols; - // React Native only supports the 'headers' option, and will print a warning if anything else is passed - var opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity"); - if (this.opts.extraHeaders) { - opts.headers = this.opts.extraHeaders; - } - try { - this.ws = usingBrowserWebSocket && !isReactNative ? protocols ? new WebSocket(uri, protocols) : new WebSocket(uri) : new WebSocket(uri, protocols, opts); - } catch (err) { - return this.emitReserved("error", err); - } - this.ws.binaryType = this.socket.binaryType; - this.addEventListeners(); - } - /** - * Adds event listeners to the socket - * - * @private - */ - }, { - key: "addEventListeners", - value: function addEventListeners() { - var _this2 = this; - this.ws.onopen = function () { - if (_this2.opts.autoUnref) { - _this2.ws._socket.unref(); - } - _this2.onOpen(); - }; - this.ws.onclose = function (closeEvent) { - return _this2.onClose({ - description: "websocket connection closed", - context: closeEvent - }); - }; - this.ws.onmessage = function (ev) { - return _this2.onData(ev.data); - }; - this.ws.onerror = function (e) { - return _this2.onError("websocket error", e); - }; - } - }, { - key: "write", - value: function write(packets) { - var _this3 = this; - this.writable = false; - // encodePacket efficient as it uses WS framing - // no need for encodePayload - var _loop = function _loop() { - var packet = packets[i]; - var lastPacket = i === packets.length - 1; - encodePacket(packet, _this3.supportsBinary, function (data) { - // always create a new object (GH-437) - var opts = {}; - // Sometimes the websocket has already been closed but the browser didn't - // have a chance of informing us about it yet, in that case send will - // throw an error - try { - if (usingBrowserWebSocket) { - // TypeError is thrown when passing the second argument on Safari - _this3.ws.send(data); - } - } catch (e) {} - if (lastPacket) { - // fake drain - // defer to next tick to allow Socket to clear writeBuffer - nextTick(function () { - _this3.writable = true; - _this3.emitReserved("drain"); - }, _this3.setTimeoutFn); - } - }); - }; - for (var i = 0; i < packets.length; i++) { - _loop(); - } - } - }, { - key: "doClose", - value: function doClose() { - if (typeof this.ws !== "undefined") { - this.ws.close(); - this.ws = null; - } - } - /** - * Generates uri for connection. - * - * @private - */ - }, { - key: "uri", - value: function uri() { - var schema = this.opts.secure ? "wss" : "ws"; - var query = this.query || {}; - // append timestamp to URI - if (this.opts.timestampRequests) { - query[this.opts.timestampParam] = yeast(); - } - // communicate binary support capabilities - if (!this.supportsBinary) { - query.b64 = 1; - } - return this.createUri(schema, query); - } - /** - * Feature detection for WebSocket. - * - * @return {Boolean} whether this transport is available. - * @private - */ - }, { - key: "check", - value: function check() { - return !!WebSocket; - } - }]); - return WS; - }(Transport); - - var WT = /*#__PURE__*/function (_Transport) { - _inherits(WT, _Transport); - var _super = _createSuper(WT); - function WT() { - _classCallCheck(this, WT); - return _super.apply(this, arguments); - } - _createClass(WT, [{ - key: "name", - get: function get() { - return "webtransport"; - } - }, { - key: "doOpen", - value: function doOpen() { - var _this = this; - // @ts-ignore - if (typeof WebTransport !== "function") { - return; - } - // @ts-ignore - this.transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]); - this.transport.closed.then(function () { - _this.onClose(); - })["catch"](function (err) { - _this.onError("webtransport error", err); - }); - // note: we could have used async/await, but that would require some additional polyfills - this.transport.ready.then(function () { - _this.transport.createBidirectionalStream().then(function (stream) { - var decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, _this.socket.binaryType); - var reader = stream.readable.pipeThrough(decoderStream).getReader(); - var encoderStream = createPacketEncoderStream(); - encoderStream.readable.pipeTo(stream.writable); - _this.writer = encoderStream.writable.getWriter(); - var read = function read() { - reader.read().then(function (_ref) { - var done = _ref.done, - value = _ref.value; - if (done) { - return; - } - _this.onPacket(value); - read(); - })["catch"](function (err) {}); - }; - read(); - var packet = { - type: "open" - }; - if (_this.query.sid) { - packet.data = "{\"sid\":\"".concat(_this.query.sid, "\"}"); - } - _this.writer.write(packet).then(function () { - return _this.onOpen(); - }); - }); - }); - } - }, { - key: "write", - value: function write(packets) { - var _this2 = this; - this.writable = false; - var _loop = function _loop() { - var packet = packets[i]; - var lastPacket = i === packets.length - 1; - _this2.writer.write(packet).then(function () { - if (lastPacket) { - nextTick(function () { - _this2.writable = true; - _this2.emitReserved("drain"); - }, _this2.setTimeoutFn); - } - }); - }; - for (var i = 0; i < packets.length; i++) { - _loop(); - } - } - }, { - key: "doClose", - value: function doClose() { - var _a; - (_a = this.transport) === null || _a === void 0 ? void 0 : _a.close(); - } - }]); - return WT; - }(Transport); - - var transports = { - websocket: WS, - webtransport: WT, - polling: Polling - }; - - // imported from https://github.com/galkn/parseuri - /** - * Parses a URI - * - * Note: we could also have used the built-in URL object, but it isn't supported on all platforms. - * - * See: - * - https://developer.mozilla.org/en-US/docs/Web/API/URL - * - https://caniuse.com/url - * - https://www.rfc-editor.org/rfc/rfc3986#appendix-B - * - * History of the parse() method: - * - first commit: https://github.com/socketio/socket.io-client/commit/4ee1d5d94b3906a9c052b459f1a818b15f38f91c - * - export into its own module: https://github.com/socketio/engine.io-client/commit/de2c561e4564efeb78f1bdb1ba39ef81b2822cb3 - * - reimport: https://github.com/socketio/engine.io-client/commit/df32277c3f6d622eec5ed09f493cae3f3391d242 - * - * @author Steven Levithan (MIT license) - * @api private - */ - var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; - var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor']; - function parse(str) { - var src = str, - b = str.indexOf('['), - e = str.indexOf(']'); - if (b != -1 && e != -1) { - str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); - } - var m = re.exec(str || ''), - uri = {}, - i = 14; - while (i--) { - uri[parts[i]] = m[i] || ''; - } - if (b != -1 && e != -1) { - uri.source = src; - uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); - uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); - uri.ipv6uri = true; - } - uri.pathNames = pathNames(uri, uri['path']); - uri.queryKey = queryKey(uri, uri['query']); - return uri; - } - function pathNames(obj, path) { - var regx = /\/{2,9}/g, - names = path.replace(regx, "/").split("/"); - if (path.slice(0, 1) == '/' || path.length === 0) { - names.splice(0, 1); - } - if (path.slice(-1) == '/') { - names.splice(names.length - 1, 1); - } - return names; - } - function queryKey(uri, query) { - var data = {}; - query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { - if ($1) { - data[$1] = $2; - } - }); - return data; - } - - var Socket$1 = /*#__PURE__*/function (_Emitter) { - _inherits(Socket, _Emitter); - var _super = _createSuper(Socket); - /** - * Socket constructor. - * - * @param {String|Object} uri - uri or options - * @param {Object} opts - options - */ - function Socket(uri) { - var _this; - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - _classCallCheck(this, Socket); - _this = _super.call(this); - _this.binaryType = defaultBinaryType; - _this.writeBuffer = []; - if (uri && "object" === _typeof(uri)) { - opts = uri; - uri = null; - } - if (uri) { - uri = parse(uri); - opts.hostname = uri.host; - opts.secure = uri.protocol === "https" || uri.protocol === "wss"; - opts.port = uri.port; - if (uri.query) opts.query = uri.query; - } else if (opts.host) { - opts.hostname = parse(opts.host).host; - } - installTimerFunctions(_assertThisInitialized(_this), opts); - _this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol; - if (opts.hostname && !opts.port) { - // if no port is specified manually, use the protocol default - opts.port = _this.secure ? "443" : "80"; - } - _this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost"); - _this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : _this.secure ? "443" : "80"); - _this.transports = opts.transports || ["polling", "websocket", "webtransport"]; - _this.writeBuffer = []; - _this.prevBufferLen = 0; - _this.opts = _extends({ - path: "/engine.io", - agent: false, - withCredentials: false, - upgrade: true, - timestampParam: "t", - rememberUpgrade: false, - addTrailingSlash: true, - rejectUnauthorized: true, - perMessageDeflate: { - threshold: 1024 - }, - transportOptions: {}, - closeOnBeforeunload: false - }, opts); - _this.opts.path = _this.opts.path.replace(/\/$/, "") + (_this.opts.addTrailingSlash ? "/" : ""); - if (typeof _this.opts.query === "string") { - _this.opts.query = decode(_this.opts.query); - } - // set on handshake - _this.id = null; - _this.upgrades = null; - _this.pingInterval = null; - _this.pingTimeout = null; - // set on heartbeat - _this.pingTimeoutTimer = null; - if (typeof addEventListener === "function") { - if (_this.opts.closeOnBeforeunload) { - // Firefox closes the connection when the "beforeunload" event is emitted but not Chrome. This event listener - // ensures every browser behaves the same (no "disconnect" event at the Socket.IO level when the page is - // closed/reloaded) - _this.beforeunloadEventListener = function () { - if (_this.transport) { - // silently close the transport - _this.transport.removeAllListeners(); - _this.transport.close(); - } - }; - addEventListener("beforeunload", _this.beforeunloadEventListener, false); - } - if (_this.hostname !== "localhost") { - _this.offlineEventListener = function () { - _this.onClose("transport close", { - description: "network connection lost" - }); - }; - addEventListener("offline", _this.offlineEventListener, false); - } - } - _this.open(); - return _this; - } - /** - * Creates transport of the given type. - * - * @param {String} name - transport name - * @return {Transport} - * @private - */ - _createClass(Socket, [{ - key: "createTransport", - value: function createTransport(name) { - var query = _extends({}, this.opts.query); - // append engine.io protocol identifier - query.EIO = protocol$1; - // transport name - query.transport = name; - // session id if we already have one - if (this.id) query.sid = this.id; - var opts = _extends({}, this.opts, { - query: query, - socket: this, - hostname: this.hostname, - secure: this.secure, - port: this.port - }, this.opts.transportOptions[name]); - return new transports[name](opts); - } - /** - * Initializes transport to use and starts probe. - * - * @private - */ - }, { - key: "open", - value: function open() { - var _this2 = this; - var transport; - if (this.opts.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1) { - transport = "websocket"; - } else if (0 === this.transports.length) { - // Emit error on next tick so it can be listened to - this.setTimeoutFn(function () { - _this2.emitReserved("error", "No transports available"); - }, 0); - return; - } else { - transport = this.transports[0]; - } - this.readyState = "opening"; - // Retry with the next transport if the transport is disabled (jsonp: false) - try { - transport = this.createTransport(transport); - } catch (e) { - this.transports.shift(); - this.open(); - return; - } - transport.open(); - this.setTransport(transport); - } - /** - * Sets the current transport. Disables the existing one (if any). - * - * @private - */ - }, { - key: "setTransport", - value: function setTransport(transport) { - var _this3 = this; - if (this.transport) { - this.transport.removeAllListeners(); - } - // set up transport - this.transport = transport; - // set up transport listeners - transport.on("drain", this.onDrain.bind(this)).on("packet", this.onPacket.bind(this)).on("error", this.onError.bind(this)).on("close", function (reason) { - return _this3.onClose("transport close", reason); - }); - } - /** - * Probes a transport. - * - * @param {String} name - transport name - * @private - */ - }, { - key: "probe", - value: function probe(name) { - var _this4 = this; - var transport = this.createTransport(name); - var failed = false; - Socket.priorWebsocketSuccess = false; - var onTransportOpen = function onTransportOpen() { - if (failed) return; - transport.send([{ - type: "ping", - data: "probe" - }]); - transport.once("packet", function (msg) { - if (failed) return; - if ("pong" === msg.type && "probe" === msg.data) { - _this4.upgrading = true; - _this4.emitReserved("upgrading", transport); - if (!transport) return; - Socket.priorWebsocketSuccess = "websocket" === transport.name; - _this4.transport.pause(function () { - if (failed) return; - if ("closed" === _this4.readyState) return; - cleanup(); - _this4.setTransport(transport); - transport.send([{ - type: "upgrade" - }]); - _this4.emitReserved("upgrade", transport); - transport = null; - _this4.upgrading = false; - _this4.flush(); - }); - } else { - var err = new Error("probe error"); - // @ts-ignore - err.transport = transport.name; - _this4.emitReserved("upgradeError", err); - } - }); - }; - function freezeTransport() { - if (failed) return; - // Any callback called by transport should be ignored since now - failed = true; - cleanup(); - transport.close(); - transport = null; - } - // Handle any error that happens while probing - var onerror = function onerror(err) { - var error = new Error("probe error: " + err); - // @ts-ignore - error.transport = transport.name; - freezeTransport(); - _this4.emitReserved("upgradeError", error); - }; - function onTransportClose() { - onerror("transport closed"); - } - // When the socket is closed while we're probing - function onclose() { - onerror("socket closed"); - } - // When the socket is upgraded while we're probing - function onupgrade(to) { - if (transport && to.name !== transport.name) { - freezeTransport(); - } - } - // Remove all listeners on the transport and on self - var cleanup = function cleanup() { - transport.removeListener("open", onTransportOpen); - transport.removeListener("error", onerror); - transport.removeListener("close", onTransportClose); - _this4.off("close", onclose); - _this4.off("upgrading", onupgrade); - }; - transport.once("open", onTransportOpen); - transport.once("error", onerror); - transport.once("close", onTransportClose); - this.once("close", onclose); - this.once("upgrading", onupgrade); - if (this.upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") { - // favor WebTransport - this.setTimeoutFn(function () { - if (!failed) { - transport.open(); - } - }, 200); - } else { - transport.open(); - } - } - /** - * Called when connection is deemed open. - * - * @private - */ - }, { - key: "onOpen", - value: function onOpen() { - this.readyState = "open"; - Socket.priorWebsocketSuccess = "websocket" === this.transport.name; - this.emitReserved("open"); - this.flush(); - // we check for `readyState` in case an `open` - // listener already closed the socket - if ("open" === this.readyState && this.opts.upgrade) { - var i = 0; - var l = this.upgrades.length; - for (; i < l; i++) { - this.probe(this.upgrades[i]); - } - } - } - /** - * Handles a packet. - * - * @private - */ - }, { - key: "onPacket", - value: function onPacket(packet) { - if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { - this.emitReserved("packet", packet); - // Socket is live - any packet counts - this.emitReserved("heartbeat"); - this.resetPingTimeout(); - switch (packet.type) { - case "open": - this.onHandshake(JSON.parse(packet.data)); - break; - case "ping": - this.sendPacket("pong"); - this.emitReserved("ping"); - this.emitReserved("pong"); - break; - case "error": - var err = new Error("server error"); - // @ts-ignore - err.code = packet.data; - this.onError(err); - break; - case "message": - this.emitReserved("data", packet.data); - this.emitReserved("message", packet.data); - break; - } - } - } - /** - * Called upon handshake completion. - * - * @param {Object} data - handshake obj - * @private - */ - }, { - key: "onHandshake", - value: function onHandshake(data) { - this.emitReserved("handshake", data); - this.id = data.sid; - this.transport.query.sid = data.sid; - this.upgrades = this.filterUpgrades(data.upgrades); - this.pingInterval = data.pingInterval; - this.pingTimeout = data.pingTimeout; - this.maxPayload = data.maxPayload; - this.onOpen(); - // In case open handler closes socket - if ("closed" === this.readyState) return; - this.resetPingTimeout(); - } - /** - * Sets and resets ping timeout timer based on server pings. - * - * @private - */ - }, { - key: "resetPingTimeout", - value: function resetPingTimeout() { - var _this5 = this; - this.clearTimeoutFn(this.pingTimeoutTimer); - this.pingTimeoutTimer = this.setTimeoutFn(function () { - _this5.onClose("ping timeout"); - }, this.pingInterval + this.pingTimeout); - if (this.opts.autoUnref) { - this.pingTimeoutTimer.unref(); - } - } - /** - * Called on `drain` event - * - * @private - */ - }, { - key: "onDrain", - value: function onDrain() { - this.writeBuffer.splice(0, this.prevBufferLen); - // setting prevBufferLen = 0 is very important - // for example, when upgrading, upgrade packet is sent over, - // and a nonzero prevBufferLen could cause problems on `drain` - this.prevBufferLen = 0; - if (0 === this.writeBuffer.length) { - this.emitReserved("drain"); - } else { - this.flush(); - } - } - /** - * Flush write buffers. - * - * @private - */ - }, { - key: "flush", - value: function flush() { - if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) { - var packets = this.getWritablePackets(); - this.transport.send(packets); - // keep track of current length of writeBuffer - // splice writeBuffer and callbackBuffer on `drain` - this.prevBufferLen = packets.length; - this.emitReserved("flush"); - } - } - /** - * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP - * long-polling) - * - * @private - */ - }, { - key: "getWritablePackets", - value: function getWritablePackets() { - var shouldCheckPayloadSize = this.maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1; - if (!shouldCheckPayloadSize) { - return this.writeBuffer; - } - var payloadSize = 1; // first packet type - for (var i = 0; i < this.writeBuffer.length; i++) { - var data = this.writeBuffer[i].data; - if (data) { - payloadSize += byteLength(data); - } - if (i > 0 && payloadSize > this.maxPayload) { - return this.writeBuffer.slice(0, i); - } - payloadSize += 2; // separator + packet type - } - - return this.writeBuffer; - } - /** - * Sends a message. - * - * @param {String} msg - message. - * @param {Object} options. - * @param {Function} callback function. - * @return {Socket} for chaining. - */ - }, { - key: "write", - value: function write(msg, options, fn) { - this.sendPacket("message", msg, options, fn); - return this; - } - }, { - key: "send", - value: function send(msg, options, fn) { - this.sendPacket("message", msg, options, fn); - return this; - } - /** - * Sends a packet. - * - * @param {String} type: packet type. - * @param {String} data. - * @param {Object} options. - * @param {Function} fn - callback function. - * @private - */ - }, { - key: "sendPacket", - value: function sendPacket(type, data, options, fn) { - if ("function" === typeof data) { - fn = data; - data = undefined; - } - if ("function" === typeof options) { - fn = options; - options = null; - } - if ("closing" === this.readyState || "closed" === this.readyState) { - return; - } - options = options || {}; - options.compress = false !== options.compress; - var packet = { - type: type, - data: data, - options: options - }; - this.emitReserved("packetCreate", packet); - this.writeBuffer.push(packet); - if (fn) this.once("flush", fn); - this.flush(); - } - /** - * Closes the connection. - */ - }, { - key: "close", - value: function close() { - var _this6 = this; - var close = function close() { - _this6.onClose("forced close"); - _this6.transport.close(); - }; - var cleanupAndClose = function cleanupAndClose() { - _this6.off("upgrade", cleanupAndClose); - _this6.off("upgradeError", cleanupAndClose); - close(); - }; - var waitForUpgrade = function waitForUpgrade() { - // wait for upgrade to finish since we can't send packets while pausing a transport - _this6.once("upgrade", cleanupAndClose); - _this6.once("upgradeError", cleanupAndClose); - }; - if ("opening" === this.readyState || "open" === this.readyState) { - this.readyState = "closing"; - if (this.writeBuffer.length) { - this.once("drain", function () { - if (_this6.upgrading) { - waitForUpgrade(); - } else { - close(); - } - }); - } else if (this.upgrading) { - waitForUpgrade(); - } else { - close(); - } - } - return this; - } - /** - * Called upon transport error - * - * @private - */ - }, { - key: "onError", - value: function onError(err) { - Socket.priorWebsocketSuccess = false; - this.emitReserved("error", err); - this.onClose("transport error", err); - } - /** - * Called upon transport close. - * - * @private - */ - }, { - key: "onClose", - value: function onClose(reason, description) { - if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) { - // clear timers - this.clearTimeoutFn(this.pingTimeoutTimer); - // stop event from firing again for transport - this.transport.removeAllListeners("close"); - // ensure transport won't stay open - this.transport.close(); - // ignore further transport communication - this.transport.removeAllListeners(); - if (typeof removeEventListener === "function") { - removeEventListener("beforeunload", this.beforeunloadEventListener, false); - removeEventListener("offline", this.offlineEventListener, false); - } - // set ready state - this.readyState = "closed"; - // clear session id - this.id = null; - // emit close event - this.emitReserved("close", reason, description); - // clean buffers after, so users can still - // grab the buffers on `close` event - this.writeBuffer = []; - this.prevBufferLen = 0; - } - } - /** - * Filters upgrades, returning only those matching client transports. - * - * @param {Array} upgrades - server upgrades - * @private - */ - }, { - key: "filterUpgrades", - value: function filterUpgrades(upgrades) { - var filteredUpgrades = []; - var i = 0; - var j = upgrades.length; - for (; i < j; i++) { - if (~this.transports.indexOf(upgrades[i])) filteredUpgrades.push(upgrades[i]); - } - return filteredUpgrades; - } - }]); - return Socket; - }(Emitter); - Socket$1.protocol = protocol$1; - - Socket$1.protocol; - - /** - * URL parser. - * - * @param uri - url - * @param path - the request path of the connection - * @param loc - An object meant to mimic window.location. - * Defaults to window.location. - * @public - */ - function url(uri) { - var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; - var loc = arguments.length > 2 ? arguments[2] : undefined; - var obj = uri; - // default to window.location - loc = loc || typeof location !== "undefined" && location; - if (null == uri) uri = loc.protocol + "//" + loc.host; - // relative path support - if (typeof uri === "string") { - if ("/" === uri.charAt(0)) { - if ("/" === uri.charAt(1)) { - uri = loc.protocol + uri; - } else { - uri = loc.host + uri; - } - } - if (!/^(https?|wss?):\/\//.test(uri)) { - if ("undefined" !== typeof loc) { - uri = loc.protocol + "//" + uri; - } else { - uri = "https://" + uri; - } - } - // parse - obj = parse(uri); - } - // make sure we treat `localhost:80` and `localhost` equally - if (!obj.port) { - if (/^(http|ws)$/.test(obj.protocol)) { - obj.port = "80"; - } else if (/^(http|ws)s$/.test(obj.protocol)) { - obj.port = "443"; - } - } - obj.path = obj.path || "/"; - var ipv6 = obj.host.indexOf(":") !== -1; - var host = ipv6 ? "[" + obj.host + "]" : obj.host; - // define unique id - obj.id = obj.protocol + "://" + host + ":" + obj.port + path; - // define href - obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port); - return obj; - } - - var withNativeArrayBuffer = typeof ArrayBuffer === "function"; - var isView = function isView(obj) { - return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer; - }; - var toString = Object.prototype.toString; - var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]"; - var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]"; - /** - * Returns true if obj is a Buffer, an ArrayBuffer, a Blob or a File. - * - * @private - */ - function isBinary(obj) { - return withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)) || withNativeBlob && obj instanceof Blob || withNativeFile && obj instanceof File; - } - function hasBinary(obj, toJSON) { - if (!obj || _typeof(obj) !== "object") { - return false; - } - if (Array.isArray(obj)) { - for (var i = 0, l = obj.length; i < l; i++) { - if (hasBinary(obj[i])) { - return true; - } - } - return false; - } - if (isBinary(obj)) { - return true; - } - if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) { - return hasBinary(obj.toJSON(), true); - } - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { - return true; - } - } - return false; - } - - /** - * Replaces every Buffer | ArrayBuffer | Blob | File in packet with a numbered placeholder. - * - * @param {Object} packet - socket.io event packet - * @return {Object} with deconstructed packet and list of buffers - * @public - */ - function deconstructPacket(packet) { - var buffers = []; - var packetData = packet.data; - var pack = packet; - pack.data = _deconstructPacket(packetData, buffers); - pack.attachments = buffers.length; // number of binary 'attachments' - return { - packet: pack, - buffers: buffers - }; - } - function _deconstructPacket(data, buffers) { - if (!data) return data; - if (isBinary(data)) { - var placeholder = { - _placeholder: true, - num: buffers.length - }; - buffers.push(data); - return placeholder; - } else if (Array.isArray(data)) { - var newData = new Array(data.length); - for (var i = 0; i < data.length; i++) { - newData[i] = _deconstructPacket(data[i], buffers); - } - return newData; - } else if (_typeof(data) === "object" && !(data instanceof Date)) { - var _newData = {}; - for (var key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - _newData[key] = _deconstructPacket(data[key], buffers); - } - } - return _newData; - } - return data; - } - /** - * Reconstructs a binary packet from its placeholder packet and buffers - * - * @param {Object} packet - event packet with placeholders - * @param {Array} buffers - binary buffers to put in placeholder positions - * @return {Object} reconstructed packet - * @public - */ - function reconstructPacket(packet, buffers) { - packet.data = _reconstructPacket(packet.data, buffers); - delete packet.attachments; // no longer useful - return packet; - } - function _reconstructPacket(data, buffers) { - if (!data) return data; - if (data && data._placeholder === true) { - var isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length; - if (isIndexValid) { - return buffers[data.num]; // appropriate buffer (should be natural order anyway) - } else { - throw new Error("illegal attachments"); - } - } else if (Array.isArray(data)) { - for (var i = 0; i < data.length; i++) { - data[i] = _reconstructPacket(data[i], buffers); - } - } else if (_typeof(data) === "object") { - for (var key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - data[key] = _reconstructPacket(data[key], buffers); - } - } - } - return data; - } - - /** - * These strings must not be used as event names, as they have a special meaning. - */ - var RESERVED_EVENTS$1 = ["connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener" // used by the Node.js EventEmitter - ]; - /** - * Protocol version. - * - * @public - */ - var protocol = 5; - var PacketType; - (function (PacketType) { - PacketType[PacketType["CONNECT"] = 0] = "CONNECT"; - PacketType[PacketType["DISCONNECT"] = 1] = "DISCONNECT"; - PacketType[PacketType["EVENT"] = 2] = "EVENT"; - PacketType[PacketType["ACK"] = 3] = "ACK"; - PacketType[PacketType["CONNECT_ERROR"] = 4] = "CONNECT_ERROR"; - PacketType[PacketType["BINARY_EVENT"] = 5] = "BINARY_EVENT"; - PacketType[PacketType["BINARY_ACK"] = 6] = "BINARY_ACK"; - })(PacketType || (PacketType = {})); - /** - * A socket.io Encoder instance - */ - var Encoder = /*#__PURE__*/function () { - /** - * Encoder constructor - * - * @param {function} replacer - custom replacer to pass down to JSON.parse - */ - function Encoder(replacer) { - _classCallCheck(this, Encoder); - this.replacer = replacer; - } - /** - * Encode a packet as a single string if non-binary, or as a - * buffer sequence, depending on packet type. - * - * @param {Object} obj - packet object - */ - _createClass(Encoder, [{ - key: "encode", - value: function encode(obj) { - if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) { - if (hasBinary(obj)) { - return this.encodeAsBinary({ - type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK, - nsp: obj.nsp, - data: obj.data, - id: obj.id - }); - } - } - return [this.encodeAsString(obj)]; - } - /** - * Encode packet as string. - */ - }, { - key: "encodeAsString", - value: function encodeAsString(obj) { - // first is type - var str = "" + obj.type; - // attachments if we have them - if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) { - str += obj.attachments + "-"; - } - // if we have a namespace other than `/` - // we append it followed by a comma `,` - if (obj.nsp && "/" !== obj.nsp) { - str += obj.nsp + ","; - } - // immediately followed by the id - if (null != obj.id) { - str += obj.id; - } - // json data - if (null != obj.data) { - str += JSON.stringify(obj.data, this.replacer); - } - return str; - } - /** - * Encode packet as 'buffer sequence' by removing blobs, and - * deconstructing packet into object with placeholders and - * a list of buffers. - */ - }, { - key: "encodeAsBinary", - value: function encodeAsBinary(obj) { - var deconstruction = deconstructPacket(obj); - var pack = this.encodeAsString(deconstruction.packet); - var buffers = deconstruction.buffers; - buffers.unshift(pack); // add packet info to beginning of data list - return buffers; // write all the buffers - } - }]); - return Encoder; - }(); - // see https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript - function isObject(value) { - return Object.prototype.toString.call(value) === "[object Object]"; - } - /** - * A socket.io Decoder instance - * - * @return {Object} decoder - */ - var Decoder = /*#__PURE__*/function (_Emitter) { - _inherits(Decoder, _Emitter); - var _super = _createSuper(Decoder); - /** - * Decoder constructor - * - * @param {function} reviver - custom reviver to pass down to JSON.stringify - */ - function Decoder(reviver) { - var _this; - _classCallCheck(this, Decoder); - _this = _super.call(this); - _this.reviver = reviver; - return _this; - } - /** - * Decodes an encoded packet string into packet JSON. - * - * @param {String} obj - encoded packet - */ - _createClass(Decoder, [{ - key: "add", - value: function add(obj) { - var packet; - if (typeof obj === "string") { - if (this.reconstructor) { - throw new Error("got plaintext data when reconstructing a packet"); - } - packet = this.decodeString(obj); - var isBinaryEvent = packet.type === PacketType.BINARY_EVENT; - if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) { - packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK; - // binary packet's json - this.reconstructor = new BinaryReconstructor(packet); - // no attachments, labeled binary but no binary data to follow - if (packet.attachments === 0) { - _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); - } - } else { - // non-binary full packet - _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); - } - } else if (isBinary(obj) || obj.base64) { - // raw binary data - if (!this.reconstructor) { - throw new Error("got binary data when not reconstructing a packet"); - } else { - packet = this.reconstructor.takeBinaryData(obj); - if (packet) { - // received final buffer - this.reconstructor = null; - _get(_getPrototypeOf(Decoder.prototype), "emitReserved", this).call(this, "decoded", packet); - } - } - } else { - throw new Error("Unknown type: " + obj); - } - } - /** - * Decode a packet String (JSON data) - * - * @param {String} str - * @return {Object} packet - */ - }, { - key: "decodeString", - value: function decodeString(str) { - var i = 0; - // look up type - var p = { - type: Number(str.charAt(0)) - }; - if (PacketType[p.type] === undefined) { - throw new Error("unknown packet type " + p.type); - } - // look up attachments if type binary - if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) { - var start = i + 1; - while (str.charAt(++i) !== "-" && i != str.length) {} - var buf = str.substring(start, i); - if (buf != Number(buf) || str.charAt(i) !== "-") { - throw new Error("Illegal attachments"); - } - p.attachments = Number(buf); - } - // look up namespace (if any) - if ("/" === str.charAt(i + 1)) { - var _start = i + 1; - while (++i) { - var c = str.charAt(i); - if ("," === c) break; - if (i === str.length) break; - } - p.nsp = str.substring(_start, i); - } else { - p.nsp = "/"; - } - // look up id - var next = str.charAt(i + 1); - if ("" !== next && Number(next) == next) { - var _start2 = i + 1; - while (++i) { - var _c = str.charAt(i); - if (null == _c || Number(_c) != _c) { - --i; - break; - } - if (i === str.length) break; - } - p.id = Number(str.substring(_start2, i + 1)); - } - // look up json data - if (str.charAt(++i)) { - var payload = this.tryParse(str.substr(i)); - if (Decoder.isPayloadValid(p.type, payload)) { - p.data = payload; - } else { - throw new Error("invalid payload"); - } - } - return p; - } - }, { - key: "tryParse", - value: function tryParse(str) { - try { - return JSON.parse(str, this.reviver); - } catch (e) { - return false; - } - } - }, { - key: "destroy", - value: - /** - * Deallocates a parser's resources - */ - function destroy() { - if (this.reconstructor) { - this.reconstructor.finishedReconstruction(); - this.reconstructor = null; - } - } - }], [{ - key: "isPayloadValid", - value: function isPayloadValid(type, payload) { - switch (type) { - case PacketType.CONNECT: - return isObject(payload); - case PacketType.DISCONNECT: - return payload === undefined; - case PacketType.CONNECT_ERROR: - return typeof payload === "string" || isObject(payload); - case PacketType.EVENT: - case PacketType.BINARY_EVENT: - return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS$1.indexOf(payload[0]) === -1); - case PacketType.ACK: - case PacketType.BINARY_ACK: - return Array.isArray(payload); - } - } - }]); - return Decoder; - }(Emitter); - /** - * A manager of a binary event's 'buffer sequence'. Should - * be constructed whenever a packet of type BINARY_EVENT is - * decoded. - * - * @param {Object} packet - * @return {BinaryReconstructor} initialized reconstructor - */ - var BinaryReconstructor = /*#__PURE__*/function () { - function BinaryReconstructor(packet) { - _classCallCheck(this, BinaryReconstructor); - this.packet = packet; - this.buffers = []; - this.reconPack = packet; - } - /** - * Method to be called when binary data received from connection - * after a BINARY_EVENT packet. - * - * @param {Buffer | ArrayBuffer} binData - the raw binary data received - * @return {null | Object} returns null if more binary data is expected or - * a reconstructed packet object if all buffers have been received. - */ - _createClass(BinaryReconstructor, [{ - key: "takeBinaryData", - value: function takeBinaryData(binData) { - this.buffers.push(binData); - if (this.buffers.length === this.reconPack.attachments) { - // done with buffer list - var packet = reconstructPacket(this.reconPack, this.buffers); - this.finishedReconstruction(); - return packet; - } - return null; - } - /** - * Cleans up binary packet reconstruction variables. - */ - }, { - key: "finishedReconstruction", - value: function finishedReconstruction() { - this.reconPack = null; - this.buffers = []; - } - }]); - return BinaryReconstructor; - }(); - - var parser = /*#__PURE__*/Object.freeze({ - __proto__: null, - protocol: protocol, - get PacketType () { return PacketType; }, - Encoder: Encoder, - Decoder: Decoder - }); - - function on(obj, ev, fn) { - obj.on(ev, fn); - return function subDestroy() { - obj.off(ev, fn); - }; - } - - /** - * Internal events. - * These events can't be emitted by the user. - */ - var RESERVED_EVENTS = Object.freeze({ - connect: 1, - connect_error: 1, - disconnect: 1, - disconnecting: 1, - // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener - newListener: 1, - removeListener: 1 - }); - /** - * A Socket is the fundamental class for interacting with the server. - * - * A Socket belongs to a certain Namespace (by default /) and uses an underlying {@link Manager} to communicate. - * - * @example - * const socket = io(); - * - * socket.on("connect", () => { - * console.log("connected"); - * }); - * - * // send an event to the server - * socket.emit("foo", "bar"); - * - * socket.on("foobar", () => { - * // an event was received from the server - * }); - * - * // upon disconnection - * socket.on("disconnect", (reason) => { - * console.log(`disconnected due to ${reason}`); - * }); - */ - var Socket = /*#__PURE__*/function (_Emitter) { - _inherits(Socket, _Emitter); - var _super = _createSuper(Socket); - /** - * `Socket` constructor. - */ - function Socket(io, nsp, opts) { - var _this; - _classCallCheck(this, Socket); - _this = _super.call(this); - /** - * Whether the socket is currently connected to the server. - * - * @example - * const socket = io(); - * - * socket.on("connect", () => { - * console.log(socket.connected); // true - * }); - * - * socket.on("disconnect", () => { - * console.log(socket.connected); // false - * }); - */ - _this.connected = false; - /** - * Whether the connection state was recovered after a temporary disconnection. In that case, any missed packets will - * be transmitted by the server. - */ - _this.recovered = false; - /** - * Buffer for packets received before the CONNECT packet - */ - _this.receiveBuffer = []; - /** - * Buffer for packets that will be sent once the socket is connected - */ - _this.sendBuffer = []; - /** - * The queue of packets to be sent with retry in case of failure. - * - * Packets are sent one by one, each waiting for the server acknowledgement, in order to guarantee the delivery order. - * @private - */ - _this._queue = []; - /** - * A sequence to generate the ID of the {@link QueuedPacket}. - * @private - */ - _this._queueSeq = 0; - _this.ids = 0; - _this.acks = {}; - _this.flags = {}; - _this.io = io; - _this.nsp = nsp; - if (opts && opts.auth) { - _this.auth = opts.auth; - } - _this._opts = _extends({}, opts); - if (_this.io._autoConnect) _this.open(); - return _this; - } - /** - * Whether the socket is currently disconnected - * - * @example - * const socket = io(); - * - * socket.on("connect", () => { - * console.log(socket.disconnected); // false - * }); - * - * socket.on("disconnect", () => { - * console.log(socket.disconnected); // true - * }); - */ - _createClass(Socket, [{ - key: "disconnected", - get: function get() { - return !this.connected; - } - /** - * Subscribe to open, close and packet events - * - * @private - */ - }, { - key: "subEvents", - value: function subEvents() { - if (this.subs) return; - var io = this.io; - this.subs = [on(io, "open", this.onopen.bind(this)), on(io, "packet", this.onpacket.bind(this)), on(io, "error", this.onerror.bind(this)), on(io, "close", this.onclose.bind(this))]; - } - /** - * Whether the Socket will try to reconnect when its Manager connects or reconnects. - * - * @example - * const socket = io(); - * - * console.log(socket.active); // true - * - * socket.on("disconnect", (reason) => { - * if (reason === "io server disconnect") { - * // the disconnection was initiated by the server, you need to manually reconnect - * console.log(socket.active); // false - * } - * // else the socket will automatically try to reconnect - * console.log(socket.active); // true - * }); - */ - }, { - key: "active", - get: function get() { - return !!this.subs; - } - /** - * "Opens" the socket. - * - * @example - * const socket = io({ - * autoConnect: false - * }); - * - * socket.connect(); - */ - }, { - key: "connect", - value: function connect() { - if (this.connected) return this; - this.subEvents(); - if (!this.io["_reconnecting"]) this.io.open(); // ensure open - if ("open" === this.io._readyState) this.onopen(); - return this; - } - /** - * Alias for {@link connect()}. - */ - }, { - key: "open", - value: function open() { - return this.connect(); - } - /** - * Sends a `message` event. - * - * This method mimics the WebSocket.send() method. - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send - * - * @example - * socket.send("hello"); - * - * // this is equivalent to - * socket.emit("message", "hello"); - * - * @return self - */ - }, { - key: "send", - value: function send() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - args.unshift("message"); - this.emit.apply(this, args); - return this; - } - /** - * Override `emit`. - * If the event is in `events`, it's emitted normally. - * - * @example - * socket.emit("hello", "world"); - * - * // all serializable datastructures are supported (no need to call JSON.stringify) - * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) }); - * - * // with an acknowledgement from the server - * socket.emit("hello", "world", (val) => { - * // ... - * }); - * - * @return self - */ - }, { - key: "emit", - value: function emit(ev) { - if (RESERVED_EVENTS.hasOwnProperty(ev)) { - throw new Error('"' + ev.toString() + '" is a reserved event name'); - } - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - args.unshift(ev); - if (this._opts.retries && !this.flags.fromQueue && !this.flags["volatile"]) { - this._addToQueue(args); - return this; - } - var packet = { - type: PacketType.EVENT, - data: args - }; - packet.options = {}; - packet.options.compress = this.flags.compress !== false; - // event ack callback - if ("function" === typeof args[args.length - 1]) { - var id = this.ids++; - var ack = args.pop(); - this._registerAckCallback(id, ack); - packet.id = id; - } - var isTransportWritable = this.io.engine && this.io.engine.transport && this.io.engine.transport.writable; - var discardPacket = this.flags["volatile"] && (!isTransportWritable || !this.connected); - if (discardPacket) ; else if (this.connected) { - this.notifyOutgoingListeners(packet); - this.packet(packet); - } else { - this.sendBuffer.push(packet); - } - this.flags = {}; - return this; - } - /** - * @private - */ - }, { - key: "_registerAckCallback", - value: function _registerAckCallback(id, ack) { - var _this2 = this; - var _a; - var timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout; - if (timeout === undefined) { - this.acks[id] = ack; - return; - } - // @ts-ignore - var timer = this.io.setTimeoutFn(function () { - delete _this2.acks[id]; - for (var i = 0; i < _this2.sendBuffer.length; i++) { - if (_this2.sendBuffer[i].id === id) { - _this2.sendBuffer.splice(i, 1); - } - } - ack.call(_this2, new Error("operation has timed out")); - }, timeout); - this.acks[id] = function () { - // @ts-ignore - _this2.io.clearTimeoutFn(timer); - for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - ack.apply(_this2, [null].concat(args)); - }; - } - /** - * Emits an event and waits for an acknowledgement - * - * @example - * // without timeout - * const response = await socket.emitWithAck("hello", "world"); - * - * // with a specific timeout - * try { - * const response = await socket.timeout(1000).emitWithAck("hello", "world"); - * } catch (err) { - * // the server did not acknowledge the event in the given delay - * } - * - * @return a Promise that will be fulfilled when the server acknowledges the event - */ - }, { - key: "emitWithAck", - value: function emitWithAck(ev) { - var _this3 = this; - for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - // the timeout flag is optional - var withErr = this.flags.timeout !== undefined || this._opts.ackTimeout !== undefined; - return new Promise(function (resolve, reject) { - args.push(function (arg1, arg2) { - if (withErr) { - return arg1 ? reject(arg1) : resolve(arg2); - } else { - return resolve(arg1); - } - }); - _this3.emit.apply(_this3, [ev].concat(args)); - }); - } - /** - * Add the packet to the queue. - * @param args - * @private - */ - }, { - key: "_addToQueue", - value: function _addToQueue(args) { - var _this4 = this; - var ack; - if (typeof args[args.length - 1] === "function") { - ack = args.pop(); - } - var packet = { - id: this._queueSeq++, - tryCount: 0, - pending: false, - args: args, - flags: _extends({ - fromQueue: true - }, this.flags) - }; - args.push(function (err) { - if (packet !== _this4._queue[0]) { - // the packet has already been acknowledged - return; - } - var hasError = err !== null; - if (hasError) { - if (packet.tryCount > _this4._opts.retries) { - _this4._queue.shift(); - if (ack) { - ack(err); - } - } - } else { - _this4._queue.shift(); - if (ack) { - for (var _len5 = arguments.length, responseArgs = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - responseArgs[_key5 - 1] = arguments[_key5]; - } - ack.apply(void 0, [null].concat(responseArgs)); - } - } - packet.pending = false; - return _this4._drainQueue(); - }); - this._queue.push(packet); - this._drainQueue(); - } - /** - * Send the first packet of the queue, and wait for an acknowledgement from the server. - * @param force - whether to resend a packet that has not been acknowledged yet - * - * @private - */ - }, { - key: "_drainQueue", - value: function _drainQueue() { - var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - if (!this.connected || this._queue.length === 0) { - return; - } - var packet = this._queue[0]; - if (packet.pending && !force) { - return; - } - packet.pending = true; - packet.tryCount++; - this.flags = packet.flags; - this.emit.apply(this, packet.args); - } - /** - * Sends a packet. - * - * @param packet - * @private - */ - }, { - key: "packet", - value: function packet(_packet) { - _packet.nsp = this.nsp; - this.io._packet(_packet); - } - /** - * Called upon engine `open`. - * - * @private - */ - }, { - key: "onopen", - value: function onopen() { - var _this5 = this; - if (typeof this.auth == "function") { - this.auth(function (data) { - _this5._sendConnectPacket(data); - }); - } else { - this._sendConnectPacket(this.auth); - } - } - /** - * Sends a CONNECT packet to initiate the Socket.IO session. - * - * @param data - * @private - */ - }, { - key: "_sendConnectPacket", - value: function _sendConnectPacket(data) { - this.packet({ - type: PacketType.CONNECT, - data: this._pid ? _extends({ - pid: this._pid, - offset: this._lastOffset - }, data) : data - }); - } - /** - * Called upon engine or manager `error`. - * - * @param err - * @private - */ - }, { - key: "onerror", - value: function onerror(err) { - if (!this.connected) { - this.emitReserved("connect_error", err); - } - } - /** - * Called upon engine `close`. - * - * @param reason - * @param description - * @private - */ - }, { - key: "onclose", - value: function onclose(reason, description) { - this.connected = false; - delete this.id; - this.emitReserved("disconnect", reason, description); - } - /** - * Called with socket packet. - * - * @param packet - * @private - */ - }, { - key: "onpacket", - value: function onpacket(packet) { - var sameNamespace = packet.nsp === this.nsp; - if (!sameNamespace) return; - switch (packet.type) { - case PacketType.CONNECT: - if (packet.data && packet.data.sid) { - this.onconnect(packet.data.sid, packet.data.pid); - } else { - 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 PacketType.EVENT: - case PacketType.BINARY_EVENT: - this.onevent(packet); - break; - case PacketType.ACK: - case PacketType.BINARY_ACK: - this.onack(packet); - break; - case PacketType.DISCONNECT: - this.ondisconnect(); - break; - case PacketType.CONNECT_ERROR: - this.destroy(); - var err = new Error(packet.data.message); - // @ts-ignore - err.data = packet.data.data; - this.emitReserved("connect_error", err); - break; - } - } - /** - * Called upon a server event. - * - * @param packet - * @private - */ - }, { - key: "onevent", - value: function onevent(packet) { - var args = packet.data || []; - if (null != packet.id) { - args.push(this.ack(packet.id)); - } - if (this.connected) { - this.emitEvent(args); - } else { - this.receiveBuffer.push(Object.freeze(args)); - } - } - }, { - key: "emitEvent", - value: function emitEvent(args) { - if (this._anyListeners && this._anyListeners.length) { - var listeners = this._anyListeners.slice(); - var _iterator = _createForOfIteratorHelper(listeners), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var listener = _step.value; - listener.apply(this, args); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - _get(_getPrototypeOf(Socket.prototype), "emit", this).apply(this, args); - if (this._pid && args.length && typeof args[args.length - 1] === "string") { - this._lastOffset = args[args.length - 1]; - } - } - /** - * Produces an ack callback to emit with an event. - * - * @private - */ - }, { - key: "ack", - value: function ack(id) { - var self = this; - var sent = false; - return function () { - // prevent double callbacks - if (sent) return; - sent = true; - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - self.packet({ - type: PacketType.ACK, - id: id, - data: args - }); - }; - } - /** - * Called upon a server acknowlegement. - * - * @param packet - * @private - */ - }, { - key: "onack", - value: function onack(packet) { - var ack = this.acks[packet.id]; - if ("function" === typeof ack) { - ack.apply(this, packet.data); - delete this.acks[packet.id]; - } - } - /** - * Called upon server connect. - * - * @private - */ - }, { - key: "onconnect", - value: function onconnect(id, pid) { - this.id = id; - this.recovered = pid && this._pid === pid; - this._pid = pid; // defined only if connection state recovery is enabled - this.connected = true; - this.emitBuffered(); - this.emitReserved("connect"); - this._drainQueue(true); - } - /** - * Emit buffered events (received and emitted). - * - * @private - */ - }, { - key: "emitBuffered", - value: function emitBuffered() { - var _this6 = this; - this.receiveBuffer.forEach(function (args) { - return _this6.emitEvent(args); - }); - this.receiveBuffer = []; - this.sendBuffer.forEach(function (packet) { - _this6.notifyOutgoingListeners(packet); - _this6.packet(packet); - }); - this.sendBuffer = []; - } - /** - * Called upon server disconnect. - * - * @private - */ - }, { - key: "ondisconnect", - value: function ondisconnect() { - this.destroy(); - this.onclose("io server disconnect"); - } - /** - * Called upon forced client/server side disconnections, - * this method ensures the manager stops tracking us and - * that reconnections don't get triggered for this. - * - * @private - */ - }, { - key: "destroy", - value: function destroy() { - if (this.subs) { - // clean subscriptions to avoid reconnections - this.subs.forEach(function (subDestroy) { - return subDestroy(); - }); - this.subs = undefined; - } - this.io["_destroy"](this); - } - /** - * Disconnects the socket manually. In that case, the socket will not try to reconnect. - * - * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed. - * - * @example - * const socket = io(); - * - * socket.on("disconnect", (reason) => { - * // console.log(reason); prints "io client disconnect" - * }); - * - * socket.disconnect(); - * - * @return self - */ - }, { - key: "disconnect", - value: function disconnect() { - if (this.connected) { - this.packet({ - type: PacketType.DISCONNECT - }); - } - // remove socket from pool - this.destroy(); - if (this.connected) { - // fire events - this.onclose("io client disconnect"); - } - return this; - } - /** - * Alias for {@link disconnect()}. - * - * @return self - */ - }, { - key: "close", - value: function close() { - return this.disconnect(); - } - /** - * Sets the compress flag. - * - * @example - * socket.compress(false).emit("hello"); - * - * @param compress - if `true`, compresses the sending data - * @return self - */ - }, { - key: "compress", - value: function compress(_compress) { - this.flags.compress = _compress; - return this; - } - /** - * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not - * ready to send messages. - * - * @example - * socket.volatile.emit("hello"); // the server may or may not receive it - * - * @returns self - */ - }, { - key: "volatile", - get: function get() { - this.flags["volatile"] = true; - return this; - } - /** - * Sets a modifier for a subsequent event emission that the callback will be called with an error when the - * given number of milliseconds have elapsed without an acknowledgement from the server: - * - * @example - * socket.timeout(5000).emit("my-event", (err) => { - * if (err) { - * // the server did not acknowledge the event in the given delay - * } - * }); - * - * @returns self - */ - }, { - key: "timeout", - value: function timeout(_timeout) { - this.flags.timeout = _timeout; - return this; - } - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. - * - * @example - * socket.onAny((event, ...args) => { - * console.log(`got ${event}`); - * }); - * - * @param listener - */ - }, { - key: "onAny", - value: function onAny(listener) { - this._anyListeners = this._anyListeners || []; - this._anyListeners.push(listener); - return this; - } - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. The listener is added to the beginning of the listeners array. - * - * @example - * socket.prependAny((event, ...args) => { - * console.log(`got event ${event}`); - * }); - * - * @param listener - */ - }, { - key: "prependAny", - value: function prependAny(listener) { - this._anyListeners = this._anyListeners || []; - this._anyListeners.unshift(listener); - return this; - } - /** - * Removes the listener that will be fired when any event is emitted. - * - * @example - * const catchAllListener = (event, ...args) => { - * console.log(`got event ${event}`); - * } - * - * socket.onAny(catchAllListener); - * - * // remove a specific listener - * socket.offAny(catchAllListener); - * - * // or remove all listeners - * socket.offAny(); - * - * @param listener - */ - }, { - key: "offAny", - value: function offAny(listener) { - if (!this._anyListeners) { - return this; - } - if (listener) { - var listeners = this._anyListeners; - for (var i = 0; i < listeners.length; i++) { - if (listener === listeners[i]) { - listeners.splice(i, 1); - return this; - } - } - } else { - this._anyListeners = []; - } - return this; - } - /** - * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, - * e.g. to remove listeners. - */ - }, { - key: "listenersAny", - value: function listenersAny() { - return this._anyListeners || []; - } - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. - * - * Note: acknowledgements sent to the server are not included. - * - * @example - * socket.onAnyOutgoing((event, ...args) => { - * console.log(`sent event ${event}`); - * }); - * - * @param listener - */ - }, { - key: "onAnyOutgoing", - value: function onAnyOutgoing(listener) { - this._anyOutgoingListeners = this._anyOutgoingListeners || []; - this._anyOutgoingListeners.push(listener); - return this; - } - /** - * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the - * callback. The listener is added to the beginning of the listeners array. - * - * Note: acknowledgements sent to the server are not included. - * - * @example - * socket.prependAnyOutgoing((event, ...args) => { - * console.log(`sent event ${event}`); - * }); - * - * @param listener - */ - }, { - key: "prependAnyOutgoing", - value: function prependAnyOutgoing(listener) { - this._anyOutgoingListeners = this._anyOutgoingListeners || []; - this._anyOutgoingListeners.unshift(listener); - return this; - } - /** - * Removes the listener that will be fired when any event is emitted. - * - * @example - * const catchAllListener = (event, ...args) => { - * console.log(`sent event ${event}`); - * } - * - * socket.onAnyOutgoing(catchAllListener); - * - * // remove a specific listener - * socket.offAnyOutgoing(catchAllListener); - * - * // or remove all listeners - * socket.offAnyOutgoing(); - * - * @param [listener] - the catch-all listener (optional) - */ - }, { - key: "offAnyOutgoing", - value: function offAnyOutgoing(listener) { - if (!this._anyOutgoingListeners) { - return this; - } - if (listener) { - var listeners = this._anyOutgoingListeners; - for (var i = 0; i < listeners.length; i++) { - if (listener === listeners[i]) { - listeners.splice(i, 1); - return this; - } - } - } else { - this._anyOutgoingListeners = []; - } - return this; - } - /** - * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, - * e.g. to remove listeners. - */ - }, { - key: "listenersAnyOutgoing", - value: function listenersAnyOutgoing() { - return this._anyOutgoingListeners || []; - } - /** - * Notify the listeners for each packet sent - * - * @param packet - * - * @private - */ - }, { - key: "notifyOutgoingListeners", - value: function notifyOutgoingListeners(packet) { - if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) { - var listeners = this._anyOutgoingListeners.slice(); - var _iterator2 = _createForOfIteratorHelper(listeners), - _step2; - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var listener = _step2.value; - listener.apply(this, packet.data); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - } - }]); - return Socket; - }(Emitter); - - /** - * Initialize backoff timer with `opts`. - * - * - `min` initial timeout in milliseconds [100] - * - `max` max timeout [10000] - * - `jitter` [0] - * - `factor` [2] - * - * @param {Object} opts - * @api public - */ - function Backoff(opts) { - opts = opts || {}; - this.ms = opts.min || 100; - this.max = opts.max || 10000; - this.factor = opts.factor || 2; - this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; - this.attempts = 0; - } - /** - * Return the backoff duration. - * - * @return {Number} - * @api public - */ - Backoff.prototype.duration = function () { - var ms = this.ms * Math.pow(this.factor, this.attempts++); - if (this.jitter) { - var rand = Math.random(); - var deviation = Math.floor(rand * this.jitter * ms); - ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; - } - return Math.min(ms, this.max) | 0; - }; - /** - * Reset the number of attempts. - * - * @api public - */ - Backoff.prototype.reset = function () { - this.attempts = 0; - }; - /** - * Set the minimum duration - * - * @api public - */ - Backoff.prototype.setMin = function (min) { - this.ms = min; - }; - /** - * Set the maximum duration - * - * @api public - */ - Backoff.prototype.setMax = function (max) { - this.max = max; - }; - /** - * Set the jitter - * - * @api public - */ - Backoff.prototype.setJitter = function (jitter) { - this.jitter = jitter; - }; - - var Manager = /*#__PURE__*/function (_Emitter) { - _inherits(Manager, _Emitter); - var _super = _createSuper(Manager); - function Manager(uri, opts) { - var _this; - _classCallCheck(this, Manager); - var _a; - _this = _super.call(this); - _this.nsps = {}; - _this.subs = []; - if (uri && "object" === _typeof(uri)) { - opts = uri; - uri = undefined; - } - opts = opts || {}; - opts.path = opts.path || "/socket.io"; - _this.opts = opts; - installTimerFunctions(_assertThisInitialized(_this), opts); - _this.reconnection(opts.reconnection !== false); - _this.reconnectionAttempts(opts.reconnectionAttempts || Infinity); - _this.reconnectionDelay(opts.reconnectionDelay || 1000); - _this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000); - _this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5); - _this.backoff = new Backoff({ - min: _this.reconnectionDelay(), - max: _this.reconnectionDelayMax(), - jitter: _this.randomizationFactor() - }); - _this.timeout(null == opts.timeout ? 20000 : opts.timeout); - _this._readyState = "closed"; - _this.uri = uri; - var _parser = opts.parser || parser; - _this.encoder = new _parser.Encoder(); - _this.decoder = new _parser.Decoder(); - _this._autoConnect = opts.autoConnect !== false; - if (_this._autoConnect) _this.open(); - return _this; - } - _createClass(Manager, [{ - key: "reconnection", - value: function reconnection(v) { - if (!arguments.length) return this._reconnection; - this._reconnection = !!v; - return this; - } - }, { - key: "reconnectionAttempts", - value: function reconnectionAttempts(v) { - if (v === undefined) return this._reconnectionAttempts; - this._reconnectionAttempts = v; - return this; - } - }, { - key: "reconnectionDelay", - value: function reconnectionDelay(v) { - var _a; - if (v === undefined) return this._reconnectionDelay; - this._reconnectionDelay = v; - (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v); - return this; - } - }, { - key: "randomizationFactor", - value: function randomizationFactor(v) { - var _a; - if (v === undefined) return this._randomizationFactor; - this._randomizationFactor = v; - (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v); - return this; - } - }, { - key: "reconnectionDelayMax", - value: function reconnectionDelayMax(v) { - var _a; - if (v === undefined) return this._reconnectionDelayMax; - this._reconnectionDelayMax = v; - (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v); - return this; - } - }, { - key: "timeout", - value: function timeout(v) { - if (!arguments.length) return this._timeout; - this._timeout = v; - return this; - } - /** - * Starts trying to reconnect if reconnection is enabled and we have not - * started reconnecting yet - * - * @private - */ - }, { - key: "maybeReconnectOnOpen", - value: function maybeReconnectOnOpen() { - // Only try to reconnect if it's the first time we're connecting - if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) { - // keeps reconnection from firing twice for the same reconnection loop - this.reconnect(); - } - } - /** - * Sets the current transport `socket`. - * - * @param {Function} fn - optional, callback - * @return self - * @public - */ - }, { - key: "open", - value: function open(fn) { - var _this2 = this; - if (~this._readyState.indexOf("open")) return this; - this.engine = new Socket$1(this.uri, this.opts); - var socket = this.engine; - var self = this; - this._readyState = "opening"; - this.skipReconnect = false; - // emit `open` - var openSubDestroy = on(socket, "open", function () { - self.onopen(); - fn && fn(); - }); - var onError = function onError(err) { - _this2.cleanup(); - _this2._readyState = "closed"; - _this2.emitReserved("error", err); - if (fn) { - fn(err); - } else { - // Only do this if there is no fn to handle the error - _this2.maybeReconnectOnOpen(); - } - }; - // emit `error` - var errorSub = on(socket, "error", onError); - if (false !== this._timeout) { - var timeout = this._timeout; - // set timer - var timer = this.setTimeoutFn(function () { - openSubDestroy(); - onError(new Error("timeout")); - socket.close(); - }, timeout); - if (this.opts.autoUnref) { - timer.unref(); - } - this.subs.push(function () { - _this2.clearTimeoutFn(timer); - }); - } - this.subs.push(openSubDestroy); - this.subs.push(errorSub); - return this; - } - /** - * Alias for open() - * - * @return self - * @public - */ - }, { - key: "connect", - value: function connect(fn) { - return this.open(fn); - } - /** - * Called upon transport open. - * - * @private - */ - }, { - key: "onopen", - value: function onopen() { - // clear old subs - this.cleanup(); - // mark as open - this._readyState = "open"; - this.emitReserved("open"); - // add new subs - var socket = this.engine; - this.subs.push(on(socket, "ping", this.onping.bind(this)), on(socket, "data", this.ondata.bind(this)), on(socket, "error", this.onerror.bind(this)), on(socket, "close", this.onclose.bind(this)), on(this.decoder, "decoded", this.ondecoded.bind(this))); - } - /** - * Called upon a ping. - * - * @private - */ - }, { - key: "onping", - value: function onping() { - this.emitReserved("ping"); - } - /** - * Called with data. - * - * @private - */ - }, { - key: "ondata", - value: function ondata(data) { - try { - this.decoder.add(data); - } catch (e) { - this.onclose("parse error", e); - } - } - /** - * Called when parser fully decodes a packet. - * - * @private - */ - }, { - key: "ondecoded", - value: function ondecoded(packet) { - var _this3 = this; - // the nextTick call prevents an exception in a user-provided event listener from triggering a disconnection due to a "parse error" - nextTick(function () { - _this3.emitReserved("packet", packet); - }, this.setTimeoutFn); - } - /** - * Called upon socket error. - * - * @private - */ - }, { - key: "onerror", - value: function onerror(err) { - this.emitReserved("error", err); - } - /** - * Creates a new socket for the given `nsp`. - * - * @return {Socket} - * @public - */ - }, { - key: "socket", - value: function socket(nsp, opts) { - var socket = this.nsps[nsp]; - if (!socket) { - socket = new Socket(this, nsp, opts); - this.nsps[nsp] = socket; - } else if (this._autoConnect && !socket.active) { - socket.connect(); - } - return socket; - } - /** - * Called upon a socket close. - * - * @param socket - * @private - */ - }, { - key: "_destroy", - value: function _destroy(socket) { - var nsps = Object.keys(this.nsps); - for (var _i = 0, _nsps = nsps; _i < _nsps.length; _i++) { - var nsp = _nsps[_i]; - var _socket = this.nsps[nsp]; - if (_socket.active) { - return; - } - } - this._close(); - } - /** - * Writes a packet. - * - * @param packet - * @private - */ - }, { - key: "_packet", - value: function _packet(packet) { - var encodedPackets = this.encoder.encode(packet); - for (var i = 0; i < encodedPackets.length; i++) { - this.engine.write(encodedPackets[i], packet.options); - } - } - /** - * Clean up transport subscriptions and packet buffer. - * - * @private - */ - }, { - key: "cleanup", - value: function cleanup() { - this.subs.forEach(function (subDestroy) { - return subDestroy(); - }); - this.subs.length = 0; - this.decoder.destroy(); - } - /** - * Close the current socket. - * - * @private - */ - }, { - key: "_close", - value: function _close() { - this.skipReconnect = true; - this._reconnecting = false; - this.onclose("forced close"); - if (this.engine) this.engine.close(); - } - /** - * Alias for close() - * - * @private - */ - }, { - key: "disconnect", - value: function disconnect() { - return this._close(); - } - /** - * Called upon engine close. - * - * @private - */ - }, { - key: "onclose", - value: function onclose(reason, description) { - this.cleanup(); - this.backoff.reset(); - this._readyState = "closed"; - this.emitReserved("close", reason, description); - if (this._reconnection && !this.skipReconnect) { - this.reconnect(); - } - } - /** - * Attempt a reconnection. - * - * @private - */ - }, { - key: "reconnect", - value: function reconnect() { - var _this4 = this; - if (this._reconnecting || this.skipReconnect) return this; - var self = this; - if (this.backoff.attempts >= this._reconnectionAttempts) { - this.backoff.reset(); - this.emitReserved("reconnect_failed"); - this._reconnecting = false; - } else { - var delay = this.backoff.duration(); - this._reconnecting = true; - var timer = this.setTimeoutFn(function () { - if (self.skipReconnect) return; - _this4.emitReserved("reconnect_attempt", self.backoff.attempts); - // check again for the case socket closed in above events - if (self.skipReconnect) return; - self.open(function (err) { - if (err) { - self._reconnecting = false; - self.reconnect(); - _this4.emitReserved("reconnect_error", err); - } else { - self.onreconnect(); - } - }); - }, delay); - if (this.opts.autoUnref) { - timer.unref(); - } - this.subs.push(function () { - _this4.clearTimeoutFn(timer); - }); - } - } - /** - * Called upon successful reconnect. - * - * @private - */ - }, { - key: "onreconnect", - value: function onreconnect() { - var attempt = this.backoff.attempts; - this._reconnecting = false; - this.backoff.reset(); - this.emitReserved("reconnect", attempt); - } - }]); - return Manager; - }(Emitter); - - /** - * Managers cache. - */ - var cache = {}; - function lookup(uri, opts) { - if (_typeof(uri) === "object") { - opts = uri; - uri = undefined; - } - opts = opts || {}; - var parsed = url(uri, opts.path || "/socket.io"); - var source = parsed.source; - var id = parsed.id; - var path = parsed.path; - var sameNamespace = cache[id] && path in cache[id]["nsps"]; - var newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace; - var io; - if (newConnection) { - io = new Manager(source, opts); - } else { - if (!cache[id]) { - cache[id] = new Manager(source, opts); - } - io = cache[id]; - } - if (parsed.query && !opts.query) { - opts.query = parsed.queryKey; - } - return io.socket(parsed.path, opts); - } - // so that "lookup" can be used both as a function (e.g. `io(...)`) and as a - // namespace (e.g. `io.connect(...)`), for backward compatibility - _extends(lookup, { - Manager: Manager, - Socket: Socket, - io: lookup, - connect: lookup - }); - - return lookup; - -})); -//# sourceMappingURL=socket.io.js.map diff --git a/src/puter-js/src/lib/socket.io/socket.io.min.js b/src/puter-js/src/lib/socket.io/socket.io.min.js deleted file mode 100644 index f39af5c95d..0000000000 --- a/src/puter-js/src/lib/socket.io/socket.io.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Socket.IO v4.7.2 - * (c) 2014-2023 Guillermo Rauch - * Released under the MIT License. - */ -!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(e){return t="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},t(e)}function e(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=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 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(t){g[v[t]]=t}));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(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer},A=function(t,e,n){var r=t.type,i=t.data;return k&&i instanceof Blob?e?n(i):O(i,n):w&&(i instanceof ArrayBuffer||_(i))?e?n(i):O(new Blob([i]),n):n(v[r]+(i||""))},O=function(t,e){var n=new FileReader;return n.onload=function(){var t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function E(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.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(t,e){if("string"!=typeof t)return{type:"message",data:x(t,e)};var n=t.charAt(0);return"b"===n?{type:"message",data:L(t.substring(1),e)}:g[n]?t.length>1?{type:g[n],data:t.substring(1)}:{type:g[n]}:b},L=function(t,e){if(S){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>4,h[u++]=(15&r)<<4|i>>2,h[u++]=(3&i)<<6|63&o;return c}(t);return x(n,e)}return{base64:!0,data:t}},x=function(t,e){return"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer},P=String.fromCharCode(30);function q(){return new TransformStream({transform:function(t,e){!function(t,e){k&&t.data instanceof Blob?t.data.arrayBuffer().then(E).then(e):w&&(t.data instanceof ArrayBuffer||_(t.data))?e(E(t.data)):A(t,!1,(function(t){m||(m=new TextEncoder),e(m.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 j(t){return t.reduce((function(t,e){return t+e.length}),0)}function D(t,e){if(t[0].length===e)return t.shift();for(var n=new Uint8Array(e),r=0,i=0;i1?e-1:0),r=1;r1&&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:""}}]),i}(U),z="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),J=64,$={},Q=0,X=0;function G(t){var e="";do{e=z[t%J]+e,t=Math.floor(t/J)}while(t>0);return e}function Z(){var t=G(+new Date);return t!==K?(Q=0,K=t):t+"."+G(Q++)}for(;X0&&void 0!==arguments[0]?arguments[0]:{};return i(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new st(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}}]),s}(W),st=function(t){o(i,t);var n=l(i);function i(t,r){var o;return e(this,i),H(f(o=n.call(this)),r),o.opts=r,o.method=r.method||"GET",o.uri=t,o.data=void 0!==r.data?r.data:null,o.create(),o}return r(i,[{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 r=this.xhr=new nt(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(t){}if("POST"===this.method)try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{r.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.opts.cookieJar)||void 0===t||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=function(){var t;3===r.readyState&&(null===(t=e.opts.cookieJar)||void 0===t||t.parseCookies(r)),4===r.readyState&&(200===r.status||1223===r.status?e.onLoad():e.setTimeoutFn((function(){e.onError("number"==typeof r.status?r.status:0)}),0))},r.send(this.data)}catch(t){return void this.setTimeoutFn((function(){e.onError(t)}),0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.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=rt,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete i.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()}}]),i}(U);if(st.requestsCount=0,st.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",at);else if("function"==typeof addEventListener){addEventListener("onpagehide"in I?"pagehide":"unload",at,!1)}function at(){for(var t in st.requests)st.requests.hasOwnProperty(t)&&st.requests[t].abort()}var ut="function"==typeof Promise&&"function"==typeof Promise.resolve?function(t){return Promise.resolve().then(t)}:function(t,e){return e(t,0)},ct=I.WebSocket||I.MozWebSocket,ht="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),ft=function(t){o(i,t);var n=l(i);function i(t){var r;return e(this,i),(r=n.call(this,t)).supportsBinary=!t.forceBase64,r}return r(i,[{key:"name",get:function(){return"websocket"}},{key:"doOpen",value:function(){if(this.check()){var t=this.uri(),e=this.opts.protocols,n=ht?{}: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=ht?new ct(t,e,n):e?new ct(t,e):new ct(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;A(n,e.supportsBinary,(function(t){try{e.ws.send(t)}catch(t){}i&&ut((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;rMath.pow(2,21)-1){a.enqueue(b);break}i=l*Math.pow(2,32)+f.getUint32(4),r=3}else{if(j(n)t){a.enqueue(b);break}}}})}(Number.MAX_SAFE_INTEGER,t.socket.binaryType),r=e.readable.pipeThrough(n).getReader(),i=q();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&&ut((function(){e.writable=!0,e.emitReserved("drain")}),e.setTimeoutFn)}))},r=0;r1&&void 0!==arguments[1]?arguments[1]:{};return e(this,a),(r=s.call(this)).binaryType="arraybuffer",r.writeBuffer=[],n&&"object"===t(n)&&(o=n,n=null),n?(n=vt(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=vt(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(t){for(var e={},n=t.split("&"),r=0,i=n.length;r1))return this.writeBuffer;for(var t,e=1,n=0;n=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=0&&e.num1?e-1:0),r=1;r1?n-1:0),i=1;in._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;s0&&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:Bt.CONNECT,data:this._pid?i({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)}},{key:"onpacket",value:function(t){if(t.nsp===this.nsp)switch(t.type){case Bt.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 Bt.EVENT:case Bt.BINARY_EVENT:this.onevent(t);break;case Bt.ACK:case Bt.BINARY_ACK:this.onack(t);break;case Bt.DISCONNECT:this.ondisconnect();break;case Bt.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=y(this._anyListeners.slice());try{for(n.s();!(e=n.n()).done;){e.value.apply(this,t)}}catch(t){n.e(t)}finally{n.f()}}p(s(a.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;o0&&t.jitter<=1?t.jitter:0,this.attempts=0}It.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)},It.prototype.reset=function(){this.attempts=0},It.prototype.setMin=function(t){this.ms=t},It.prototype.setMax=function(t){this.max=t},It.prototype.setJitter=function(t){this.jitter=t};var Ft=function(n){o(s,n);var i=l(s);function s(n,r){var o,a;e(this,s),(o=i.call(this)).nsps={},o.subs=[],n&&"object"===t(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 It({min:o.reconnectionDelay(),max:o.reconnectionDelayMax(),jitter:o.randomizationFactor()}),o.timeout(null==r.timeout?2e4:r.timeout),o._readyState="closed",o.uri=n;var u=r.parser||qt;return o.encoder=new u.Encoder,o.decoder=new u.Decoder,o._autoConnect=!1!==r.autoConnect,o._autoConnect&&o.open(),o}return r(s,[{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 gt(this.uri,this.opts);var n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;var i=jt(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=jt(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(jt(t,"ping",this.onping.bind(this)),jt(t,"data",this.ondata.bind(this)),jt(t,"error",this.onerror.bind(this)),jt(t,"close",this.onclose.bind(this)),jt(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;ut((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 Ut(this,t,e),this.nsps[t]=n),n}},{key:"_destroy",value:function(t){for(var e=0,n=Object.keys(this.nsps);e=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)}}]),s}(U),Mt={};function Vt(e,n){"object"===t(e)&&(n=e,e=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=vt(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}(e,(n=n||{}).path||"/socket.io"),o=i.source,s=i.id,a=i.path,u=Mt[s]&&a in Mt[s].nsps;return n.forceNew||n["force new connection"]||!1===n.multiplex||u?r=new Ft(o,n):(Mt[s]||(Mt[s]=new Ft(o,n)),r=Mt[s]),i.query&&!n.query&&(n.query=i.queryKey),r.socket(i.path,n)}return i(Vt,{Manager:Ft,Socket:Ut,io:Vt,connect:Vt}),Vt})); -//# sourceMappingURL=socket.io.min.js.map diff --git a/src/puter-js/src/lib/socket.io/socket.io.msgpack.min.js b/src/puter-js/src/lib/socket.io/socket.io.msgpack.min.js deleted file mode 100644 index e103520998..0000000000 --- a/src/puter-js/src/lib/socket.io/socket.io.msgpack.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - * Socket.IO v4.7.2 - * (c) 2014-2023 Guillermo Rauch - * Released under the MIT License. - */ -!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;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n=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>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;i1?e-1:0),r=1;r1&&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(;Y0&&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;rMath.pow(2,21)-1){a.enqueue(b);break}i=l*Math.pow(2,32)+f.getUint32(4),r=3}else{if(D(n)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;r1&&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;r1))return this.writeBuffer;for(var t,e=1,n=0;n=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>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=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>>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>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;o0&&(u=n[0]._offset);for(var c,h=0,f=0,l=0,p=e.length;l=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=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;n1?e-1:0),r=1;r1?n-1:0),i=1;in._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;s0&&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)}},{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;o0&&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=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})); -//# sourceMappingURL=socket.io.msgpack.min.js.map diff --git a/src/puter-js/src/lib/utils.js b/src/puter-js/src/lib/utils.js index adb5e6f05e..f8a19cb76e 100644 --- a/src/puter-js/src/lib/utils.js +++ b/src/puter-js/src/lib/utils.js @@ -514,15 +514,6 @@ async function driverCall_ ( }).catch(reject_func); } -async function blob_to_url (blob) { - const reader = new (globalThis.FileReader || FileReaderPoly)(); - return await new Promise((resolve, reject) => { - reader.onloadend = () => resolve(reader.result); - reader.onerror = reject; - reader.readAsDataURL(blob); - }); -} - function blobToDataUri (blob) { return new Promise((resolve, reject) => { const reader = new (globalThis.FileReader || FileReaderPoly)(); @@ -536,20 +527,6 @@ function blobToDataUri (blob) { }); } -function arrayBufferToDataUri (arrayBuffer) { - return new Promise((resolve, reject) => { - const blob = new Blob([arrayBuffer]); - const reader = new (globalThis.FileReader || FileReaderPoly)(); - reader.onload = function (event) { - resolve(event.target.result); - }; - reader.onerror = function (error) { - reject(error); - }; - reader.readAsDataURL(blob); - }); -} - const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'mpeg', 'avi', 'mkv', 'm4v', 'ogv']; const isVideoInput = (url) => { @@ -560,5 +537,5 @@ const isVideoInput = (url) => { }; export { - arrayBufferToDataUri, blob_to_url, blobToDataUri, driverCall, handle_error, handle_resp, initXhr, isVideoInput, make_driver_method, parseResponse, setupXhrEventHandlers, uuidv4, + blobToDataUri, driverCall, handle_error, initXhr, isVideoInput, make_driver_method, parseResponse, setupXhrEventHandlers, uuidv4, }; diff --git a/src/puter-js/src/modules/Drivers.js b/src/puter-js/src/modules/Drivers.js index a959f6cd7d..dec1ba004a 100644 --- a/src/puter-js/src/modules/Drivers.js +++ b/src/puter-js/src/modules/Drivers.js @@ -169,17 +169,11 @@ class Drivers { const key = `${iface_name}:${service_name}`; if ( this.drivers_[key] ) return this.drivers_[key]; - // const interfaces = await this.list(); - // if ( ! interfaces[iface_name] ) { - // throw new Error(`Interface ${iface_name} not found`); - // } - return this.drivers_[key] = new Driver ({ call_backend: new FetchDriverCallBackend({ getAPIOrigin: () => this.APIOrigin, getAuthToken: () => this.authToken, }), - // iface: interfaces[iface_name], iface_name, service_name, }); diff --git a/src/puter-js/src/modules/FSItem.js b/src/puter-js/src/modules/FSItem.js index 01e75b3f17..c52d9d1eee 100644 --- a/src/puter-js/src/modules/FSItem.js +++ b/src/puter-js/src/modules/FSItem.js @@ -1,4 +1,4 @@ -import path from '../lib/path.js'; +import path from 'path-browserify'; class FSItem { constructor (options) { @@ -67,21 +67,6 @@ class FSItem { }); }; - // Watches for changes to the item, and calls the callback function - // with the new data when a change is detected. - watch = function (callback) { - // todo - implement - }; - - open = function (callback) { - // todo - implement - }; - - // Set wallpaper - setAsWallpaper = function (options, callback) { - // todo - implement - }; - rename = function (new_name) { return puter.fs.rename(this.uid, new_name); }; @@ -98,15 +83,6 @@ class FSItem { return puter.fs.delete(this.path); }; - versions = async function () { - // todo - implement - }; - - trash = function () { - // todo make sure puter allows for moving to trash by default - // todo implement trashing - }; - mkdir = async function (name, auto_rename = false) { // Don't proceed if this is not a directory, throw error if ( ! this.isDirectory ) @@ -118,10 +94,6 @@ class FSItem { return puter.fs.mkdir(path.join(this.path, name)); }; - metadata = async function () { - // todo - implement - }; - readdir = async function () { // Don't proceed if this is not a directory, throw error if ( ! this.isDirectory ) diff --git a/src/puter-js/src/modules/FileSystem/Batch.js b/src/puter-js/src/modules/FileSystem/Batch.js deleted file mode 100644 index 70e0558937..0000000000 --- a/src/puter-js/src/modules/FileSystem/Batch.js +++ /dev/null @@ -1,49 +0,0 @@ -import { fetchUrl } from '../../lib/networkUtils.js'; - -export default puter => class Batch { - constructor () { - this.form = new FormData(); - this.operations = []; - } - - move (source, destination, new_name) { - this.operations.push({ - op: 'move', - source, - destination, - new_name, - }); - return this; // for chaining - } - - // alias for `delete` - rm (...a) { - return this.delete(...a); - } - - delete (...paths) { - for ( const path of paths ) { - this.operations.push({ - op: 'delete', - path, - }); - } - } - - async send () { - // Prepare Form - for ( const operation of this.operations ) { - this.form.append('operation', JSON.stringify(operation)); - } - - // Send Request. The Content-Type (multipart boundary) is set by the - // transport from the FormData body, so it is not passed explicitly. - const res = await fetchUrl(`${puter.APIOrigin}/batch`, { - method: 'POST', - includePuterAuth: true, - body: this.form, - }); - - return (await res.json())?.results; - } -}; diff --git a/src/puter-js/src/modules/FileSystem/index.js b/src/puter-js/src/modules/FileSystem/index.js index 112478e317..99f04affc4 100644 --- a/src/puter-js/src/modules/FileSystem/index.js +++ b/src/puter-js/src/modules/FileSystem/index.js @@ -1,5 +1,5 @@ -import path from '../../lib/path.js'; -import io from '../../lib/socket.io/socket.io.esm.min.js'; +import path from 'path-browserify'; +import { io } from 'socket.io-client'; import * as utils from '../../lib/utils.js'; // Constants @@ -9,7 +9,6 @@ const LAST_VALID_TS = 'last_valid_ts'; // Operations import FSItem from '../FSItem.js'; -import Batch from './Batch.js'; import copy from './operations/copy.js'; import deleteFSEntry from './operations/deleteFSEntry.js'; import getReadURL from './operations/getReadUrl.js'; @@ -59,23 +58,12 @@ export class PuterJSFileSystemModule { */ constructor (puter) { this.puter = puter; - this.Batch = Batch(puter); this.authToken = puter.authToken; this.APIOrigin = puter.APIOrigin; this.appID = puter.appID; this.cacheUpdateTimer = null; // Connect socket. this.initializeSocket(); - - // We need to use `Object.defineProperty` instead of passing - // `authToken` and `APIOrigin` because they will change. - const api_info = {}; - Object.defineProperty(api_info, 'authToken', { - get: () => this.authToken, - }); - Object.defineProperty(api_info, 'APIOrigin', { - get: () => this.APIOrigin, - }); } /** diff --git a/src/puter-js/src/modules/FileSystem/operations/mkdir.js b/src/puter-js/src/modules/FileSystem/operations/mkdir.js index 5136ec39de..8ef2339ef7 100644 --- a/src/puter-js/src/modules/FileSystem/operations/mkdir.js +++ b/src/puter-js/src/modules/FileSystem/operations/mkdir.js @@ -1,4 +1,4 @@ -import path from '../../../lib/path.js'; +import path from 'path-browserify'; import * as utils from '../../../lib/utils.js'; import getAbsolutePathForApp from '../utils/getAbsolutePathForApp.js'; diff --git a/src/puter-js/src/modules/FileSystem/operations/move.js b/src/puter-js/src/modules/FileSystem/operations/move.js index 4ee28c5050..5705e74f48 100644 --- a/src/puter-js/src/modules/FileSystem/operations/move.js +++ b/src/puter-js/src/modules/FileSystem/operations/move.js @@ -1,4 +1,4 @@ -import path from '../../../lib/path.js'; +import path from 'path-browserify'; import * as utils from '../../../lib/utils.js'; import getAbsolutePathForApp from '../utils/getAbsolutePathForApp.js'; import stat from './stat.js'; diff --git a/src/puter-js/src/modules/FileSystem/operations/upload/entries.js b/src/puter-js/src/modules/FileSystem/operations/upload/entries.js index e6b24531f1..ff4265cb70 100644 --- a/src/puter-js/src/modules/FileSystem/operations/upload/entries.js +++ b/src/puter-js/src/modules/FileSystem/operations/upload/entries.js @@ -1,7 +1,7 @@ // Normalize the many accepted `upload()` input shapes into a flat list of // entries, then split that list into the directories and files to create. -import path from '../../../../lib/path.js'; +import path from 'path-browserify'; /** * Split an array into fixed-size chunks. Returns an empty array for empty or diff --git a/src/puter-js/src/modules/FileSystem/operations/upload/legacyBatchUpload.js b/src/puter-js/src/modules/FileSystem/operations/upload/legacyBatchUpload.js index b1ed5c91e6..2735d680e5 100644 --- a/src/puter-js/src/modules/FileSystem/operations/upload/legacyBatchUpload.js +++ b/src/puter-js/src/modules/FileSystem/operations/upload/legacyBatchUpload.js @@ -4,7 +4,7 @@ // batch writes are unavailable or unsupported in the current environment. // Invoked with the FileSystem module as `this`. -import path from '../../../../lib/path.js'; +import path from 'path-browserify'; import * as utils from '../../../../lib/utils.js'; import { normalizeThumbnailData } from './thumbnails.js'; diff --git a/src/puter-js/src/modules/FileSystem/operations/upload/signedBatchUpload.js b/src/puter-js/src/modules/FileSystem/operations/upload/signedBatchUpload.js index 1f0cbe766f..216108908b 100644 --- a/src/puter-js/src/modules/FileSystem/operations/upload/signedBatchUpload.js +++ b/src/puter-js/src/modules/FileSystem/operations/upload/signedBatchUpload.js @@ -3,7 +3,7 @@ // URLs (single-shot or multipart), then finalized (`/fs/completeBatchWrite`). // Invoked with the FileSystem module as `this`. -import path from '../../../../lib/path.js'; +import path from 'path-browserify'; import { MAX_THUMBNAIL_BYTES, SIGNED_BATCH_WRITE_CAPABILITY_KEY, diff --git a/src/puter-js/src/modules/FileSystem/operations/write.js b/src/puter-js/src/modules/FileSystem/operations/write.js index 847ec5ffa5..13505a7cb5 100644 --- a/src/puter-js/src/modules/FileSystem/operations/write.js +++ b/src/puter-js/src/modules/FileSystem/operations/write.js @@ -1,4 +1,4 @@ -import path from '../../../lib/path.js'; +import path from 'path-browserify'; import getAbsolutePathForApp from '../utils/getAbsolutePathForApp.js'; const write = async function (targetPath, data, options = {}) { diff --git a/src/puter-js/src/modules/FileSystem/utils/getAbsolutePathForApp.js b/src/puter-js/src/modules/FileSystem/utils/getAbsolutePathForApp.js index 3e70bb0826..86c7ab3f55 100644 --- a/src/puter-js/src/modules/FileSystem/utils/getAbsolutePathForApp.js +++ b/src/puter-js/src/modules/FileSystem/utils/getAbsolutePathForApp.js @@ -1,4 +1,4 @@ -import path from '../../../lib/path.js'; +import path from 'path-browserify'; const getAbsolutePathForApp = (relativePath, puter = globalThis.puter) => { // preserve previous behavior for falsy values when env is gui diff --git a/src/puter-js/src/modules/ai/ai.test.js b/src/puter-js/src/modules/ai/ai.test.js index c5aaeae38d..0fd5a3b020 100644 --- a/src/puter-js/src/modules/ai/ai.test.js +++ b/src/puter-js/src/modules/ai/ai.test.js @@ -70,7 +70,7 @@ const makeFakePuter = () => ({ }, }); -// Minimal FileReader for node: only what blobToDataUri / blob_to_url use. +// Minimal FileReader for node: only what blobToDataUri uses. class FakeFileReader { readAsDataURL (blob) { blob.arrayBuffer().then((buf) => { diff --git a/src/puter-js/src/modules/ai/lib/media.js b/src/puter-js/src/modules/ai/lib/media.js index 4bfe195c9d..6b8c158a4e 100644 --- a/src/puter-js/src/modules/ai/lib/media.js +++ b/src/puter-js/src/modules/ai/lib/media.js @@ -13,14 +13,14 @@ const resultToUrl = async (result, error) => { return result; } if ( result instanceof Blob ) { - return await utils.blob_to_url(result); + return await utils.blobToDataUri(result); } if ( result instanceof ArrayBuffer ) { - return await utils.blob_to_url(new Blob([result])); + return await utils.blobToDataUri(new Blob([result])); } if ( result && typeof result === 'object' && typeof result.arrayBuffer === 'function' ) { const arrayBuffer = await result.arrayBuffer(); - return await utils.blob_to_url(new Blob([arrayBuffer], { type: result.type || undefined })); + return await utils.blobToDataUri(new Blob([arrayBuffer], { type: result.type || undefined })); } throw error; }; @@ -66,7 +66,7 @@ export const toVideoElement = async (result) => { let sourceUrl = null; let mimeType = null; if ( result instanceof Blob ) { - sourceUrl = await utils.blob_to_url(result); + sourceUrl = await utils.blobToDataUri(result); mimeType = result.type || 'video/mp4'; } else if ( typeof result === 'string' ) { sourceUrl = result; diff --git a/src/puter-js/tests/api/suites/fs.suite.ts b/src/puter-js/tests/api/suites/fs.suite.ts index 04011c9e38..913746ce45 100644 --- a/src/puter-js/tests/api/suites/fs.suite.ts +++ b/src/puter-js/tests/api/suites/fs.suite.ts @@ -386,21 +386,6 @@ export default suite('fs', { ); }, - 'batch send applies move and delete operations': async (t) => { - const dir = `${home(t)}/fs-suite-batch`; - await t.puter.fs.mkdir(dir); - await t.puter.fs.write(`${dir}/moved.txt`, 'batch move'); - await t.puter.fs.write(`${dir}/removed.txt`, 'batch delete'); - const batch = new t.puter.fs.Batch(); - batch.move(`${dir}/moved.txt`, dir, 'moved-renamed.txt'); - batch.delete(`${dir}/removed.txt`); - const results = await batch.send(); - t.assert.ok(Array.isArray(results), 'batch should return results'); - const blob = await t.puter.fs.read(`${dir}/moved-renamed.txt`); - t.assert.equal(await blob.text(), 'batch move'); - await t.assert.rejects(() => t.puter.fs.stat(`${dir}/removed.txt`)); - }, - 'upload stores multiple files into a directory': async (t) => { const dir = `${home(t)}/fs-suite-upload`; await t.puter.fs.mkdir(dir); diff --git a/src/puter-js/types/modules/fs-item.d.ts b/src/puter-js/types/modules/fs-item.d.ts index 6204d37c8e..e47f615c87 100644 --- a/src/puter-js/types/modules/fs-item.d.ts +++ b/src/puter-js/types/modules/fs-item.d.ts @@ -61,12 +61,4 @@ export class FSItem { readdir (): Promise; /** Reads the contents of the file. Resolves to a `Blob` containing the file's contents. */ read (): Promise; - - // Placeholders that are not implemented in the runtime SDK yet. - watch (callback: (item: FSItem) => void): void; - open (callback: (item: FSItem) => void): void; - setAsWallpaper (options?: Record, callback?: () => void): void; - versions (): Promise; - trash (): Promise; - metadata (): Promise; } diff --git a/src/puter-js/webpack.config.js b/src/puter-js/webpack.config.js index acb7221614..e0312d1e2b 100644 --- a/src/puter-js/webpack.config.js +++ b/src/puter-js/webpack.config.js @@ -19,14 +19,13 @@ export default (env = {}) => ({ // `--env coverage` instruments every first-party module with istanbul // counters (accumulated on `globalThis.__coverage__`), so the API test // harness can measure SDK coverage in whatever runtime executes the - // bundle. Vendored code (socket.io) is left out of the numbers. + // bundle. ...(env.coverage ? { module: { rules: [ { test: /\.js$/, include: path.resolve(__dirname, 'src'), - exclude: path.resolve(__dirname, 'src/lib/socket.io'), use: { loader: 'babel-loader', options: {