UNPKG

@carbonhost/typescript

Version:

[![License](https://img.shields.io/badge/license-GNU%20AGPL-blue)](LICENSE) [![TypeScript](https://img.shields.io/badge/types-TypeScript-blue)](https://www.typescriptlang.org/) [![Build](https://img.shields.io/github/actions/workflow/status/carbon-host/ca

491 lines (477 loc) 14.9 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { Carbon: () => Carbon, CarbonStar: () => CarbonStar }); module.exports = __toCommonJS(index_exports); // src/carbon.ts var import_axios2 = __toESM(require("axios")); // src/carbon-star.ts var import_axios = __toESM(require("axios")); // src/backups/index.ts var BackupManager = class { star; axios; controllerAxios; constructor(star, axios3, controllerAxios) { this.star = star; this.axios = axios3; this.controllerAxios = controllerAxios; } async getBackups() { return this.controllerAxios.get(`/v1/stars/${this.star._id}/backups`).then((res) => res.data); } async getBackup(backupId) { return this.controllerAxios.get(`/v1/stars/${this.star._id}/backups/${backupId}`).then((res) => res.data); } async deleteBackup(backupId) { return this.controllerAxios.delete(`/v1/stars/${this.star._id}/backups/${backupId}`).then((res) => res.data); } async downloadBackup(backupId) { return this.controllerAxios.get(`/v1/stars/${this.star._id}/backups/${backupId}/download`).then((res) => res.data); } async createBackup(backup) { return this.axios.post("/backups", backup).then((res) => res.data); } async restoreBackup(backupId) { return this.axios.post(`/backups/${backupId}/restore`).then((res) => res.data); } }; // src/file-manager/index.ts var FileManager = class { star; axios; constructor(star, axios3) { this.star = star; this.axios = axios3; } async fetchFiles(directory) { return this.axios.get(`/files?path=${directory}`).then((res) => res.data); } async getFiles(directory) { return await this.fetchFiles(directory); } async getFile(path) { return this.axios.get( `/files/content?path=${path}` ).then((res) => res.data); } async saveFile(path, content) { return this.axios.put("/files/write", { path, content }); } async chmod(options) { return this.axios.post("/files/chmod", options); } async moveFiles(path, files) { return this.axios.post("/files/move", { path, files }); } async renameFile(path, name) { return this.axios.put("/files/rename", { path, name }); } async duplicateFile(path) { return this.axios.post("/files/duplicate", { path }); } async downloadFile(path) { return this.axios.get("/files/download", { params: { path }, responseType: "blob" }); } async deleteFile(params) { const requestParams = {}; if (params.path) { requestParams.path = params.path; } if (params.paths?.length) { requestParams.paths = `[${params.paths.map((path) => `"${path}"`).join(",")}]`; } return this.axios.delete("/files", { params: requestParams }); } async createFile(parentDirectory, fileName) { return this.axios.post("/files", { type: "file", path: `${parentDirectory}/${fileName}` }); } async createDirectory(parentDirectory, folderName) { return this.axios.post("/files", { type: "directory", path: `${parentDirectory}/${folderName}` }); } async decompressFile(root, file) { return this.axios.post("/files/decompress", { root, file }); } async compressFiles(root, files) { return this.axios.post("/files/compress", { root, files }); } async uploadFile(path, file) { try { const url = await this.axios.get("/files/upload", { params: { path } }).then((res) => res.data.url); const formData = new FormData(); formData.append("files", file); const updatedURL = `${url}&directory=${path}`; return await this.axios.post(updatedURL, formData, { headers: { // Don't set Content-Type manually - axios will set it automatically with boundary "Content-Type": "multipart/form-data" } }); } catch (err) { console.error("Upload error:", err); throw err; } } }; // src/managers/minecraft-manager.ts var MinecraftManager = class { star; axios; constructor(star, axios3) { this.star = star; this.axios = axios3; } // getJoinableDomain() { // const port = this.star.ports.find(port => port.internalType === "minecraft")?.publishedPort ?? this.star.getPublishedPort(25565); // return `${this.star.ip}:${port}` // } async getCommands(query) { return this.axios.get("/carbon-plugin/commands", { params: { query } }).then((res) => res.data); } async getInfo() { return this.axios.get("/carbon-plugin").then((res) => res.data); } async getPlayers(limit, offset) { return this.axios.get("/carbon-plugin/players", { params: { limit, offset } }).then((res) => res.data); } async installCarbonPlugin(port) { return this.axios.post("/carbon-plugin/install", { port }).then((res) => res.data); } }; // src/managers/stat-manager.ts var StatManager = class { // @ts-ignore star; axios; constructor(star, axios3) { this.star = star; this.axios = axios3; } async getRecentStats() { return this.axios.get("/stats/recent").then((res) => res.data); } }; // src/network/index.ts var NetworkManager = class { star; axios; constructor(star, axios3) { this.star = star; this.axios = axios3; } async getPorts() { return this.axios.get("/network/ports").then((res) => res.data); } async deletePort(portId) { return this.axios.delete(`/network/ports/${portId}`).then((res) => res.data); } async createPort(notes) { return this.axios.post("/network/ports", { notes }).then((res) => res.data); } async getSFTPDetails() { return this.axios.get("/network/sftp").then((res) => res.data); } async resetSFTPPassword() { return this.axios.post("/network/sftp/reset-password").then((res) => res.data); } }; // src/stars/users/index.ts var UserManager = class { star; axios; controllerAxios; constructor(star, axios3) { this.star = star; this.axios = axios3; this.controllerAxios = star.carbonClient.getAxios(); } async inviteUser(email) { return this.controllerAxios.post(`/v1/stars/${this.star._id}/users/invites`, { email }).then((res) => res.data); } async getInvites() { return this.controllerAxios.get(`/v1/stars/${this.star._id}/users/invites`).then((res) => res.data); } async cancelInvite(inviteId) { return this.controllerAxios.delete(`/v1/stars/${this.star._id}/users/invites/${inviteId}`).then((res) => res.data); } async removeUser(userId) { return this.controllerAxios.delete(`/v1/stars/${this.star._id}/users/${userId}`).then((res) => res.data); } }; // src/carbon-star.ts var CarbonStar = class { // @ts-ignore carbonClient; axios; _id; ownerId; name; config; serverId; clientId; galaxyId; ip; subdomain; subUsers; resources; suspended; createdAt; lastBilled; billingCycle; billingEnabled; billingStoppedAt; billingStoppedReason; constructor(carbonClient, carbonStar) { this.carbonClient = carbonClient; this.axios = import_axios.default.create(carbonClient.getAxios().defaults); this.axios.defaults.baseURL = `${this.axios.defaults.baseURL}/v1/stars/${carbonStar._id}`; this._id = carbonStar._id; this.ownerId = carbonStar.ownerId; this.name = carbonStar.name; this.config = { type: carbonStar.config.type, version: carbonStar.config.version, javaVersion: carbonStar.config.javaVersion, customJar: carbonStar.config.customJar, startupCommand: carbonStar.config.startupCommand, maximumRamPercentage: carbonStar.config.maximumRamPercentage, additionalFlags: carbonStar.config.additionalFlags, minehutSupport: carbonStar.config.minehutSupport, overrideStartup: carbonStar.config.overrideStartup, automaticUpdating: carbonStar.config.automaticUpdating, simdOperations: carbonStar.config.simdOperations, removeUpdateWarnings: carbonStar.config.removeUpdateWarnings, malwareScan: carbonStar.config.malwareScan, acceptEula: carbonStar.config.acceptEula }; this.serverId = carbonStar.serverId; this.clientId = carbonStar.clientId; this.galaxyId = carbonStar.galaxyId; this.ip = carbonStar.ip; this.subdomain = carbonStar.subdomain; this.subUsers = carbonStar.subUsers; this.resources = { storage: carbonStar.resources.storage, memory: carbonStar.resources.memory, vCPU: carbonStar.resources.vCPU }; this.suspended = carbonStar.suspended; this.createdAt = carbonStar.createdAt; this.lastBilled = carbonStar.lastBilled; this.billingCycle = carbonStar.billingCycle; this.billingEnabled = carbonStar.billingEnabled; this.billingStoppedAt = carbonStar.billingStoppedAt; this.billingStoppedReason = carbonStar.billingStoppedReason; } get users() { return new UserManager(this, this.axios); } get minecraft() { return new MinecraftManager(this, this.axios); } get files() { return new FileManager(this, this.axios); } get stats() { return new StatManager(this, this.axios); } get backups() { return new BackupManager(this, this.axios, this.carbonClient.getAxios()); } get network() { return new NetworkManager(this, this.axios); } async delete() { return this.carbonClient.getAxios().delete(`/v1/stars/${this._id}`).then((res) => res.data); } async update(request) { return this.carbonClient.getAxios().patch(`/v1/stars/${this._id}`, request).then((res) => res.data); } async rename(name) { return this.carbonClient.getAxios().put(`/v1/stars/${this._id}/name`, { name }).then((res) => res.data); } async stopBilling(reason) { return this.carbonClient.getAxios().post(`/v1/stars/${this._id}/stop-billing`, { reason }).then((res) => res.data); } async enableBilling() { return this.carbonClient.getAxios().post(`/v1/stars/${this._id}/enable-billing`).then((res) => res.data); } async getResources() { return this.axios.get("/resources").then((res) => res.data); } async setPower(action) { return this.axios.put("/power", { action }).then((res) => res.data); } async executeCommand(command) { return this.axios.post("/command", { command }).then((res) => res.data); } // async uploadFile(file: File, path: string) { // const formData = new FormData(); // formData.append("file", file); // return this.axios // .post<{ status: string; filePath: string }>("/files/upload", formData, { // headers: { // "Content-Type": "multipart/form-data", // }, // params: { // path, // }, // }) // .then((res) => res.data) // .catch((err) => { // console.log(err); // console.log(err.response.data); // }); // } }; // src/managers/api-key-manager.ts var APIKeyManager = class { axios; constructor(axios3) { this.axios = axios3; } async getAPIKey(apiKeyId) { return this.axios.get(`/v1/api-keys/${apiKeyId}`).then((res) => res.data); } async getAPIKeys() { return this.axios.get("/v1/api-keys").then((res) => res.data); } async verifyAPIKey(apiKey) { return this.axios.post("/v1/api-keys/verify", { token: apiKey }).then((res) => res.data); } async deleteAPIKey(apiKeyId) { return this.axios.delete(`/v1/api-keys/${apiKeyId}`).then((res) => res.data); } }; // src/invites/index.ts var InviteManager = class { axios; constructor(axios3) { this.axios = axios3; } async getInvite(inviteId) { return this.axios.get(`/v1/invites/${inviteId}`).then((res) => res.data); } async acceptInvite(inviteId) { return this.axios.post(`/v1/invites/${inviteId}/accept`).then((res) => res.data); } }; // src/carbon.ts var Carbon = class { axios; apiKey; constructor({ apiKey, url }) { this.apiKey = apiKey; this.axios = import_axios2.default.create({ baseURL: url || "https://api.carbon.host", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` } }); } async getMe(forceRefresh) { return this.axios.get(`/v1/me${forceRefresh ? "?forceRefresh=true" : ""}`).then((res) => res.data); } async createAPIKey({ name, description, type }) { return this.axios.post("/v1/api-keys", { name, description, type }).then((res) => res.data); } get apiKeys() { return new APIKeyManager(this.axios); } get inviteManager() { return new InviteManager(this.axios); } async fetchStars(saveToCache) { return this.axios.get("/v1/stars", { params: { saveToCache: saveToCache ? "true" : "false" } }).then((res) => res.data); } async fetchStar(id) { return this.axios.get(`/v1/stars/${id}`).then((res) => res.data); } async getStars(saveToCache) { const stars = await this.fetchStars(saveToCache); return stars.map((star) => new CarbonStar(this, star)); } async getStar(id) { const star = await this.fetchStar(id); return new CarbonStar(this, star); } async createStar(body) { return this.axios.post("/v1/stars", body).then((res) => res.data).catch((err) => { console.log("Error creating star", err.data); throw err; }); } getAxios() { return this.axios; } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Carbon, CarbonStar });