UNPKG

@modexvpn/hcloud

Version:
443 lines (413 loc) 13.5 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); // index.ts var index_exports = {}; __export(index_exports, { hcloud: () => hcloud }); module.exports = __toCommonJS(index_exports); // client.ts var import_axios = __toESM(require("axios")); var HCLOUD_API_URL = "https://api.hetzner.cloud/v1"; var HCLOUD_API_TOKEN = process.env.HCLOUD_API_TOKEN; if (!HCLOUD_API_TOKEN) { throw new Error("HCLOUD_API_TOKEN is missing. Set it in your .env file"); } var hcloudClient = import_axios.default.create({ baseURL: HCLOUD_API_URL, headers: { Authorization: `Bearer ${HCLOUD_API_TOKEN}`, "Content-Type": "application/json" } }); // utils/formatError.ts function formatHcloudError(error, context) { const err = error; const baseMessage = err?.response?.data?.error?.message || err?.message || "Unknown error"; const details = err?.response?.data?.error?.details; let extraMessage = ""; if (details?.fields?.length) { const fieldMessages = details.fields.map((field) => { const issues = field.messages?.join(", ") || "invalid"; return `${field.name}: ${issues}`; }); extraMessage += ` Fields: ${fieldMessages.join("; ")}`; } if (details?.limits?.length) { const limitNames = details.limits.map((limit) => limit.name); extraMessage += ` Limits hit: ${limitNames.join(", ")}`; } return new Error(`${context}: ${baseMessage}${extraMessage}`); } // sdk/servers/getServerById.ts async function getServerById(serverId) { try { const res = await hcloudClient.get(`/servers/${serverId}`); return res.data.server; } catch (error) { throw formatHcloudError(error, `Failed to fetch server ${serverId}`); } } // sdk/servers/getServers.ts var getServers = { async list(query) { try { const res = await hcloudClient.get("/servers", { params: query }); return res.data; } catch (error) { throw formatHcloudError(error, "Failed to list servers"); } } }; // sdk/servers/deleteServer.ts async function deleteServer(serverId) { try { const res = await hcloudClient.delete(`/servers/${serverId}`); return res.data.action; } catch (error) { throw formatHcloudError(error, "Failed to delete server"); } } // sdk/servers/createServer.ts async function createServer(options) { try { const res = await hcloudClient.post("/servers", options); return res.data.server; } catch (error) { throw formatHcloudError(error, "Failed to create server"); } } // sdk/servers/getServerMetrics.ts async function getServerMetrics(serverId, params = { type: "cpu", start: new Date(Date.now() - 5 * 60 * 1e3).toISOString(), end: (/* @__PURE__ */ new Date()).toISOString() }) { try { const res = await hcloudClient.get(`/servers/${serverId}/metrics`, { params }); return res.data.metrics; } catch (error) { throw formatHcloudError(error, `Failed to fetch metrics for server ${serverId}`); } } // sdk/servers/updateServer.ts async function updateServer(serverId, options) { try { const res = await hcloudClient.put(`/servers/${serverId}`, options); return res.data.server; } catch (error) { throw formatHcloudError(error, "Failed to create server"); } } // sdk/servers/actions/attachIso.ts async function attachIso(serverId, iso) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/attach_iso`, { iso }); return res.data; } catch (error) { throw formatHcloudError(error, `Could not attach ISO to server: ${serverId}`); } } // sdk/servers/actions/detachIso.ts async function detachIso(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/detach_iso`); return res.data; } catch (error) { throw formatHcloudError(error, `Could not detach ISO from server: ${serverId}`); } } // sdk/servers/actions/rebuild.ts async function rebuild(serverId, imageId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/rebuild`, { image: imageId }); return res.data; } catch (error) { throw formatHcloudError(error, `Could not rebuild server: ${serverId}`); } } // sdk/servers/actions/disableBackup.ts async function disableBackup(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/disable_backup`); return res.data; } catch (error) { throw formatHcloudError(error, `Could not disable backup for server: ${serverId}`); } } // sdk/servers/actions/disableRescue.ts async function disableRescue(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/disable_rescue`); return res.data; } catch (error) { throw formatHcloudError(error, `Could not disable rescue mode for server: ${serverId}`); } } // sdk/servers/actions/powerControl.ts var powerControl = { async on(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/poweron`); return res.data; } catch (error) { throw formatHcloudError(error, `Failed to power on server: ${serverId}`); } }, async powerOff(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/poweroff`); return res.data; } catch (error) { throw formatHcloudError(error, `Failed to power off server: ${serverId}`); } }, async reboot(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/reboot`); return res.data; } catch (error) { throw formatHcloudError(error, `Failed to reboot server: ${serverId}`); } }, async reset(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/reset`); return res.data; } catch (error) { throw formatHcloudError(error, `Failed to reset server: ${serverId}`); } }, async shutdown(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/shutdown`); return res.data; } catch (error) { throw formatHcloudError(error, `Failed to shut down server: ${serverId}`); } } }; // sdk/servers/actions/resetPassword.ts async function resetPassword(serverId) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/reset_password`); return res.data; } catch (error) { throw formatHcloudError(error, `Could not reset password of server: ${serverId}`); } } // sdk/servers/actions/changeProtection.ts async function changeProtection(serverId, deleteServer2, rebuild2) { try { const res = await hcloudClient.post(`/servers/${serverId}/actions/change_protection`, { delete: deleteServer2, rebuild: rebuild2 }); return res.data; } catch (error) { throw formatHcloudError(error, `Could not change protection for server: ${serverId}`); } } // sdk/servers/actions/getActions.ts async function getActions() { try { const res = await hcloudClient.get("/servers/actions"); return res.data; } catch (error) { throw formatHcloudError(error, `Could get all actions.`); } } // sdk/locations/getLocations.ts async function getLocations(query) { try { const res = await hcloudClient.get("/locations", { params: query }); return res.data; } catch (error) { throw formatHcloudError(error, "Failed to list locations"); } } // sdk/locations/getLocation.ts async function getLocation(locationId) { try { const res = await hcloudClient.get(`/locations/${locationId}`); return res.data.location; } catch (error) { throw formatHcloudError(error, `Coult not get location: ${locationId}`); } } // sdk/servers/actions/sshIntoServer.ts var import_node_ssh = require("node-ssh"); var ssh = new import_node_ssh.NodeSSH(); async function sshIntoServer(ip, command, username, privateKey = process.env.SSH_PRIVATE_KEY) { try { await ssh.connect({ host: ip, username, privateKey }); const result = await ssh.execCommand(command); return { stdout: result.stdout, stderr: result.stderr }; } catch (error) { throw formatHcloudError(error, `Could not SSH into server: ${ip}`); } finally { ssh.dispose(); } } // sdk/servers/server-type/getServerTypes.ts var getServersTypes = { async list(query) { try { const res = await hcloudClient.get("/servers", { params: query }); return res.data; } catch (error) { throw formatHcloudError(error, "Failed to list servers"); } } }; // sdk/servers/server-type/getServerType.ts async function getServerTypeById(serverId) { try { const res = await hcloudClient.get(`/server_types/${serverId}`); return res.data; } catch (error) { throw formatHcloudError(error, "Failed to list servers"); } } // types/security/sshkeys.schema.ts var import_zod2 = require("zod"); // types/common/label.types.ts var import_zod = require("zod"); var labelKeyRegex = /^(([a-z0-9]([-a-z0-9]*[a-z0-9])?\.)*[a-z0-9]([-a-z0-9]*[a-z0-9])?\/)?[a-zA-Z0-9]([a-zA-Z0-9._-]{0,61}[a-zA-Z0-9])?$/; var labelValueRegex = /^([a-zA-Z0-9]([a-zA-Z0-9._-]{0,61}[a-zA-Z0-9])?)?$/; var LabelSchema = import_zod.z.record( import_zod.z.string().regex(labelKeyRegex, "Invalid label key").refine((key) => !key.startsWith("hetzner.cloud/"), { message: "Keys with 'hetzner.cloud/' prefix are reserved" }), import_zod.z.string().regex(labelValueRegex, "Invalid label value") ); // types/security/sshkeys.schema.ts var SSHKeySchema = import_zod2.z.object({ id: import_zod2.z.number(), name: import_zod2.z.string(), fingerprint: import_zod2.z.string(), public_key: import_zod2.z.string(), labels: LabelSchema, created: import_zod2.z.string() }); // sdk/security/ssh-keys/getSSHKey.ts var import_zod3 = require("zod"); var GetSSHKeyResponseSchema = import_zod3.z.object({ ssh_key: SSHKeySchema }); async function getSSHKey(sshKeyId) { try { const res = await hcloudClient.get(`/ssh_keys/${sshKeyId}`); const parsed = GetSSHKeyResponseSchema.parse(res.data); return parsed.ssh_key; } catch (error) { throw formatHcloudError(error, "Failed to get ssh key"); } } // types/common/meta.types.ts var import_zod4 = require("zod"); var MetaSchema = import_zod4.z.object({ pagination: import_zod4.z.object({ page: import_zod4.z.number(), per_page: import_zod4.z.number(), previous_page: import_zod4.z.number().nullable(), next_page: import_zod4.z.number().nullable(), last_page: import_zod4.z.number(), total_entries: import_zod4.z.number() }) }); // sdk/security/ssh-keys/getSSHKeys.ts var import_zod5 = require("zod"); var GetSSHKeyQuerySchema = import_zod5.z.object({ name: import_zod5.z.string().optional(), sort: import_zod5.z.union([import_zod5.z.string(), import_zod5.z.array(import_zod5.z.string())]).optional(), page: import_zod5.z.number().optional(), per_page: import_zod5.z.number().optional(), fingerprint: import_zod5.z.string().optional(), label_selector: import_zod5.z.string().optional() }); var GetSSHKeyResponseSchema2 = import_zod5.z.object({ ssh_keys: import_zod5.z.array(SSHKeySchema), meta: MetaSchema }); async function getSSHKeys(query) { try { const res = await hcloudClient.get("/ssh_keys", { params: query }); const parsed = GetSSHKeyResponseSchema2.parse(res.data); return parsed; } catch (error) { throw formatHcloudError(error, "Failed to list ssh keys"); } } // index.ts var hcloud = { servers: { list: getServers.list, getById: getServerById, delete: deleteServer, create: createServer, getMetrics: getServerMetrics, update: updateServer, attachIso, detachIso, rebuild, disableBackup, disableRescue, powerControl, resetPassword, changeProtection, listActions: getActions, sshIntoServer, listServerType: getServersTypes.list, getServerTypeById }, locations: { list: getLocations, getById: getLocation }, security: { getSSHKey, listSSHKeys: getSSHKeys } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { hcloud }); //# sourceMappingURL=index.js.map