Move to ES6 module (#357)

* Redo imports and exports for lib

* Redo imports and exports for bim

* Redo imports and exports for games

* Remove remaining module.exports

* Use export default in lib

* Use export default in protocols

* Fix import in genreadme.js

* Make package module and solve __dirname

* Fix minecraft protocol imports

* Fix imports on games and make binary runnable

* Renamed protocol class exports to lowercase

* Export promises class as default

* Update README.md to use imports instead of require

* Update CHANGELOG to mention the changes.

* Remove Valve unused imports

* Fix iconv import
This commit is contained in:
CosminPerRam 2023-09-14 23:28:31 +03:00 committed by GitHub
parent b4f6e7fab6
commit ad9adff06c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
64 changed files with 249 additions and 323 deletions

View file

@ -1,11 +1,11 @@
const dns = require('dns'),
Logger = require('./Logger'),
util = require('util'),
dnsLookupAsync = util.promisify(dns.lookup),
dnsResolveAsync = util.promisify(dns.resolve),
punycode = require('punycode');
import * as dns from 'dns';
import * as punycode from "punycode";
import { promisify } from "util";
class DnsResolver {
const dnsLookupAsync = promisify(dns.lookup);
const dnsResolveAsync = promisify(dns.resolve);
export default class DnsResolver {
/**
* @param {Logger} logger
*/
@ -76,5 +76,3 @@ class DnsResolver {
return {address: address};
}
}
module.exports = DnsResolver;

View file

@ -1,7 +1,8 @@
const Path = require('path'),
fs = require('fs');
import * as path from 'path';
import { fileURLToPath } from "url";
import * as fs from 'fs';
class GameResolver {
export default class GameResolver {
constructor() {
const loaded = this._readGames();
this.gamesByKey = loaded.gamesByKey;
@ -56,7 +57,9 @@ class GameResolver {
}
_readGames() {
const gamesFile = Path.normalize(__dirname+'/../games.txt');
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const gamesFile = path.normalize(__dirname+'/../games.txt');
const lines = fs.readFileSync(gamesFile,'utf8').split('\n');
const gamesByKey = new Map();
@ -117,5 +120,3 @@ class GameResolver {
return out;
}
}
module.exports = GameResolver;

View file

@ -1,9 +1,10 @@
const dgram = require('dgram');
const HexUtil = require('./HexUtil');
const Logger = require('./Logger');
const util = require('util');
class GlobalUdpSocket {
import { createSocket } from "dgram";
import { debugDump } from "./HexUtil.js";
import { promisify } from "util";
import Logger from "./Logger.js";
export default class GlobalUdpSocket {
constructor({port}) {
this.socket = null;
this.callbacks = new Set();
@ -14,7 +15,7 @@ class GlobalUdpSocket {
async _getSocket() {
if (!this.socket) {
const udpSocket = dgram.createSocket({
const udpSocket = createSocket({
type: 'udp4',
reuseAddr: true
});
@ -24,7 +25,7 @@ class GlobalUdpSocket {
const fromPort = rinfo.port;
this.logger.debug(log => {
log(fromAddress + ':' + fromPort + " <--UDP(" + this.port + ")");
log(HexUtil.debugDump(buffer));
log(debugDump(buffer));
});
for (const callback of this.callbacks) {
callback(fromAddress, fromPort, buffer);
@ -33,7 +34,7 @@ class GlobalUdpSocket {
udpSocket.on('error', e => {
this.logger.debug("UDP ERROR:", e);
});
await util.promisify(udpSocket.bind).bind(udpSocket)(this.port);
await promisify(udpSocket.bind).bind(udpSocket)(this.port);
this.port = udpSocket.address().port;
this.socket = udpSocket;
}
@ -46,11 +47,11 @@ class GlobalUdpSocket {
if (debug) {
this.logger._print(log => {
log(address + ':' + port + " UDP(" + this.port + ")-->");
log(HexUtil.debugDump(buffer));
log(debugDump(buffer));
});
}
await util.promisify(socket.send).bind(socket)(buffer,0,buffer.length,port,address);
await promisify(socket.send).bind(socket)(buffer,0,buffer.length,port,address);
}
addCallback(callback, debug) {
@ -66,5 +67,3 @@ class GlobalUdpSocket {
this.logger.debugEnabled = this.debuggingCallbacks.size > 0;
}
}
module.exports = GlobalUdpSocket;

View file

@ -1,24 +1,21 @@
class HexUtil {
/** @param {Buffer} buffer */
static debugDump(buffer) {
let hexLine = '';
let chrLine = '';
let out = '';
out += "Buffer length: " + buffer.length + " bytes\n";
for(let i = 0; i < buffer.length; i++) {
const sliced = buffer.slice(i,i+1);
hexLine += sliced.toString('hex')+' ';
let chr = sliced.toString();
if(chr < ' ' || chr > '~') chr = ' ';
chrLine += chr+' ';
if(hexLine.length > 60 || i === buffer.length - 1) {
out += hexLine + '\n';
out += chrLine + '\n';
hexLine = chrLine = '';
}
}
return out;
}
}
module.exports = HexUtil;
/** @param {Buffer} buffer */
export const debugDump = (buffer) => {
let hexLine = '';
let chrLine = '';
let out = '';
out += "Buffer length: " + buffer.length + " bytes\n";
for(let i = 0; i < buffer.length; i++) {
const sliced = buffer.slice(i,i+1);
hexLine += sliced.toString('hex')+' ';
let chr = sliced.toString();
if(chr < ' ' || chr > '~') chr = ' ';
chrLine += chr+' ';
if(hexLine.length > 60 || i === buffer.length - 1) {
out += hexLine + '\n';
out += chrLine + '\n';
hexLine = chrLine = '';
}
}
return out;
}

View file

@ -1,6 +1,6 @@
const HexUtil = require('./HexUtil');
import {debugDump} from './HexUtil.js';
class Logger {
export default class Logger {
constructor() {
this.debugEnabled = false;
this.prefix = '';
@ -31,7 +31,7 @@ class Logger {
if (arg instanceof Error) {
out.push(arg.stack);
} else if (arg instanceof Buffer) {
out.push(HexUtil.debugDump(arg));
out.push(debugDump(arg));
} else if (typeof arg == 'function') {
const result = arg.call(undefined, (...args) => this._print(...args));
if (result !== undefined) out.push(...this._convertArgsToStrings(result));
@ -42,5 +42,3 @@ class Logger {
return out;
}
}
module.exports = Logger;

View file

@ -1,4 +1,4 @@
class Promises {
export default class Promises {
static createTimeout(timeoutMs, timeoutMsg) {
let cancel = null;
const wrapped = new Promise((res, rej) => {
@ -16,5 +16,3 @@ class Promises {
return wrapped;
}
}
module.exports = Promises;

View file

@ -1,22 +1,8 @@
const Path = require('path'),
fs = require('fs'),
Core = require('../protocols/core');
import * as Protocols from '../protocols/index.js'
class ProtocolResolver {
constructor() {
this.protocolDir = Path.normalize(__dirname+'/../protocols');
}
export const getProtocol = (protocolId) => {
if(!(protocolId in Protocols))
throw Error('Protocol definition file missing: ' + protocolId);
/**
* @returns Core
*/
create(protocolId) {
protocolId = Path.basename(protocolId);
const path = this.protocolDir+'/'+protocolId;
if(!fs.existsSync(path+'.js')) throw Error('Protocol definition file missing: '+type);
const protocol = require(path);
return new protocol();
}
return new Protocols[protocolId];
}
module.exports = ProtocolResolver;

View file

@ -1,6 +1,6 @@
const GameResolver = require('./GameResolver'),
ProtocolResolver = require('./ProtocolResolver'),
GlobalUdpSocket = require('./GlobalUdpSocket');
import GameResolver from "./GameResolver.js";
import {getProtocol} from './ProtocolResolver.js';
import GlobalUdpSocket from "./GlobalUdpSocket.js";
const defaultOptions = {
socketTimeout: 2000,
@ -9,13 +9,12 @@ const defaultOptions = {
ipFamily: 0
};
class QueryRunner {
export default class QueryRunner {
constructor(runnerOpts = {}) {
this.udpSocket = new GlobalUdpSocket({
port: runnerOpts.listenUdpPort
});
this.gameResolver = new GameResolver();
this.protocolResolver = new ProtocolResolver();
}
async run(userOptions) {
@ -90,11 +89,9 @@ class QueryRunner {
}
async _attempt(options) {
const core = this.protocolResolver.create(options.protocol);
const core = getProtocol(options.protocol);
core.options = options;
core.udpSocket = this.udpSocket;
return await core.runOnceSafe();
}
}
module.exports = QueryRunner;

View file

@ -1,4 +1,5 @@
class Player {
export class Player {
name = '';
raw = {};
@ -13,7 +14,7 @@ class Player {
}
}
class Players extends Array {
export class Players extends Array {
setNum(num) {
// If the server specified some ridiculous number of players (billions), we don't want to
// run out of ram allocating these objects.
@ -29,7 +30,7 @@ class Players extends Array {
}
}
class Results {
export class Results {
name = '';
map = '';
password = false;
@ -40,5 +41,3 @@ class Results {
players = new Players();
bots = new Players();
}
module.exports = Results;

View file

@ -1,8 +1,8 @@
const QueryRunner = require('./QueryRunner');
import QueryRunner from './QueryRunner.js';
let singleton = null;
class Gamedig {
export default class Gamedig {
constructor(runnerOpts) {
this.queryRunner = new QueryRunner(runnerOpts);
}
@ -22,5 +22,3 @@ class Gamedig {
return await Gamedig.getInstance().query(...args);
}
}
module.exports = Gamedig;

View file

@ -1,8 +1,7 @@
const Iconv = require('iconv-lite'),
Long = require('long'),
Core = require('../protocols/core'),
Buffer = require('buffer'),
Varint = require('varint');
import Iconv from "iconv-lite";
import Long from 'long';
import {Buffer} from "buffer";
import Varint from 'varint';
function readUInt64BE(buffer,offset) {
const high = buffer.readUInt32BE(offset);
@ -15,7 +14,7 @@ function readUInt64LE(buffer,offset) {
return new Long(low,high,true);
}
class Reader {
export default class Reader {
/**
* @param {Core} query
* @param {Buffer} buffer
@ -171,5 +170,3 @@ class Reader {
return this.i >= this.buffer.length;
}
}
module.exports = Reader;