Compare commits

..

34 Commits

Author SHA1 Message Date
jkunz 3a2ad58d1c v1.2.1 2026-05-07 23:31:22 +00:00
jkunz 46782d925b fix(client): update request handling and typings for current smartrequest and OpenAPI output 2026-05-07 23:31:22 +00:00
philkunz e85d725873 1.2.0 2024-06-15 16:21:46 +02:00
philkunz d90be18e74 feat(openapi): integrate openapi directly into the repo. 2024-06-15 16:21:45 +02:00
philkunz 5c0e4c6b90 1.1.1 2024-06-15 15:31:55 +02:00
philkunz 34e2c82e68 fix(core): update 2024-06-15 15:31:55 +02:00
philkunz bc53e9f872 1.1.0 2024-06-15 12:26:30 +02:00
philkunz 646ab4d18c feat(volumes and firewalls): enable volumes and firewalls management. 2024-06-15 12:26:29 +02:00
philkunz aaeb025217 1.0.18 2024-02-29 12:01:54 +01:00
philkunz 21e37a7a16 fix(core): update 2024-02-29 12:01:53 +01:00
philkunz 4e0dfb0356 1.0.17 2024-02-18 23:45:04 +01:00
philkunz 84780647da fix(core): update 2024-02-18 23:45:03 +01:00
philkunz 1645d7881a 1.0.16 2024-02-18 23:43:41 +01:00
philkunz 88351db20f fix(core): update 2024-02-18 23:43:40 +01:00
philkunz 18cbf8693f 1.0.15 2024-02-18 23:41:51 +01:00
philkunz 7d64a2bc4d fix(core): update 2024-02-18 23:41:50 +01:00
philkunz 4c327e5e32 1.0.14 2024-02-18 23:25:57 +01:00
philkunz a898928bd3 fix(core): update 2024-02-18 23:25:57 +01:00
philkunz aba8182422 1.0.13 2024-02-18 23:23:21 +01:00
philkunz 5412ab524b fix(core): update 2024-02-18 23:23:20 +01:00
philkunz 2f175e9d64 1.0.12 2024-02-18 01:17:15 +01:00
philkunz d2b1018234 fix(core): update 2024-02-18 01:17:15 +01:00
philkunz e7babf5222 1.0.11 2024-02-17 21:59:11 +01:00
philkunz 63660ecc03 fix(core): update 2024-02-17 21:59:10 +01:00
philkunz 336e27f383 1.0.10 2024-02-17 21:58:11 +01:00
philkunz 9174571ea4 fix(core): update 2024-02-17 21:58:10 +01:00
philkunz 4a722b79b7 1.0.9 2024-02-17 21:55:53 +01:00
philkunz 866dc35403 fix(core): update 2024-02-17 21:55:52 +01:00
philkunz 84d74a131a 1.0.8 2024-02-17 21:55:26 +01:00
philkunz 929404fadd fix(core): update 2024-02-17 21:55:25 +01:00
philkunz 332a4a4195 1.0.7 2024-02-17 20:41:22 +01:00
philkunz 07d625fa1f fix(core): update 2024-02-17 20:41:21 +01:00
philkunz e7cafd9c1c 1.0.6 2024-01-29 21:17:14 +01:00
philkunz 60725ecdcb fix(core): update 2024-01-29 21:17:14 +01:00
21 changed files with 32983 additions and 5061 deletions
+37
View File
@@ -0,0 +1,37 @@
{
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "apiclient.xyz",
"gitrepo": "hetznercloud",
"description": "An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.",
"npmPackagename": "@apiclient.xyz/hetznercloud",
"license": "MIT",
"projectDomain": "apiclient.xyz",
"keywords": [
"Hetzner",
"Cloud",
"API",
"TypeScript",
"Client",
"Servers",
"Volumes",
"Firewalls",
"Automation",
"DevOps",
"Cloud Infrastructure"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@ship.zone/szci": {
"npmGlobalTools": []
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"fileMatch": ["/.smartconfig.json"],
"schema": {
"type": "object",
"properties": {
+36
View File
@@ -0,0 +1,36 @@
# Changelog
## 2026-05-07 - 1.2.1 - fix(client)
update request handling and typings for current smartrequest and OpenAPI output
- migrate HetznerAccount requests to the SmartRequest builder API and normalize responses to statusCode/body
- adjust generated request and resource types for nullable OpenAPI fields and JSON request bodies
- make live API tests skip cleanly when the Hetzner token is missing or rejected
- refresh package tooling and project metadata configuration files
## 2024-06-15 - 1.2.0 - release
Release published with no additional user-facing changes beyond recent updates already included below.
- Version 1.2.0 tags the current state without introducing separate documented changes.
## 2024-06-15 - 1.1.1 - openapi
Integrated OpenAPI directly into the repository.
- Added OpenAPI assets and related integration directly to the repo.
## 2024-06-15 - 1.1.0 - core
Applied a core update.
- Updated core functionality and internal project behavior.
## 2024-06-15 - 1.0.18 - volumes and firewalls
Added support for managing volumes and firewalls.
- Enabled volumes management.
- Enabled firewalls management.
## 2024-01-29 - 1.0.1 to 1.0.17 - core
Series of trivial core update releases between 1.0.1 and 1.0.17.
- Repeated maintenance-level `fix(core): update` changes were released across versions 1.0.1 through 1.0.17.
- Individual entries are summarized here to avoid duplicating minimal, non-descriptive updates.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Task Venture Capital GmbH
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.
-18
View File
@@ -1,18 +0,0 @@
{
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "apiclient.xyz",
"gitrepo": "hetznercloud",
"description": "an unofficial api client for the hetzner cloud api",
"npmPackagename": "@apiclient.xyz/hetznercloud",
"license": "MIT",
"projectDomain": "apiclient.xyz"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
}
}
+27 -12
View File
@@ -1,8 +1,8 @@
{
"name": "@apiclient.xyz/hetznercloud",
"version": "1.0.5",
"version": "1.2.1",
"private": false,
"description": "an unofficial api client for the hetzner cloud api",
"description": "An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@@ -12,19 +12,21 @@
"test": "(tstest test/ --web)",
"build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "(tsdoc)",
"create": "openapi-generator-cli generate -i https://docs.hetzner.cloud/spec.json -g typescript-node -o ts_openapi"
"updateOpenapi": "openapi-typescript https://docs.hetzner.cloud/spec.json --output ts/openapi.spec.ts"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.25",
"@git.zone/tsbundle": "^2.0.5",
"@git.zone/tsrun": "^1.2.46",
"@git.zone/tstest": "^1.0.44",
"@push.rocks/tapbundle": "^5.0.15",
"@types/node": "^20.8.7"
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tsbundle": "^2.10.1",
"@git.zone/tsrun": "^2.0.3",
"@git.zone/tstest": "^3.6.3",
"@push.rocks/qenv": "^6.1.4",
"@types/node": "^25.6.2",
"openapi-typescript": "^7.13.0",
"typescript": "^5.9.3"
},
"dependencies": {
"@push.rocks/smartrequest": "^2.0.21",
"@tempfix/hetzner-openapi": "^1.0.4"
"@push.rocks/smartrequest": "^5.0.3",
"@tsclass/tsclass": "^9.5.1"
},
"repository": {
"type": "git",
@@ -46,7 +48,20 @@
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
".smartconfig.json",
"readme.md"
],
"keywords": [
"Hetzner",
"Cloud",
"API",
"TypeScript",
"Client",
"Servers",
"Volumes",
"Firewalls",
"Automation",
"DevOps",
"Cloud Infrastructure"
]
}
+6935 -4956
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
required:
- 'HETZNER_API_TOKEN'
View File
+255 -29
View File
@@ -1,39 +1,265 @@
# @apiclient.xyz/hetznercloud
an unofficial api client for the hetzner cloud api
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiclient.xyz/hetznercloud)
* [gitlab.com (source)](https://gitlab.com/apiclient.xyz/hetznercloud)
* [github.com (source mirror)](https://github.com/apiclient.xyz/hetznercloud)
* [docs (typedoc)](https://apiclient.xyz.gitlab.io/hetznercloud/)
`@apiclient.xyz/hetznercloud` is an unofficial TypeScript client for the Hetzner Cloud API. It wraps the day-to-day infrastructure primitives this package currently supports - servers, volumes, and firewalls - behind small classes that keep the original Hetzner resource data available while giving you convenient methods for create, list, label-filter, and delete workflows.
## Status for master
## Issue Reporting and Security
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/apiclient.xyz/hetznercloud/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/apiclient.xyz/hetznercloud/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiclient.xyz/hetznercloud)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/apiclient.xyz/hetznercloud)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@apiclient.xyz/hetznercloud)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiclient.xyz/hetznercloud)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiclient.xyz/hetznercloud)](https://lossless.cloud)
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Usage
A modern approach to talking to the hetzner API.
## Why Use It?
- TypeScript-first ESM package for Hetzner Cloud automation.
- Simple `HetznerAccount` object that owns API token authentication.
- Resource classes for `HetznerServer`, `HetznerVolume`, and `HetznerFirewall`.
- Label-based lookup helpers for predictable automation runs.
- Typed request and response shapes generated from the Hetzner OpenAPI specification.
- Escape hatch via `account.request()` whenever you need an endpoint that does not yet have a higher-level class method.
## Install
```bash
pnpm add @apiclient.xyz/hetznercloud
```
## Quick Start
```typescript
import hetznerCloud from '@apiclient.xyz/hetznercloud'
const myhetznerAccount = new hetznerCloud.HetznerAccount('myToken');
const servers = myhetznerAccount.getServers();
for (const server of servers) {
await server.delete();
import {
HetznerAccount,
HetznerFirewall,
HetznerVolume,
} from '@apiclient.xyz/hetznercloud';
const account = new HetznerAccount('your-hetzner-api-token');
const server = await account.createServer({
name: 'demo-api-01',
type: 'cpx31',
location: 'nbg1',
labels: {
app: 'demo-api',
environment: 'staging',
},
userData: '#!/bin/bash\napt-get update',
});
const volume = await HetznerVolume.create(account, {
name: 'demo-api-data',
size: 25,
location: 'nbg1',
labels: {
app: 'demo-api',
environment: 'staging',
},
server,
});
const firewall = await HetznerFirewall.create(account, {
name: 'demo-api-web',
labels: {
app: 'demo-api',
environment: 'staging',
},
rules: [
{
direction: 'in',
protocol: 'tcp',
port: '443',
source_ips: ['0.0.0.0/0', '::/0'],
},
],
});
console.log(server.data);
console.log(volume.data);
console.log(firewall.data);
```
## Core Concepts
### Accounts
`HetznerAccount` stores your Hetzner Cloud API token and exposes the shared request layer used by all resource classes.
```typescript
import { HetznerAccount } from '@apiclient.xyz/hetznercloud';
const account = new HetznerAccount('your-hetzner-api-token');
```
Available account helpers:
- `account.getServers()` lists all servers visible to the token.
- `account.getServersByLabel(labels)` lists servers and returns exact label matches.
- `account.createServer(options)` creates a new server.
- `account.request(method, path, payload)` calls the Hetzner Cloud API directly.
The direct request helper returns an object shaped like this:
```typescript
const response = await account.request('GET', '/servers', {});
console.log(response.statusCode);
console.log(response.body);
```
The current implementation logs request metadata and response bodies to the console, which is useful during automation debugging and important to remember when running with sensitive payloads.
### Servers
Servers are represented by `HetznerServer`. The package can create, list, filter, and delete them.
```typescript
const server = await account.createServer({
name: 'worker-01',
type: 'cpx41',
location: 'fsn1',
labels: {
role: 'worker',
},
userData: '#!/bin/bash\necho ready',
});
const allServers = await account.getServers();
const workerServers = await account.getServersByLabel({ role: 'worker' });
await server.delete();
```
`createServer()` currently creates Ubuntu 22.04 servers, starts them immediately, and enables public IPv4 and IPv6 networking.
Supported server type names are:
```text
cx11, cx21, cx31, cx41, cx51,
ccx11, ccx21, ccx31, ccx41, ccx51,
ccx13, ccx23, ccx33, ccx43, ccx53, ccx63,
cpx11, cpx21, cpx31, cpx41, cpx51, cpx61, cpx70, cpx71, cpx90
```
Supported location names are:
```text
fsn1, nbg1, hel1, ash, hil
```
### Volumes
Volumes are represented by `HetznerVolume`. A volume is created for and attached to an existing `HetznerServer` instance.
```typescript
import { HetznerVolume } from '@apiclient.xyz/hetznercloud';
const volume = await HetznerVolume.create(account, {
name: 'worker-01-data',
size: 50,
location: 'fsn1',
labels: {
role: 'worker',
},
server,
});
const allVolumes = await HetznerVolume.getVolumes(account);
const workerVolumes = await HetznerVolume.getVolumesByLabel(account, { role: 'worker' });
await volume.delete();
```
`HetznerVolume.create()` currently formats new volumes as `xfs` and attaches them to `options.server.data.id`.
### Firewalls
Firewalls are represented by `HetznerFirewall`. The package can create firewalls with rules, list them, filter them by label, and delete them.
```typescript
import { HetznerFirewall } from '@apiclient.xyz/hetznercloud';
const firewall = await HetznerFirewall.create(account, {
name: 'web-ingress',
labels: {
app: 'frontend',
},
rules: [
{
direction: 'in',
protocol: 'tcp',
port: '80',
source_ips: ['0.0.0.0/0', '::/0'],
},
{
direction: 'in',
protocol: 'tcp',
port: '443',
source_ips: ['0.0.0.0/0', '::/0'],
},
],
});
const allFirewalls = await HetznerFirewall.getFirewalls(account);
const frontendFirewalls = await HetznerFirewall.getFirewallsByLabel(account, { app: 'frontend' });
await firewall.delete();
```
### Label Filtering
The label helpers perform exact matches for every key/value pair you pass in. This makes them practical for idempotent automation where labels are your resource ownership contract.
```typescript
const servers = await account.getServersByLabel({
app: 'demo-api',
environment: 'staging',
});
```
## Direct API Access
Use `account.request()` when you need access to an endpoint that is not wrapped yet. Pass the HTTP method, the API path below `/v1`, and a payload object.
```typescript
const locationsResponse = await account.request('GET', '/locations', {});
if (locationsResponse.statusCode >= 200 && locationsResponse.statusCode < 300) {
console.log(locationsResponse.body);
}
```
## Legal
> MIT licensed | **&copy;** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
For non-`GET` and non-`DELETE` requests, the payload is sent as JSON.
## Development
```bash
pnpm install
pnpm test
pnpm run build
```
Tests use `@git.zone/tstest`. Live Hetzner API tests look for `HETZNER_API_TOKEN`; without a usable token, the live API parts are skipped.
The OpenAPI types can be refreshed with:
```bash
pnpm run updateOpenapi
```
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [license](./license) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
+69 -6
View File
@@ -1,8 +1,71 @@
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
import * as hetznercloud from '../ts/index.js'
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as hetznercloud from '../ts/index.js';
import * as qenv from '@push.rocks/qenv';
const testQenv = new qenv.Qenv('./', './.nogit/');
tap.test('first test', async () => {
console.log(hetznercloud)
})
let testAccount: hetznercloud.HetznerAccount | undefined;
let liveApiAvailable = false;
let liveApiSkipReason = 'HETZNER_API_TOKEN has not been validated.';
tap.start()
tap.test('should create a valid hetzer account', async (toolsArg) => {
const token = await testQenv.getEnvVarOnDemand('HETZNER_API_TOKEN');
if (!token) {
liveApiSkipReason = 'HETZNER_API_TOKEN is not configured.';
toolsArg.skip(liveApiSkipReason);
return;
}
testAccount = new hetznercloud.HetznerAccount(token);
expect(testAccount).toBeInstanceOf(hetznercloud.HetznerAccount);
});
tap.test('should be able to list all servers', async (toolsArg) => {
if (!testAccount) {
toolsArg.skip(liveApiSkipReason);
return;
}
const account = testAccount;
const tokenCheckResponse = await account.request('GET', '/servers', {});
if (tokenCheckResponse.statusCode === 401 || tokenCheckResponse.statusCode === 403) {
liveApiSkipReason = 'HETZNER_API_TOKEN was rejected by the Hetzner API.';
toolsArg.skip(liveApiSkipReason);
return;
}
if (tokenCheckResponse.statusCode < 200 || tokenCheckResponse.statusCode >= 300) {
throw new Error(`Hetzner API returned status ${tokenCheckResponse.statusCode}`);
}
liveApiAvailable = true;
const servers = await account.getServers();
expect(servers).toBeArray();
console.log(JSON.stringify(servers, null, 2));
});
const testserver = tap.test('should be able to create a server', async (toolsArg) => {
if (!liveApiAvailable || !testAccount) {
toolsArg.skip(liveApiSkipReason);
return;
}
const newServer = await testAccount.createServer({
name: 'testserver',
location: 'nbg1',
type: 'cpx41',
labels: {
servezoneId: 'testzone',
},
});
expect(newServer).toBeInstanceOf(hetznercloud.HetznerServer);
console.log(newServer);
await toolsArg.delayFor(10000);
return newServer;
});
tap.test('should be able to delete a server', async (toolsArg) => {
if (!liveApiAvailable) {
toolsArg.skip(liveApiSkipReason);
return;
}
const testServer: hetznercloud.HetznerServer =
await (testserver.testResultPromise as Promise<hetznercloud.HetznerServer>);
await testServer.delete();
});
export default tap.start();
+3 -3
View File
@@ -1,8 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@apiclient.xyz/hetznercloud',
version: '1.0.5',
description: 'an unofficial api client for the hetzner cloud api'
version: '1.2.1',
description: 'An unofficial TypeScript API client for the Hetzner Cloud API providing easy methods to manage servers, volumes, and firewalls.'
}
+40 -7
View File
@@ -11,6 +11,14 @@ export class HetznerAccount {
return HetznerServer.getServers(this);
}
public async getServersByLabel(labelObject: plugins.tsclass.typeFestOwn.SecondArgument<typeof HetznerServer.getServersByLabel>) {
return HetznerServer.getServersByLabel(this, labelObject);
}
public async createServer(optionsArg: plugins.tsclass.typeFestOwn.SecondArgument<typeof HetznerServer.create>) {
return HetznerServer.create(this, optionsArg);
}
/**
* request things from the hetzner API
* @param methodArg
@@ -19,13 +27,38 @@ export class HetznerAccount {
*/
public request = async (methodArg: string, pathArg: string, payloadArg: any) => {
const url = `https://api.hetzner.cloud/v1${pathArg}`;
const response = await plugins.smartrequest.request(url, {
method: methodArg,
headers: {
console.log(`Url: ${url}`);
console.log(`Method: ${methodArg}`);
console.log(`Payload: ${JSON.stringify(payloadArg, null, 2)}`);
const request = plugins.smartrequest.SmartRequest.create()
.url(url)
.headers({
Authorization: `Bearer ${this.token}`,
},
requestBody: payloadArg,
});
return response;
})
.options({
keepAlive: false,
});
if (methodArg !== 'GET' && methodArg !== 'DELETE') {
request.json(payloadArg);
}
const response = methodArg === 'POST'
? await request.post()
: methodArg === 'PUT'
? await request.put()
: methodArg === 'PATCH'
? await request.patch()
: methodArg === 'DELETE'
? await request.delete()
: await request.get();
const body = await response.json().catch(() => ({}));
const responseObject = {
statusCode: response.status,
body,
};
console.log(responseObject.statusCode);
console.log(responseObject.body);
return responseObject;
}
}
+74
View File
@@ -0,0 +1,74 @@
// Hetzner Cloud Firewall Class
import type { HetznerAccount } from './classes.account.js';
import * as plugins from './hetznercloud.plugins.js';
import * as types from './types.js';
export class HetznerFirewall {
// STATIC
public static create = async (
hetznerAccountRefArg: HetznerAccount,
optionsArg: {
name: string;
labels?: {[key: string]: string},
rules: types.TFirewallCreateRequestBody['rules'],
}
) => {
const firewall = new HetznerFirewall(hetznerAccountRefArg);
const createFirewallUrl = '/firewalls';
const createFirewallPayload: types.TFirewallCreateRequestBody = {
name: optionsArg.name,
labels: optionsArg.labels || {} as any,
rules: optionsArg.rules
};
const response = await firewall.hetznerAccountRef.request(
'POST',
createFirewallUrl,
createFirewallPayload
);
firewall.data = (response.body as types.TFirewallCreateResponseBody).firewall!;
return firewall;
}
public static getFirewalls = async (hetznerAccountRefArg: HetznerAccount) => {
const firewallsGetUrl = '/firewalls';
const response = await hetznerAccountRefArg.request('GET', firewallsGetUrl, {});
const firewallsDataArray = (response.body as types.TFirewallsGetResponseBody).firewalls;
const firewalls: HetznerFirewall[] = [];
for (const firewallData of firewallsDataArray) {
const firewall = new HetznerFirewall(hetznerAccountRefArg);
firewall.data = firewallData;
firewalls.push(firewall);
}
return firewalls;
}
public static getFirewallsByLabel = async (hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) => {
const firewalls = await HetznerFirewall.getFirewalls(hetznerAccountRefArg);
const results: HetznerFirewall[] = [];
for (const firewall of firewalls) {
let isMatch = true;
for (const key in labelObject) {
if ((firewall.data.labels || {})[key] !== labelObject[key]) {
isMatch = false;
}
}
if (isMatch) {
results.push(firewall);
}
}
return results;
}
// INSTANCE
public data!: types.IFirewall;
public hetznerAccountRef: HetznerAccount;
constructor(hetznerAccountRefArg: HetznerAccount) {
this.hetznerAccountRef = hetznerAccountRefArg;
}
public async delete() {
await this.hetznerAccountRef.request('DELETE', `/firewalls/${this.data.id}`, {});
}
}
+48 -18
View File
@@ -4,32 +4,45 @@ import * as types from './types.js';
export class HetznerServer {
// STATIC
public static async create(hetznerAccountRefArg: HetznerAccount, optionsArg: {
name: string,
datacenter: 'nbg1-dc3',
}) {
public static async create(
hetznerAccountRefArg: HetznerAccount,
optionsArg: {
name: string;
type: types.THetznerCloudServerName;
location: types.THetznerCloudLocationName;
labels?: {[key: string]: string},
userData?: string,
}
) {
const server = new HetznerServer(hetznerAccountRefArg);
const createServerUrl = '/servers';
const createServerPayload: types.TServerCreateRequestBody =
{
name: optionsArg.name,
datacenter: optionsArg.datacenter,
image: '',
server_type: '',
start_after_create: true,
user_data: '',
};
const response = await server.hetznerAccountRef.request('POST', createServerUrl, createServerPayload);
server.data = (response.body as types.TServerCreateResponseBody).server;
const createServerPayload: types.TServerCreateRequestBody = {
name: optionsArg.name,
image: 'ubuntu-22.04',
server_type: optionsArg.type,
start_after_create: true,
labels: optionsArg.labels || {} as any,
location: optionsArg.location,
user_data: optionsArg.userData || '',
public_net: {
enable_ipv4: true,
enable_ipv6: true,
},
};
const response = await server.hetznerAccountRef.request(
'POST',
createServerUrl,
createServerPayload
);
server.data = (response.body as types.TServerCreateResponseBody).server!;
return server;
}
public static async getServers(hetznerAccountRefArg: HetznerAccount) {
const serversGetUrl = '/servers';
const response = await hetznerAccountRefArg.request('GET', serversGetUrl, {});
const serversDataArray = (response.body as types.TServersGetResponseBody).servers;
const serversDataArray = (response.body as types.TServersGetResponseBody).servers;
const servers: HetznerServer[] = [];
for (const serverData of serversDataArray) {
const server = new HetznerServer(hetznerAccountRefArg);
@@ -39,9 +52,26 @@ export class HetznerServer {
return servers;
}
public static async getServersByLabel(hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) {
const servers = await HetznerServer.getServers(hetznerAccountRefArg);
const results: HetznerServer[] = [];
for (const server of servers) {
let isMatch = true;
for (const key in labelObject) {
if ((server.data.labels || {})[key] !== labelObject[key]) {
isMatch = false;
}
}
if (isMatch) {
results.push(server);
}
}
return results;
}
// INSTANCE
public hetznerAccountRef: HetznerAccount;
public data: types.IServer;
public data!: types.IServer;
constructor(hetznerAccountRefArg: HetznerAccount) {
this.hetznerAccountRef = hetznerAccountRefArg;
+77
View File
@@ -0,0 +1,77 @@
import type { HetznerAccount } from './classes.account.js';
import type { HetznerServer } from './classes.server.js';
import * as plugins from './hetznercloud.plugins.js';
import * as types from './types.js';
export class HetznerVolume {
public static create = async (
hetznerAccountRefArg: HetznerAccount,
optionsArg: {
name: string;
size: number;
location: types.THetznerCloudLocationName;
labels?: {[key: string]: string},
server: HetznerServer,
}
) => {
const volume = new HetznerVolume(hetznerAccountRefArg);
const createVolumeUrl = '/volumes';
const createVolumePayload: types.TVolumeCreateRequestBody = {
name: optionsArg.name,
size: optionsArg.size,
location: optionsArg.location,
labels: optionsArg.labels || {} as any,
server: optionsArg.server.data.id,
format: 'xfs'
};
const response = await volume.hetznerAccountRef.request(
'POST',
createVolumeUrl,
createVolumePayload
);
volume.data = (response.body as types.TVolumeCreateResponseBody).volume!;
return volume;
}
public static getVolumes = async (hetznerAccountRefArg: HetznerAccount) => {
const volumesGetUrl = '/volumes';
const response = await hetznerAccountRefArg.request('GET', volumesGetUrl, {});
const volumesDataArray = (response.body as types.TVolumeGetResponseBody).volumes;
const volumes: HetznerVolume[] = [];
for (const volumeData of volumesDataArray) {
const volume = new HetznerVolume(hetznerAccountRefArg);
volume.data = volumeData;
volumes.push(volume);
}
return volumes;
}
public static getVolumesByLabel = async (hetznerAccountRefArg: HetznerAccount, labelObject: {[key: string]: string}) => {
const volumes = await HetznerVolume.getVolumes(hetznerAccountRefArg);
const results: HetznerVolume[] = [];
for (const volume of volumes) {
let isMatch = true;
for (const key in labelObject) {
if ((volume.data.labels || {})[key] !== labelObject[key]) {
isMatch = false;
}
}
if (isMatch) {
results.push(volume);
}
}
return results;
}
public data!: types.IVolume;
public hetznerAccountRef: HetznerAccount;
constructor(hetznerAccountRefArg: HetznerAccount) {
this.hetznerAccountRef = hetznerAccountRefArg;
}
public delete = async () => {
await this.hetznerAccountRef.request('DELETE', `/volumes/${this.data.id}`, {});
}
}
+7 -6
View File
@@ -1,12 +1,13 @@
import * as hetznerOpenapi from '@tempfix/hetzner-openapi';
export {
hetznerOpenapi
}
// @push.rocks
import * as smartrequest from '@push.rocks/smartrequest';
export {
smartrequest,
}
// @tsclass scope
import * as tsclass from '@tsclass/tsclass';
export {
tsclass,
}
+4
View File
@@ -0,0 +1,4 @@
export * from './classes.account.js';
export * from './classes.server.js';
export * from './classes.volume.js';
export * from './classes.firewall.js';
+25285
View File
File diff suppressed because it is too large Load Diff
+59 -5
View File
@@ -1,12 +1,66 @@
import * as plugins from './hetznercloud.plugins.js';
import * as hetznerOpenapiSpec from './openapi.spec.js';
type TJsonRequestBody<TPathMethod> = TPathMethod extends { requestBody?: infer TRequestBody }
? NonNullable<TRequestBody> extends { content: { 'application/json': infer TJsonBody } }
? TJsonBody
: never
: never;
// datacenters
export type TDatacenters = plugins.hetznerOpenapi.paths['/datacenters']['get']['responses']['200']['content']['application/json'];
export type TDatacenters = hetznerOpenapiSpec.paths['/datacenters']['get']['responses']['200']['content']['application/json'];
// servers
export type IServer = plugins.hetznerOpenapi.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server'];
export type IServer = NonNullable<hetznerOpenapiSpec.paths['/servers/{id}']['get']['responses']['200']['content']['application/json']['server']>;
export type TServersGetRequestBody = {};
export type TServersGetResponseBody = plugins.hetznerOpenapi.paths['/servers']['get']['responses']['200']['content']['application/json'];
export type TServerCreateRequestBody = plugins.hetznerOpenapi.paths['/servers']['post']['requestBody']['content']['application/json'];
export type TServerCreateResponseBody = plugins.hetznerOpenapi.paths['/servers']['post']['responses']['201']['content']['application/json'];
export type TServersGetResponseBody = hetznerOpenapiSpec.paths['/servers']['get']['responses']['200']['content']['application/json'];
export type TServerCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/servers']['post']>;
export type TServerCreateResponseBody = hetznerOpenapiSpec.paths['/servers']['post']['responses']['201']['content']['application/json'];
export type TServerDeleteRequestBody = hetznerOpenapiSpec.paths['/servers/{id}']['delete'];
// server types
export type THetznerCloudServerName =
| 'cx11'
| 'cx21'
| 'cx31'
| 'cx41'
| 'cx51'
| 'ccx11'
| 'ccx21'
| 'ccx31'
| 'ccx41'
| 'ccx51'
| 'ccx13'
| 'ccx23'
| 'ccx33'
| 'ccx43'
| 'ccx53'
| 'ccx63'
| 'cpx11'
| 'cpx21'
| 'cpx31'
| 'cpx41'
| 'cpx51'
| 'cpx61'
| 'cpx70'
| 'cpx71'
| 'cpx90';
// location types
export type THetznerCloudLocationName = 'fsn1' | 'nbg1' | 'hel1' | 'ash' | 'hil';
// volumes
export type IVolume = NonNullable<hetznerOpenapiSpec.paths['/volumes/{id}']['get']['responses']['200']['content']['application/json']['volume']>;
export type TVolumeGetRequestBody = {};
export type TVolumeGetResponseBody = hetznerOpenapiSpec.paths['/volumes']['get']['responses']['200']['content']['application/json'];
export type TVolumeCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/volumes']['post']>;
export type TVolumeCreateResponseBody = hetznerOpenapiSpec.paths['/volumes']['post']['responses']['201']['content']['application/json'];
export type TVolumeDeleteRequestBody = hetznerOpenapiSpec.paths['/volumes/{id}']['delete'];
// firewalls
export type IFirewall = NonNullable<hetznerOpenapiSpec.paths['/firewalls/{id}']['get']['responses']['200']['content']['application/json']['firewall']>;
export type TFirewallsGetRequestBody = {};
export type TFirewallsGetResponseBody = hetznerOpenapiSpec.paths['/firewalls']['get']['responses']['200']['content']['application/json'];
export type TFirewallCreateRequestBody = TJsonRequestBody<hetznerOpenapiSpec.paths['/firewalls']['post']>;
export type TFirewallCreateResponseBody = hetznerOpenapiSpec.paths['/firewalls']['post']['responses']['201']['content']['application/json'];
export type TFirewallDeleteRequestBody = hetznerOpenapiSpec.paths['/firewalls/{id}']['delete'];
+3
View File
@@ -9,6 +9,9 @@
"verbatimModuleSyntax": true,
"declaration": true,
"emitDecoratorMetadata": true,
"types": [
"node"
]
},
"exclude": [
"dist_*/**/*.d.ts"