update internal utils to core-utils package #489

Merged
Sirherobrine23 merged 1 commits from migratePackages into main 2022-11-07 19:09:34 +00:00
23 changed files with 115 additions and 567 deletions

88
package-lock.json generated
View File

@ -9,16 +9,14 @@
"version": "5.2.0",
"license": "GPL-3.0",
"dependencies": {
"@the-bds-maneger/core-utils": "^1.0.0",
"@the-bds-maneger/server_versions": "^4.2.0",
"adm-zip": "^0.5.9",
"cron": "^2.1.0",
"got": "^12.5.2",
"prismarine-nbt": "^2.2.1",
"tar": "^6.1.12"
},
"devDependencies": {
"@types/adm-zip": "^0.5.0",
"@types/cron": "^2.0.0",
"@types/mocha": "^10.0.0",
"@types/node": "^18.11.9",
"@types/tar": "^6.1.3",
@ -1103,6 +1101,19 @@
"node": ">=14.16"
}
},
"node_modules/@the-bds-maneger/core-utils": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@the-bds-maneger/core-utils/-/core-utils-1.0.0.tgz",
"integrity": "sha512-GyVy1QLMWQ/utJ0TVOViZHzE3RI04SSvy/ErzKPuOqzjTDqvAeZvXP7WEzcr1huj1z8YIw5OBDkiwX2ki6GGzw==",
"dependencies": {
"adm-zip": "^0.5.9",
"got": "^12.5.2",
"tar": "^6.1.12"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@the-bds-maneger/server_versions": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@the-bds-maneger/server_versions/-/server_versions-4.2.0.tgz",
@ -1161,27 +1172,11 @@
"@types/node": "*"
}
},
"node_modules/@types/cron": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@types/cron/-/cron-2.0.0.tgz",
"integrity": "sha512-xZM08fqvwIXgghtPVkSPKNgC+JoMQ2OHazEvyTKnNf7aWu1aB6/4lBbQFrb03Td2cUGG7ITzMv3mFYnMu6xRaQ==",
"dev": true,
"dependencies": {
"@types/luxon": "*",
"@types/node": "*"
}
},
"node_modules/@types/http-cache-semantics": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz",
"integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ=="
},
"node_modules/@types/luxon": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.1.0.tgz",
"integrity": "sha512-gCd/HcCgjqSxfMrgtqxCgYk/22NBQfypwFUG7ZAyG/4pqs51WLTcUzVp1hqTbieDYeHS3WoVEh2Yv/2l+7B0Vg==",
"dev": true
},
"node_modules/@types/mocha": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.0.tgz",
@ -1732,14 +1727,6 @@
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true
},
"node_modules/cron": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cron/-/cron-2.1.0.tgz",
"integrity": "sha512-Hq7u3P8y7UWYvsZbSKHHJDVG0VO9O7tp2qljxzTScelcTODBfCme8AIhnZsFwmQ9NchZ3hr2uNr+s3DSms7q6w==",
"dependencies": {
"luxon": "^1.23.x"
}
},
"node_modules/cssom": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
@ -2780,14 +2767,6 @@
"integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==",
"dev": true
},
"node_modules/luxon": {
"version": "1.28.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz",
"integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ==",
"engines": {
"node": "*"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
@ -5165,6 +5144,16 @@
"defer-to-connect": "^2.0.1"
}
},
"@the-bds-maneger/core-utils": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@the-bds-maneger/core-utils/-/core-utils-1.0.0.tgz",
"integrity": "sha512-GyVy1QLMWQ/utJ0TVOViZHzE3RI04SSvy/ErzKPuOqzjTDqvAeZvXP7WEzcr1huj1z8YIw5OBDkiwX2ki6GGzw==",
"requires": {
"adm-zip": "^0.5.9",
"got": "^12.5.2",
"tar": "^6.1.12"
}
},
"@the-bds-maneger/server_versions": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/@the-bds-maneger/server_versions/-/server_versions-4.2.0.tgz",
@ -5217,27 +5206,11 @@
"@types/node": "*"
}
},
"@types/cron": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@types/cron/-/cron-2.0.0.tgz",
"integrity": "sha512-xZM08fqvwIXgghtPVkSPKNgC+JoMQ2OHazEvyTKnNf7aWu1aB6/4lBbQFrb03Td2cUGG7ITzMv3mFYnMu6xRaQ==",
"dev": true,
"requires": {
"@types/luxon": "*",
"@types/node": "*"
}
},
"@types/http-cache-semantics": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz",
"integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ=="
},
"@types/luxon": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/luxon/-/luxon-3.1.0.tgz",
"integrity": "sha512-gCd/HcCgjqSxfMrgtqxCgYk/22NBQfypwFUG7ZAyG/4pqs51WLTcUzVp1hqTbieDYeHS3WoVEh2Yv/2l+7B0Vg==",
"dev": true
},
"@types/mocha": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.0.tgz",
@ -5644,14 +5617,6 @@
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true
},
"cron": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/cron/-/cron-2.1.0.tgz",
"integrity": "sha512-Hq7u3P8y7UWYvsZbSKHHJDVG0VO9O7tp2qljxzTScelcTODBfCme8AIhnZsFwmQ9NchZ3hr2uNr+s3DSms7q6w==",
"requires": {
"luxon": "^1.23.x"
}
},
"cssom": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/cssom/-/cssom-0.5.0.tgz",
@ -6391,11 +6356,6 @@
"integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==",
"dev": true
},
"luxon": {
"version": "1.28.0",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-1.28.0.tgz",
"integrity": "sha512-TfTiyvZhwBYM/7QdAVDh+7dBTBA29v4ik0Ce9zda3Mnf8on1S5KJI8P2jKFZ8+5C0jhmr0KwJEO/Wdpm0VeWJQ=="
},
"make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",

View File

@ -16,7 +16,7 @@
"docs": "typedoc --readme none --out docs src/index.ts",
"dev": "nodemon",
"build": "tsc",
"test:partial": "mocha -r ts-node/register -r tsconfig-paths/register --exit",
"test:partial": "mocha -r ts-node/register --exit",
"test": "npm run test:partial -- 'tests/**/*.ts'"
},
"repository": {
@ -32,16 +32,14 @@
"node": ">=16.0.0"
},
"dependencies": {
"@the-bds-maneger/core-utils": "^1.0.0",
"@the-bds-maneger/server_versions": "^4.2.0",
"adm-zip": "^0.5.9",
"cron": "^2.1.0",
"got": "^12.5.2",
"prismarine-nbt": "^2.2.1",
"tar": "^6.1.12"
},
"devDependencies": {
"@types/adm-zip": "^0.5.0",
"@types/cron": "^2.0.0",
"@types/mocha": "^10.0.0",
"@types/node": "^18.11.9",
"@types/tar": "^6.1.3",

View File

@ -1,14 +1,12 @@
import { platformManeger } from "@the-bds-maneger/server_versions";
import { manegerConfigProprieties } from "./configManipulate";
import { randomPort } from "./lib/randomPort";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import * as globalPlatfroms from "./globalPlatfroms";
import * as coreUtils from "@the-bds-maneger/core-utils";
import path from "node:path";
import fsOld from "node:fs";
import fs from "node:fs/promises";
import * as globalPlatfroms from "./globalPlatfroms";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import { commendExists } from "./lib/childPromisses";
import * as httpLarge from "@http/large";
import extendsFs, { exists, readdirrecursive } from "./lib/extendsFs";
import { randomPort } from "./lib/randomPort";
import { manegerConfigProprieties } from "./configManipulate";
// RegExp
export const saveFileFolder = /^(worlds|server\.properties|config|((permissions|allowlist|valid_known_packs)\.json)|(development_.*_packs))$/;
@ -28,7 +26,7 @@ export async function installServer(version: string|boolean, platformOptions: bd
await fs.readdir(serverPath).then(files => Promise.all(files.filter(file => !saveFileFolder.test(file)).map(file => fs.rm(path.join(serverPath, file), {recursive: true, force: true}))));
const serverConfigProperties = (await fs.readFile(path.join(serverPath, "server.properties"), "utf8").catch(() => "")).trim();
await httpLarge.extractZip({url, folderTarget: serverPath});
await coreUtils.httpRequestLarge.extractZip({url, folderTarget: serverPath});
if (serverConfigProperties) await fs.writeFile(path.join(serverPath, "server.properties"), serverConfigProperties);
await fs.writeFile(path.join(serverRoot, "version_installed.json"), JSON.stringify({version: bedrockData.version, date: bedrockData.date, installDate: new Date()}));
@ -57,9 +55,9 @@ export async function startServer(platformOptions: bdsPlatformOptions = {id: "de
let command = path.join(serverPath, "bedrock_server");
if ((["android", "linux"]).includes(process.platform) && process.arch !== "x64") {
args.push(command);
if (await commendExists("qemu-x86_64-static")) command = "qemu-x86_64-static";
else if (await commendExists("qemu-x86_64")) command = "qemu-x86_64";
else if (await commendExists("box64")) command = "box64";
if (await coreUtils.customChildProcess.commendExists("qemu-x86_64-static")) command = "qemu-x86_64-static";
else if (await coreUtils.customChildProcess.commendExists("qemu-x86_64")) command = "qemu-x86_64";
else if (await coreUtils.customChildProcess.commendExists("box64")) command = "box64";
else throw new Error("Cannot emulate x64 architecture. Check the documentents in \"https://github.com/The-Bds-Maneger/Bds-Maneger-Core/wiki/Server-Platforms#minecraft-bedrock-server-alpha\"");
}
const backendStart = new Date();
@ -161,7 +159,7 @@ export type bedrockConfig = {
export async function serverConfig(platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("bedrock", platformOptions);
const fileProperties = path.join(serverPath, "server.properties");
if (!await extendsFs.exists(fileProperties)) await fs.cp(path.join(__dirname, "../configs/java/server.properties"), fileProperties);
if (!await coreUtils.extendFs.exists(fileProperties)) await fs.cp(path.join(__dirname, "../configs/java/server.properties"), fileProperties);
return manegerConfigProprieties<editConfig, bedrockConfig>({
configPath: fileProperties,
configManipulate: {
@ -277,9 +275,9 @@ export type resourceManifest = {
export async function addResourcePacksToWorld(resourceId: string, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("bedrock", platformOptions);
const serverConfigObject = (await serverConfig(platformOptions)).getConfig();
if (!await exists(path.join(serverPath, "worlds", serverConfigObject["level-name"], "world_resource_packs.json"))) await fs.writeFile(path.join(serverPath, "worlds", serverConfigObject["level-name"], "world_resource_packs.json"), "[]");
if (!await coreUtils.extendFs.exists(path.join(serverPath, "worlds", serverConfigObject["level-name"], "world_resource_packs.json"))) await fs.writeFile(path.join(serverPath, "worlds", serverConfigObject["level-name"], "world_resource_packs.json"), "[]");
const resourcesData: resourcePacks[] = JSON.parse(await fs.readFile(path.join(serverPath, "worlds", serverConfigObject["level-name"], "world_resource_packs.json"), "utf8"));
const manifests: resourceManifest[] = await Promise.all((await readdirrecursive([path.join(serverPath, "resource_packs"), path.join(serverPath, "worlds", serverConfigObject["level-name"], "resource_packs")])).filter((file: string) => file.endsWith("manifest.json")).map(async (file: string) => JSON.parse(await fs.readFile(file, "utf8"))));
const manifests: resourceManifest[] = await Promise.all((await coreUtils.extendFs.readdirrecursive([path.join(serverPath, "resource_packs"), path.join(serverPath, "worlds", serverConfigObject["level-name"], "resource_packs")])).filter((file: string) => file.endsWith("manifest.json")).map(async (file: string) => JSON.parse(await fs.readFile(file, "utf8"))));
const packInfo = manifests.find(pf => pf.header.uuid === resourceId);
if (!packInfo) throw new Error("UUID to texture not installed in the server");
if (resourcesData.includes({pack_id: resourceId})) throw new Error("Textura alredy installed in the World");

View File

@ -1,10 +1,9 @@
import * as coreUtils from "@the-bds-maneger/core-utils";
import net from "node:net";
import crypto from "node:crypto";
import fs from "node:fs/promises";
import tar from "tar";
import { bdsRoot } from "./platformPathManeger";
import { exists } from "./lib/extendsFs";
import { getExternalIP } from "@http/client";
export type payload = {
httpVersion?: string,
@ -123,7 +122,7 @@ export class exportBds {
public async listen(port = 0) {
return new Promise<number>(done => {
this.#server.listen(port, async () => {
const externalIP = await getExternalIP();
const externalIP = await coreUtils.httpRequestClient.getExternalIP();
let address = this.#server.address()["address"], port = this.#server.address()["port"];
if (/::/.test(address)) address = `[${address}]`;
console.log("auth token '%s'", this.authToken);
@ -143,7 +142,7 @@ export class exportBds {
}
export async function importBds(option: {host: string, port: number, authToken: string}) {
if (await exists(bdsRoot)) await fs.rename(bdsRoot, bdsRoot+"_backup_"+Date.now());
if (await coreUtils.extendFs.exists(bdsRoot)) await fs.rename(bdsRoot, bdsRoot+"_backup_"+Date.now());
const {socket} = await parsePayload(stringifyPayload(net.createConnection({host: option.host, port: option.port}), {request: {method: "GET", path: "/"}, header: {Authorization: option.authToken}}));
console.info("Connection sucess!");
const tar_extract = tar.extract({cwd: bdsRoot, noChmod: false, noMtime: false, preserveOwner: true});

View File

@ -1,10 +1,3 @@
// HTTP
import * as httpSimples from "@http/simples";
import * as httpLarge from "@http/large";
import * as httpGithub from "@http/github";
import * as httpClient from "@http/client";
const httpRequest = {httpSimples, httpLarge, httpGithub, httpClient};
// Utils
import * as platformPathManeger from "./platformPathManeger"
import * as globalPlatfroms from "./globalPlatfroms";
@ -21,7 +14,7 @@ import * as Spigot from "./spigot";
import * as Powernukkit from "./pwnuukit";
import * as PaperMC from "./paper";
export {platformPathManeger, globalPlatfroms, pluginManeger, export_import, httpRequest, PocketmineMP, pluginHooks, Powernukkit, PaperMC, Bedrock, Spigot, proxy, Java};
export {platformPathManeger, globalPlatfroms, pluginManeger, export_import, PocketmineMP, pluginHooks, Powernukkit, PaperMC, Bedrock, Spigot, proxy, Java};
export default {
Bedrock,
Java,
@ -35,7 +28,6 @@ export default {
pluginManeger,
pluginHooks,
export_import,
proxy,
httpRequest
proxy
}
};

View File

@ -1,19 +1,18 @@
import path from "node:path";
import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import * as coreUtils from "@the-bds-maneger/core-utils";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { actionV2, actionsV2 } from "./globalPlatfroms";
import { saveFile } from "@http/large";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import { manegerConfigProprieties } from "./configManipulate";
import { randomPort } from "./lib/randomPort";
import extendsFs from "./lib/extendsFs";
import fsOld from "node:fs";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath, serverRoot, platformIDs, id } = await pathControl("java", platformOptions);
const javaDownload = await platformManeger.java.find(version);
await saveFile({url: javaDownload.url, filePath: path.join(serverPath, "server.jar")});
await coreUtils.httpRequestLarge.saveFile({url: javaDownload.url, filePath: path.join(serverPath, "server.jar")});
await fs.writeFile(path.join(serverRoot, "version_installed.json"), JSON.stringify({version: javaDownload.version, date: javaDownload.date, installDate: new Date()}));
if (platformIDs.length > 1) {
@ -136,7 +135,7 @@ export type editConfig = Gamemode|Difficulty|serverPort|maxPlayers|allowList|ser
export async function serverConfig(platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath } = await pathControl("java", platformOptions);
const fileProperties = path.join(serverPath, "server.properties");
if (!await extendsFs.exists(fileProperties)) await fs.cp(path.join(__dirname, "../configs/java/server.properties"), fileProperties);
if (!await coreUtils.extendFs.exists(fileProperties)) await fs.cp(path.join(__dirname, "../configs/java/server.properties"), fileProperties);
return manegerConfigProprieties<editConfig>({
configPath: fileProperties,
configManipulate: {

View File

@ -1,53 +0,0 @@
import type { ObjectEncodingOptions } from "node:fs";
import * as child_process from "node:child_process";
export default {execFileAsync, execAsync, commendExists};
export type ExecFileOptions = ObjectEncodingOptions & child_process.ExecFileOptions & {stdio?: "ignore"|"inherit"};
export function execFileAsync(command: string): Promise<{stdout: string, stderr: string}>;
export function execFileAsync(command: string, args: (string|number)[]): Promise<{stdout: string, stderr: string}>;
export function execFileAsync(command: string, options: ExecFileOptions): Promise<{stdout: string, stderr: string}>;
export function execFileAsync(command: string, args: (string|number)[], options: ExecFileOptions): Promise<{stdout: string, stderr: string}>;
export function execFileAsync(command: string, args?: ExecFileOptions|(string|number)[], options?: ExecFileOptions) {
let childOptions: ExecFileOptions = {};
let childArgs: string[] = [];
if (args instanceof Array) childArgs = args.map(String); else if (args instanceof Object) childOptions = args as ExecFileOptions;
if (options) childOptions = options;
childOptions.maxBuffer = Infinity;
if (childOptions?.env) childOptions.env = {...process.env, ...childOptions.env};
return new Promise<{stdout: string, stderr: string}>((resolve, rejectExec) => {
const child = child_process.execFile(command, childArgs.map(String), childOptions, (err, out, err2) => {if (err) return rejectExec(err);resolve({stdout: out, stderr: err2});});
if (options?.stdio === "inherit") {
child.stdout.on("data", data => process.stdout.write(data));
child.stderr.on("data", data => process.stderr.write(data));
}
});
}
export type execAsyncOptions = child_process.ExecOptions & {encoding?: BufferEncoding} & {stdio?: "ignore"|"inherit"};
export function execAsync(command: string): Promise<{stdout: string, stderr: string}>;
export function execAsync(command: string, options: execAsyncOptions): Promise<{stdout: string, stderr: string}>;
export function execAsync(command: string, options?: execAsyncOptions) {
let childOptions: execAsyncOptions = {};
if (options) childOptions = options;
if (childOptions?.env) childOptions.env = {...process.env, ...childOptions.env};
return new Promise<{stdout: string, stderr: string}>((resolve, rejectExec) => {
const child = child_process.exec(command, {...childOptions}, (err, out: string|Buffer, err2: string|Buffer) => {if (err) return rejectExec(err);resolve({stdout: ((out instanceof Buffer) ? out.toString():out), stderr: (err2 instanceof Buffer)?err2.toString():err2});});
if (options?.stdio === "inherit") {
child.stdout.on("data", data => process.stdout.write(data));
child.stderr.on("data", data => process.stderr.write(data));
}
});
}
export const defaultCommandNotExists = new Error("This command not exists or is a shell function");
export async function commendExists(command: string): Promise<boolean>;
export async function commendExists(command: string, returnBoolean: true): Promise<boolean>;
export async function commendExists(command: string, returnBoolean: false): Promise<string>;
export async function commendExists(command: string, returnBoolean: boolean = true): Promise<string|boolean> {
let location: string;
if (process.platform === "win32") location = (await execAsync(`where ${command}`).catch(() => ({stdout: ""}))).stdout;
else location = (await execAsync(`command -v ${command}`).catch(() => ({stdout: ""}))).stdout;
if (returnBoolean) return !!location
if (!location) throw defaultCommandNotExists;
return location;
}

View File

@ -1,43 +0,0 @@
import { Stats } from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
export default {exists, isDirectory, isFile, readdirrecursive};
export async function exists(filePath: string) {
return fs.access(path.resolve(filePath)).then(() => true).catch(() => false);
}
export async function isDirectory(filePath: string) {
try {
return (await fs.lstat(filePath)).isDirectory();
} catch {
return false;
}
}
export async function isFile(filePath: string) {
try {
return (await fs.lstat(filePath)).isFile();
} catch {
return false;
}
}
export type dirRecursive = {path: string, stat: Stats};
export async function readdirrecursive(filePath: string|string[], returnInfo = false): Promise<(dirRecursive|string)[]> {
if (typeof filePath === "object") return Promise.all(filePath.map(folder => readdirrecursive(folder, returnInfo))).then(returnArray => {
const files: ((typeof returnArray)[0]) = [];
for (const folderInfo of returnArray) files.push(...folderInfo);
return files;
});
if (!(await exists(filePath))) throw new Error("Folder not exists");
const resolvedPath = path.resolve(filePath);
if (!await isDirectory(resolvedPath)) throw new Error("path if not directory");
const dirfiles = (await fs.readdir(resolvedPath)).map(file => path.join(resolvedPath, file));
for (const folder of dirfiles) {
if (await isFile(folder)) continue;
await readdirrecursive(folder, false).then(files => dirfiles.push(...files as string[])).catch(err => err);
}
if (returnInfo) return Promise.all(dirfiles.map(async file => typeof file === "string"?fs.lstat(file).then(stat => ({ path: file, stat })):file));
return dirfiles;
}

View File

@ -1,18 +1,18 @@
import path from "node:path";
import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import Proprieties from "./lib/Proprieties";
import * as globalPlatfroms from "./globalPlatfroms";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { saveFile } from "@http/large";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import { spigotProprieties } from "./spigot";
import * as globalPlatfroms from "./globalPlatfroms";
import * as coreUtils from "@the-bds-maneger/core-utils";
import Proprieties from "./lib/Proprieties";
import fsOld from "node:fs";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath, id } = await pathControl("paper", platformOptions);
const release = await platformManeger.paper.find(version);
await saveFile({url: release.url, filePath: path.join(serverPath, "paper.jar")});
await coreUtils.httpRequestLarge.saveFile({url: release.url, filePath: path.join(serverPath, "paper.jar")});
return {
id,
version: release.version,

View File

@ -2,7 +2,7 @@ import crypto from "node:crypto";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
import { exists } from "./lib/extendsFs";
import { extendFs } from "@the-bds-maneger/core-utils";
export let bdsRoot = path.join(os.homedir(), ".bdsManeger");
if (process.env.BDS_HOME) {
@ -38,7 +38,7 @@ const idRegex = /^[A-Za-z0-9]*$/;
export async function pathControl(platform: bdsPlatform, options?: bdsPlatformOptions) {
if (!platformArray.includes(platform)) throw new Error("Invalid platform");
const platformRoot = path.join(bdsRoot, platform);
if (!await exists(platformRoot)) await fs.mkdir(platformRoot, {recursive: true});
if (!await extendFs.exists(platformRoot)) await fs.mkdir(platformRoot, {recursive: true});
if (!options) options = {};
// Create if not exists
@ -47,9 +47,9 @@ export async function pathControl(platform: bdsPlatform, options?: bdsPlatformOp
if (options.newId) {
options.id = crypto.randomBytes(16).toString("hex");
fs.mkdir(path.join(platformRoot, options.id), {recursive: true});
if (await exists(path.join(platformRoot, "default"))) await fs.unlink(path.join(platformRoot, "default"));
if (await extendFs.exists(path.join(platformRoot, "default"))) await fs.unlink(path.join(platformRoot, "default"));
await fs.symlink(path.join(platformRoot, options.id), path.join(platformRoot, "default"));
} else if (!await exists(path.join(platformRoot, options.id))) throw new Error("Folder ID not created!");
} else if (!await extendFs.exists(path.join(platformRoot, options.id))) throw new Error("Folder ID not created!");
// Get real id
if (!idRegex.test(options.id)) throw new Error("Invalid Platform ID");
@ -65,12 +65,12 @@ export async function pathControl(platform: bdsPlatform, options?: bdsPlatformOp
if (options?.withBuildFolder) buildFolder = path.join(serverRoot, "build");
// Create folder if not exists
if (!(await exists(serverRoot))) await fs.mkdir(serverRoot, {recursive: true});
if (!(await exists(serverPath))) await fs.mkdir(serverPath, {recursive: true});
if (!(await exists(hooksPath))) await fs.mkdir(hooksPath, {recursive: true});
if (!(await exists(backupPath))) await fs.mkdir(backupPath, {recursive: true});
if (!(await exists(logsPath))) await fs.mkdir(logsPath, {recursive: true});
if (buildFolder && !(await exists(buildFolder))) await fs.mkdir(buildFolder, {recursive: true});
if (!(await extendFs.exists(serverRoot))) await fs.mkdir(serverRoot, {recursive: true});
if (!(await extendFs.exists(serverPath))) await fs.mkdir(serverPath, {recursive: true});
if (!(await extendFs.exists(hooksPath))) await fs.mkdir(hooksPath, {recursive: true});
if (!(await extendFs.exists(backupPath))) await fs.mkdir(backupPath, {recursive: true});
if (!(await extendFs.exists(logsPath))) await fs.mkdir(logsPath, {recursive: true});
if (buildFolder && !(await extendFs.exists(buildFolder))) await fs.mkdir(buildFolder, {recursive: true});
return {
id: options?.id,
@ -93,11 +93,11 @@ export async function pathControl(platform: bdsPlatform, options?: bdsPlatformOp
export async function changeDefault(platform: bdsPlatform, id: bdsPlatformOptions["id"]) {
if (!platformArray.includes(platform)) throw new Error("Invalid platform");
const serverPlatform = path.join(bdsRoot, platform);
if (!await exists(serverPlatform)) throw new Error("Install server fist!");
if (!await extendFs.exists(serverPlatform)) throw new Error("Install server fist!");
const ids = (await fs.readdir(serverPlatform)).filter(folder => folder.toLowerCase() !== "default");
if (!ids.includes(id)) throw new Error("Id not exists to Platform");
const oldPath = fs.realpath(path.join(bdsRoot, platform, "default"));
if (await exists(path.join(bdsRoot, platform, "default"))) await fs.unlink(path.join(bdsRoot, platform, "default"));
if (await extendFs.exists(path.join(bdsRoot, platform, "default"))) await fs.unlink(path.join(bdsRoot, platform, "default"));
await fs.symlink(path.join(bdsRoot, platform, id), path.join(bdsRoot, platform, "default"));
return {
@ -114,7 +114,7 @@ export async function changeDefault(platform: bdsPlatform, id: bdsPlatformOption
export async function getIds(platform?: bdsPlatform) {
if (!platform) {
const platformIds: {[platform: string]: {id: string, realID?: string}[]} = {};
if (!await exists(bdsRoot)) return platformIds;
if (!await extendFs.exists(bdsRoot)) return platformIds;
const Platforms = await fs.readdir(bdsRoot);
if (Platforms.filter(folder => !platformArray.includes(folder as bdsPlatform)).length > 0) throw new Error("Old or invalid Platform path.");
for (const Platform of Platforms) {
@ -130,6 +130,6 @@ export async function getIds(platform?: bdsPlatform) {
}
if (!platformArray.includes(platform)) throw new Error("Invalid platform");
const serverPlatform = path.join(bdsRoot, platform);
if (!await exists(serverPlatform)) throw new Error("Install server fist!");
if (!await extendFs.exists(serverPlatform)) throw new Error("Install server fist!");
return (await fs.readdir(serverPlatform)).filter(folder => folder.toLowerCase() !== "default");
}

View File

@ -1,8 +1,7 @@
import { httpRequestLarge, customChildProcess } from "@the-bds-maneger/core-utils";
import { actionsV2 } from "../globalPlatfroms";
import path from "node:path";
import fs from "node:fs/promises";
import { actionsV2 } from "../globalPlatfroms";
import { execFileAsync } from "../lib/childPromisses";
import { saveFile } from "@http/large";
export type hooksPlatform = "bedrock"|"java"|"pocketmine"|"spigot"|"powernukkit"|"paper";
export type hooksPlatformGeneric = hooksPlatform|"generic";
@ -67,9 +66,9 @@ export class script_hook {
const onSave = path.join(this.#localFolder, fileName);
// Git
if (gitUrlDetect.test(urlHost)) {
await execFileAsync("git", ["clone", urlHost, "--depth", 1, onSave], {cwd: this.#localFolder});
if (await exists(path.join(onSave, "package.json"))) await execFileAsync("npm", ["install", "--no-save"], {cwd: onSave, stdio: "inherit"});
} else await saveFile({url: urlHost, filePath: onSave});
await customChildProcess.execFileAsync("git", ["clone", urlHost, "--depth", 1, onSave], {cwd: this.#localFolder});
if (await exists(path.join(onSave, "package.json"))) await customChildProcess.execFileAsync("npm", ["install", "--no-save"], {cwd: onSave, stdio: "inherit"});
} else await httpRequestLarge.saveFile({url: urlHost, filePath: onSave});
if (!!this.#serverActions) await this.#registerScript(onSave);
return;
}

View File

@ -1,7 +1,6 @@
import path from "node:path";
import type { bdsPlatform } from "../platformPathManeger";
import { getJSON } from "@http/simples";
import { saveFile } from "@http/large";
import { httpRequest, httpRequestLarge } from "@the-bds-maneger/core-utils";
export type pluginConfig = {
version?: 1,
@ -41,11 +40,11 @@ export class pluginManeger {
const urlandbds = /http[s]:\/\/|bdsplugin:\/\//;
if (/bdsplugin:\/\//.test(plugin)) plugin = `https://raw.githubusercontent.com/The-Bds-Maneger/plugin_list/main/plugins/${plugin.replace(urlandbds, "").replace(".json", "")}.json`;
else if (!/http[s]:\/\/\//.test(plugin)) plugin = "bdsplugin://"+plugin;
const info = await getJSON<pluginConfig|pluginV2>(plugin);
const info = await httpRequest.getJSON<pluginConfig|pluginV2>(plugin);
if (info.version === 2) {
const platformData = info.platform[this.#platform];
if (!platformData) throw new Error("Platform not supported to Plugin!");
await saveFile({
await httpRequestLarge.saveFile({
url: platformData.url,
filePath: path.join(this.#pluginFolder, platformData.fileName||path.basename(platformData.url))
});
@ -53,7 +52,7 @@ export class pluginManeger {
return;
}
if (!info.platforms.includes(this.#platform)) throw new Error("Platform not supported to Plugin!");
await saveFile({
await httpRequestLarge.saveFile({
url: info.url,
filePath: path.join(this.#pluginFolder, info.fileName||path.basename(info.url))
});

View File

@ -1,16 +1,13 @@
import { customChildProcess, httpRequest, httpRequestGithub, httpRequestLarge } from "@the-bds-maneger/core-utils";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { existsSync as fsExistsSync, Stats } from "node:fs";
import { promisify } from "node:util";
import * as globalPlatfroms from "./globalPlatfroms";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
import AdmZip from "adm-zip";
import * as globalPlatfroms from "./globalPlatfroms";
import { existsSync as fsExistsSync, Stats } from "node:fs";
import { promisify } from "node:util";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { execFileAsync, execAsync } from "./lib/childPromisses";
import { extractZip, saveFile, tarExtract } from "@http/large";
import { bufferFetch } from "@http/simples";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import {GithubRelease, githubRelease} from "@http/github";
async function findPhp(serverPath: string, extraPath?: string): Promise<string> {
if (!extraPath) extraPath = path.join(serverPath, "bin");
@ -54,14 +51,14 @@ async function buildPhp(serverPath: string, buildFolder: string) {
if (fsExistsSync(path.resolve(serverPath, "bin"))) await fs.rm(path.resolve(serverPath, "bin"), {recursive: true});
if (process.platform === "win32") {
const env = {VS_EDITION: process.env.VS_EDITION||"Enterprise", SOURCES_PATH: process.env.SOURCES_PATH||`${buildFolder}\\pocketmine-php-sdk`};
await execFileAsync("git", ["clone", "--depth=1", "https://github.com/pmmp/php-build-scripts.git", buildFolder], {cwd: buildFolder, stdio: "inherit"});
await execAsync(".\\windows-compile-vs.bat", {cwd: buildFolder, stdio: "inherit", env});
await customChildProcess.execFileAsync("git", ["clone", "--depth=1", "https://github.com/pmmp/php-build-scripts.git", buildFolder], {cwd: buildFolder, stdio: "inherit"});
await customChildProcess.execAsync(".\\windows-compile-vs.bat", {cwd: buildFolder, stdio: "inherit", env});
await promisify((new AdmZip(path.join(buildFolder, (await fs.readdir(buildFolder)).find(file => file.endsWith(".zip"))))).extractAllToAsync)(serverPath, false, true);
} else {
const buildFile = path.join(buildFolder, "build.sh");
await fs.writeFile(buildFile, (await bufferFetch({url: "https://raw.githubusercontent.com/pmmp/php-build-scripts/stable/compile.sh"})).data);
await fs.writeFile(buildFile, (await httpRequest.bufferFetch({url: "https://raw.githubusercontent.com/pmmp/php-build-scripts/stable/compile.sh"})).data);
await fs.chmod(buildFile, "777");
await execFileAsync(buildFile, ["-j"+os.cpus().length], {cwd: buildFolder, stdio: "inherit"});
await customChildProcess.execFileAsync(buildFile, ["-j"+os.cpus().length], {cwd: buildFolder, stdio: "inherit"});
await fs.cp(path.join(buildFolder, "bin", (await fs.readdir(path.join(buildFolder, "bin")))[0]), path.join(serverPath, "bin"), {force: true, recursive: true, preserveTimestamps: true, verbatimSymlinks: true});
}
await fs.rm(buildFolder, {recursive: true, force: true});
@ -69,20 +66,20 @@ async function buildPhp(serverPath: string, buildFolder: string) {
}
async function installPhp(serverPath: string, buildFolder: string): Promise<void> {
const releases: (githubRelease["assets"][0])[] = [];
(await GithubRelease("The-Bds-Maneger", "Build-PHP-Bins")).map(re => re.assets).forEach(res => releases.push(...res));
const releases: (httpRequestGithub.githubRelease["assets"][0])[] = [];
(await httpRequestGithub.GithubRelease("The-Bds-Maneger", "Build-PHP-Bins")).map(re => re.assets).forEach(res => releases.push(...res));
if (fsExistsSync(path.resolve(serverPath, "bin"))) await fs.rm(path.resolve(serverPath, "bin"), {recursive: true});
await fs.writeFile(path.join(os.tmpdir(), "bds_test.php"), `<?php echo "Hello World";`);
if (process.platform === "win32") {
let url: string = releases.filter(assert => assert.name.endsWith(".zip")).find(assert => /win32|windows/.test(assert.name))?.browser_download_url;
if (!url) throw new Error("Cannnot get php url");
return promisify((new AdmZip(await saveFile({url}))).extractAllToAsync)(serverPath, false, true);
return promisify((new AdmZip(await httpRequestLarge.saveFile({url}))).extractAllToAsync)(serverPath, false, true);
} else {
const fileTest = RegExp(`${process.platform.toLowerCase()}.*${process.arch.toLowerCase()}`);
const file = releases.find(re => fileTest.test(re.name.toLowerCase()));
if (file) {
if (/\.zip/.test(file.name)) await extractZip({url: file.browser_download_url, folderTarget: serverPath});
else await tarExtract({url: file.browser_download_url, folderPath: path.join(serverPath, "bin")});
if (/\.zip/.test(file.name)) await httpRequestLarge.extractZip({url: file.browser_download_url, folderTarget: serverPath});
else await httpRequestLarge.tarExtract({url: file.browser_download_url, folderPath: path.join(serverPath, "bin")});
// Update zts
if (process.platform === "linux"||process.platform === "android"||process.platform === "darwin") {
@ -98,7 +95,7 @@ async function installPhp(serverPath: string, buildFolder: string): Promise<void
}
}
// test it's works php
await execFileAsync(await findPhp(serverPath), ["-v"]).catch(err => {
await customChildProcess.execFileAsync(await findPhp(serverPath), ["-v"]).catch(err => {
console.warn(String(err));
return buildPhp(serverPath, buildFolder);
});
@ -109,7 +106,7 @@ export async function installServer(version: string|boolean, platformOptions: bd
const { serverPath, buildFolder, id } = await pathControl("pocketmine", platformOptions);
await installPhp(serverPath, buildFolder);
const info = await platformManeger.pocketmine.find(version);
await saveFile({url: info?.url, filePath: path.join(serverPath, "pocketmine.phar")});
await httpRequestLarge.saveFile({url: info?.url, filePath: path.join(serverPath, "pocketmine.phar")});
return {
id,
version: info.version,

View File

@ -1,18 +1,18 @@
import { platformManeger } from "@the-bds-maneger/server_versions";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import { httpRequestLarge } from "@the-bds-maneger/core-utils";
import * as globalPlatfroms from "./globalPlatfroms";
import path from "node:path";
import fsOld from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import * as globalPlatfroms from "./globalPlatfroms";
import { platformManeger } from "@the-bds-maneger/server_versions";
import { saveFile } from "@http/large";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
export async function installServer(version: string|boolean, platformOptions: bdsPlatformOptions = {id: "default"}) {
const { serverPath, id } = await pathControl("powernukkit", platformOptions);
const jarPath = path.join(serverPath, "pwnukkit.jar");
if (!fsOld.existsSync(serverPath)) await fs.mkdir(serverPath, {recursive: true});
const pwNukktiData = await platformManeger.powernukkit.find(version);
await saveFile({url: pwNukktiData.url, filePath: jarPath})
await httpRequestLarge.saveFile({url: pwNukktiData.url, filePath: jarPath})
return {
id,
version: pwNukktiData.version,

View File

@ -1,26 +0,0 @@
import { getJSON } from "@http/simples";
export type testIp<protocolType extends "ipv4"|"ipv6" = "ipv4"> = {
ip: string,
type: protocolType,
subtype: string,
via: string,
padding: string,
asn: string,
asnlist: string,
asn_name: string,
country: string,
protocol: "HTTP/2.0"|"HTTP/1.1"|"HTTP/1.0"
};
export async function getExternalIP(): Promise<{ipv4: string, ipv6?: string, rawRequest?: {ipv4: testIp<"ipv4">, ipv6?: testIp<"ipv6">}}> {
const [ipv6, ipv4] = await Promise.all([
await getJSON<testIp<"ipv6">>("https://ipv6.lookup.test-ipv6.com/ip/").catch(() => undefined),
await getJSON<testIp<"ipv4">>("https://ipv4.lookup.test-ipv6.com/ip/")
]);
return {
ipv4: ipv4.ip,
ipv6: ipv6?.ip,
rawRequest: {ipv4, ipv6}
};
}

View File

@ -1,107 +0,0 @@
import { getJSON } from "@http/simples";
export type githubRelease = {
url: string;
assets_url: string;
upload_url: string;
html_url: string;
id: number;
tarball_url: string;
zipball_url: string;
body: string;
author: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
};
node_id: string;
tag_name: string;
target_commitish: string;
name: string;
draft: boolean;
prerelease: boolean;
created_at: string;
published_at: string;
assets: Array<{
url: string;
id: number;
node_id: string;
name: string;
label: string;
content_type: string;
state: string;
size: number;
download_count: number;
created_at: string;
updated_at: string;
browser_download_url: string;
uploader: {
login: string;
id: number;
node_id: string;
avatar_url: string;
gravatar_id: string;
url: string;
html_url: string;
followers_url: string;
following_url: string;
gists_url: string;
starred_url: string;
subscriptions_url: string;
organizations_url: string;
repos_url: string;
events_url: string;
received_events_url: string;
type: string;
site_admin: boolean;
};
}>;
};
export async function GithubRelease(username: string, repo: string, releaseTag: string): Promise<githubRelease>;
export async function GithubRelease(username: string, repo: string): Promise<githubRelease[]>;
export async function GithubRelease(username: string): Promise<githubRelease[]>;
export async function GithubRelease(username: string, repo?: string, releaseTag?: string): Promise<githubRelease|githubRelease[]> {
let fullRepo = username;
if (!username) throw new Error("Repository is required, example: GithubRelease(\"Username/repo\") or GithubRelease(\"Username\", \"repo\")");
if (repo) {
if (!/\//.test(fullRepo)) fullRepo += "/"+repo;
}
if (releaseTag) return getJSON<githubRelease>(`https://api.github.com/repos/${fullRepo}/releases/tags/${releaseTag}`);
return getJSON<githubRelease[]>(`https://api.github.com/repos/${fullRepo}/releases?per_page=100`);
}
export type githubTree = {
"sha": string,
"url": string,
"truncated": boolean,
"tree": {
"path": string,
"mode": string,
"type": "blob"|"tree",
"sha": string,
"size": number,
"url": string
}[],
};
export async function githubTree(username: string, repo: string, tree: string = "main") {
const validate = /^[a-zA-Z0-9_\-]+$/;
if (!validate.test(username)) throw new Error("Invalid username");
if (!validate.test(repo)) throw new Error("Invalid repository name");
return getJSON<githubTree>(`https://api.github.com/repos/${username}/${repo}/git/trees/${tree}?recursive=true`);
}

View File

@ -1,53 +0,0 @@
import { requestOptions, pipeFetch } from "@http/simples";
import os from "node:os";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import tar from "tar";
import AdmZip from "adm-zip";
import { exists } from "../lib/extendsFs";
export async function saveFile(request: string|requestOptions & {filePath?: string}) {
if (typeof request === "string") request = {url: request};
const filePath = request.filePath||path.join(os.tmpdir(), `raw_bdscore_${Date.now()}_${(path.parse(request.url||request.socket?.path||crypto.randomBytes(16).toString("hex"))).name}`);
await pipeFetch({...request, waitFinish: true, stream: fs.createWriteStream(filePath, {autoClose: false})});
return filePath;
}
export async function tarExtract(request: requestOptions & {folderPath?: string}) {
const folderToExtract = request.folderPath||path.join(os.tmpdir(), `raw_bdscore_${Date.now()}_${(path.parse(request.url||request.socket?.path||crypto.randomBytes(16).toString("hex"))).name}`);
if (!await exists(folderToExtract)) await fs.promises.mkdir(folderToExtract, {recursive: true});
await pipeFetch({
...request,
waitFinish: true,
stream: tar.extract({
cwd: folderToExtract,
noChmod: false,
noMtime: false,
preserveOwner: true,
keep: true,
p: true
})
});
return folderToExtract
}
const githubAchive = /github.com\/[\S\w]+\/[\S\w]+\/archive\//;
export async function extractZip(request: requestOptions & {folderTarget: string}) {
const zip = new AdmZip(await saveFile(request));
const targetFolder = githubAchive.test(request.url)?await fs.promises.mkdtemp(path.join(os.tmpdir(), "githubRoot_"), "utf8"):request.folderTarget;
await new Promise<void>((done, reject) => {
zip.extractAllToAsync(targetFolder, true, true, (err) => {
if (!err) return done();
return reject(err);
})
});
if (githubAchive.test(request.url)) {
const files = await fs.promises.readdir(targetFolder);
if (files.length === 0) throw new Error("Invalid extract");
await fs.promises.cp(path.join(targetFolder, files[0]), request.folderTarget, {recursive: true, force: true, preserveTimestamps: true, verbatimSymlinks: true});
return await fs.promises.rm(targetFolder, {recursive: true, force: true});
}
return;
}

View File

@ -1,69 +0,0 @@
import type { Method } from "got";
import * as fs from "node:fs";
import * as stream from "node:stream";
export let got: (typeof import("got"))["default"];
async function gotCjs(): Promise<(typeof import("got"))["default"]> {
if (got) return got;
const dyImport = (await (eval('import("got")') as Promise<typeof import("got")>)).default.extend({
enableUnixSockets: true,
headers: {
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
"Accept": "*/*"
}
});
got = dyImport;
return dyImport;
}
export type requestOptions = {
url?: string,
socket?: {
socketPath: string,
path?: string,
}
method?: Method,
headers?: {[headerName: string]: string[]|string},
body?: any,
};
export async function pipeFetch(options: requestOptions & {stream: fs.WriteStream|stream.Writable, waitFinish?: boolean}) {
if (!(options?.url||options?.socket)) throw new Error("Host blank")
const urlRequest = (typeof options.url === "string")?options.url:`http://unix:${options.socket.socketPath}:${options.socket.path||"/"}`;
const gotStream = (await gotCjs()).stream(urlRequest, {
isStream: true,
headers: options.headers||{},
method: options.method||"GET",
...((options.method||"GET").toLowerCase()!=="get"?(typeof options.body === "string"?{body: options.body}:{json: options.body}):{}),
});
await new Promise<void>((done, reject) => {
gotStream.pipe(options.stream);
options.stream.on("error", reject);
gotStream.on("error", reject);
gotStream.once("end", () => {
if (options.waitFinish) return options.stream.once("finish", done);
return done();
});
});
}
export async function bufferFetch(options: string|requestOptions) {
if (typeof options === "string") options = {url: options};
if (!(options.url||options.socket)) throw new Error("Host blank")
const urlRequest = (typeof options.url === "string")?options.url:`http://unix:${options.socket.socketPath}:${options.socket.path||"/"}`;
return (await gotCjs())(urlRequest, {
responseType: "buffer",
headers: options.headers||{},
method: options.method||"GET",
...((options.method||"GET").toLowerCase()!=="get"?(typeof options.body === "string"?{body: options.body}:{json: options.body}):{}),
}).then(res => ({headers: res.headers, data: Buffer.from(res.body), response: res}));
}
export async function getJSON<JSONReturn = any>(request: string|requestOptions): Promise<JSONReturn> {
return bufferFetch(request).then(({data}) => JSON.parse(data.toString("utf8")) as JSONReturn)
}
export async function urls(options: requestOptions|string): Promise<string[]> {
const data = (await bufferFetch(options)).data.toString("utf8");
return (data.match(/((http[s]):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))/g)).map(res => typeof res === "string"?res:res[1]);
}

View File

@ -1,21 +1,19 @@
import { httpRequest, httpRequestLarge, httpRequestGithub } from "@the-bds-maneger/core-utils";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import * as globalPlatfroms from "./globalPlatfroms";
import Proprieties from "./lib/Proprieties"
import fsOld from "node:fs";
import path from "node:path";
import fs from "node:fs/promises";
import fsOld from "node:fs";
import os from "node:os";
import * as globalPlatfroms from "./globalPlatfroms";
import { bufferFetch, getJSON } from "@http/simples";
import { saveFile } from "@http/large";
import { GithubRelease } from "@http/github";
import { pathControl, bdsPlatformOptions } from "./platformPathManeger";
import Proprieties from "./lib/Proprieties"
async function listVersions() {
const data = (await bufferFetch("https://hub.spigotmc.org/versions/")).data.toString("utf8").split("\r").filter(line => /\.json/.test(line)).map(line => {const [, data] = line.match(/>(.*)<\//); return data?.replace(".json", "");}).filter(ver => /^[0-9]+\./.test(ver));
const data = (await httpRequest.bufferFetch("https://hub.spigotmc.org/versions/")).data.toString("utf8").split("\r").filter(line => /\.json/.test(line)).map(line => {const [, data] = line.match(/>(.*)<\//); return data?.replace(".json", "");}).filter(ver => /^[0-9]+\./.test(ver));
const data2 = await Promise.all(data.map(async (version) => {
const data = await getJSON<{name: string, description: string, toolsVersion: number, javaVersions?: number[], refs: {BuildData: string, Bukkit: string, CraftBukkit: string, Spigot: string}}>(`https://hub.spigotmc.org/versions/${version}.json`);
const data = await httpRequest.getJSON<{name: string, description: string, toolsVersion: number, javaVersions?: number[], refs: {BuildData: string, Bukkit: string, CraftBukkit: string, Spigot: string}}>(`https://hub.spigotmc.org/versions/${version}.json`);
return {
version,
date: new Date((await getJSON(`https://hub.spigotmc.org/stash/rest/api/latest/projects/SPIGOT/repos/spigot/commits/${data.refs.Spigot}/`)).committerTimestamp),
date: new Date((await httpRequest.getJSON(`https://hub.spigotmc.org/stash/rest/api/latest/projects/SPIGOT/repos/spigot/commits/${data.refs.Spigot}/`)).committerTimestamp),
data,
};
}));
@ -27,11 +25,11 @@ export async function installServer(version: string|boolean, platformOptions: bd
const jarPath = path.join(serverPath, "server.jar");
if (typeof version === "boolean"||version === "latest") version = (await listVersions())[0].version;
const url = `https://github.com/The-Bds-Maneger/SpigotBuilds/releases/download/${version}/Spigot.jar`;
await saveFile({url, filePath: jarPath});
await httpRequestLarge.saveFile({url, filePath: jarPath});
return {
id, url,
version: version,
date: new Date((await GithubRelease("The-Bds-Maneger", "SpigotBuilds", version)).created_at),
date: new Date((await httpRequestGithub.GithubRelease("The-Bds-Maneger", "SpigotBuilds", version)).created_at),
};
}

View File

@ -1,7 +0,0 @@
import { execAsync, execFileAsync, commendExists } from "../../src/lib/childPromisses";
describe("Child Process Async/Await", () => {
it("Exec", async () => execAsync("ls .."));
it("Exec File", async () => execFileAsync("ls", [".."]));
it("Command Exists", async () => commendExists("bash", false));
});

View File

@ -1,11 +0,0 @@
import path from "path";
import { readdirrecursive, exists, isFile, isDirectory } from "../../src/lib/extendsFs";
describe("Extend FS", function(){
this.timeout(Infinity);
it("List files/dirs recursive without info", async () => readdirrecursive(path.resolve(__dirname, "../../src")).then(res => typeof res[0] === "string"?null:Promise.reject(new Error("Invalid dir return"))));
it("List files/dirs recursive with info", async () => readdirrecursive([path.resolve(__dirname, "../../src"), __dirname], true));
it("Exists", async () => exists(__filename).then(res => res?null:Promise.reject(new Error("Invalid return this file"))));
it("Is file", async () => isFile(__filename).then(res => res?null:Promise.reject(new Error("Invalid return this file"))));
it("Is directory", async () => isDirectory(__dirname).then(res => res?null:Promise.reject(new Error("Invalid return this folder"))));
});

View File

@ -1,16 +0,0 @@
import stream from "node:stream";
import { getJSON, pipeFetch } from "../../src/request/simples";
import { saveFile } from "../../src/request/large";
import { GithubRelease, githubTree } from "../../src/request/github";
import { getExternalIP } from "../../src/request/client";
describe("HTTP Request", function(){
this.timeout(Infinity);
const Stream = new stream.Writable({write(_chunk, _encoding, callback) {callback()}});
it("External IP", async () => getExternalIP());
it("Github Releases", async () => GithubRelease("The-Bds-Maneger", "Bds-Maneger-Core"));
it("Github Tree", async () => githubTree("The-Bds-Maneger", "Bds-Maneger-Core"));
it("JSON", async () => getJSON("https://raw.githubusercontent.com/The-Bds-Maneger/Bds-Maneger-Core/main/package.json"));
it("Stream", async () => pipeFetch({stream: Stream, url: "https://raw.githubusercontent.com/The-Bds-Maneger/Bds-Maneger-Core/main/package.json"}));
it("Save File", async () => saveFile("https://raw.githubusercontent.com/The-Bds-Maneger/Bds-Maneger-Core/main/package.json"));
});

View File

@ -11,13 +11,7 @@
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"allowJs": true,
"lib": ["ES6"],
"baseUrl": ".",
"paths": {
"@http/*": [
"src/request/*"
]
}
"lib": ["ES6"]
},
"include": [
"src/**/*"