cloudflare/readme.md

361 lines
10 KiB
Markdown
Raw Normal View History

2023-06-13 18:54:25 +02:00
# @apiclient.xyz/cloudflare
2020-02-09 17:54:33 +00:00
An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.
[![npm version](https://badge.fury.io/js/%40apiclient.xyz%2Fcloudflare.svg)](https://www.npmjs.com/package/@apiclient.xyz/cloudflare)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
## Features
- **Comprehensive coverage** of the Cloudflare API including zones, DNS records, and Workers
- **Class-based design** with intuitive methods for all Cloudflare operations
- **Strong TypeScript typing** for excellent IDE autocompletion and type safety
- **Built on the official Cloudflare client** but with a more developer-friendly interface
- **Convenience methods** for common operations to reduce boilerplate code
- **Promise-based API** for easy async/await usage
- **ESM and browser compatible** for maximum flexibility
## Installation
2024-06-15 19:55:48 +02:00
```bash
# Using npm
2024-06-15 19:55:48 +02:00
npm install @apiclient.xyz/cloudflare
# Using yarn
yarn add @apiclient.xyz/cloudflare
2020-02-09 17:54:33 +00:00
# Using pnpm
pnpm add @apiclient.xyz/cloudflare
```
2020-02-09 17:54:33 +00:00
## Quick Start
2024-06-15 19:55:48 +02:00
```typescript
2023-06-13 18:54:25 +02:00
import * as cflare from '@apiclient.xyz/cloudflare';
2020-02-09 17:54:33 +00:00
// Initialize with your API token
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
// Use convenience methods for quick operations
await cfAccount.convenience.createRecord('subdomain.example.com', 'A', '192.0.2.1', 3600);
// Or work with the powerful class-based API
const zone = await cfAccount.zoneManager.getZoneByName('example.com');
await zone.purgeCache();
2024-06-15 19:55:48 +02:00
```
## Usage Guide
2024-06-15 19:55:48 +02:00
### Account Management
2024-06-15 19:55:48 +02:00
Initialize your Cloudflare account with your API token:
2024-06-15 19:55:48 +02:00
```typescript
import * as cflare from '@apiclient.xyz/cloudflare';
2024-06-15 19:55:48 +02:00
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
2024-06-15 19:55:48 +02:00
// If you have multiple accounts, you can preselect one
await cfAccount.preselectAccountByName('My Company Account');
2024-06-15 19:55:48 +02:00
// List all accounts you have access to
const myAccounts = await cfAccount.listAccounts();
2024-06-15 19:55:48 +02:00
```
### Zone Management
2024-06-15 19:55:48 +02:00
Zones represent your domains in Cloudflare.
2024-06-15 19:55:48 +02:00
```typescript
// Get all zones in your account
const allZones = await cfAccount.convenience.listZones();
2024-06-15 19:55:48 +02:00
// Get a specific zone by domain name
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
2024-06-15 19:55:48 +02:00
// Get zone ID directly
const zoneId = await cfAccount.convenience.getZoneId('example.com');
2024-06-15 19:55:48 +02:00
// Create a new zone
const newZone = await cfAccount.zoneManager.createZone('newdomain.com');
2024-06-15 19:55:48 +02:00
// Purge cache for an entire zone
await cfAccount.convenience.purgeZone('example.com');
// Or using the zone object
await myZone.purgeCache();
2024-06-15 19:55:48 +02:00
// Purge specific URLs
await myZone.purgeUrls(['https://example.com/css/styles.css', 'https://example.com/js/app.js']);
2024-06-15 19:55:48 +02:00
// Enable/disable development mode
await myZone.enableDevelopmentMode(); // Enables dev mode for 3 hours
await myZone.disableDevelopmentMode();
2020-02-09 17:54:33 +00:00
// Check zone status
const isActive = await myZone.isActive();
const usingCfNameservers = await myZone.isUsingCloudflareNameservers();
2020-02-09 17:54:33 +00:00
```
### DNS Record Management
2024-06-15 19:55:48 +02:00
Manage DNS records for your domains with ease.
2024-06-15 19:55:48 +02:00
```typescript
// List all DNS records for a domain
const allRecords = await cfAccount.convenience.listRecords('example.com');
// Create a new DNS record
await cfAccount.convenience.createRecord('api.example.com', 'A', '192.0.2.1', 3600);
// Create a CNAME record
await cfAccount.convenience.createRecord('www.example.com', 'CNAME', 'example.com', 3600);
// Get a specific DNS record
const record = await cfAccount.convenience.getRecord('api.example.com', 'A');
// Update a DNS record (automatically creates it if it doesn't exist)
await cfAccount.convenience.updateRecord('api.example.com', 'A', '192.0.2.2', 3600);
// Remove a specific DNS record
await cfAccount.convenience.removeRecord('api.example.com', 'A');
// Clean (remove) all records of a specific type
await cfAccount.convenience.cleanRecord('example.com', 'TXT');
// Support for ACME DNS challenges (for certificate issuance)
await cfAccount.convenience.acmeSetDnsChallenge('example.com', 'challenge-token-here');
await cfAccount.convenience.acmeRemoveDnsChallenge('example.com');
2024-06-15 19:55:48 +02:00
```
### Workers Management
2024-06-15 19:55:48 +02:00
Create and manage Cloudflare Workers with full TypeScript support.
2024-06-15 19:55:48 +02:00
```typescript
// Create or update a worker
const workerScript = `
addEventListener('fetch', event => {
event.respondWith(new Response('Hello from Cloudflare Workers!'))
})`;
const worker = await cfAccount.workerManager.createWorker('my-worker', workerScript);
// List all workers
const allWorkers = await cfAccount.workerManager.listWorkerScripts();
// Get an existing worker
const existingWorker = await cfAccount.workerManager.getWorker('my-worker');
// Set routes for a worker
await worker.setRoutes([
{
zoneName: 'example.com',
pattern: 'https://api.example.com/*'
},
{
zoneName: 'example.com',
pattern: 'https://app.example.com/api/*'
2024-06-15 19:55:48 +02:00
}
]);
// Get all routes for a worker
const routes = await worker.getRoutes();
// Delete a worker
await cfAccount.workerManager.deleteWorker('my-worker');
2024-06-15 19:55:48 +02:00
```
2020-02-09 17:54:33 +00:00
### Complete Example
2020-02-09 17:54:33 +00:00
Here's a complete example showing how to manage multiple aspects of your Cloudflare account:
2020-02-09 17:54:33 +00:00
2024-06-15 19:55:48 +02:00
```typescript
import * as cflare from '@apiclient.xyz/cloudflare';
async function manageCloudflare() {
2024-06-15 19:55:48 +02:00
try {
// Initialize with API token
const cfAccount = new cflare.CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
// Preselect account if needed
await cfAccount.preselectAccountByName('My Company');
// Get zone and check status
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
console.log(`Zone active: ${await myZone.isActive()}`);
console.log(`Using CF nameservers: ${await myZone.isUsingCloudflareNameservers()}`);
// Configure DNS
await cfAccount.convenience.createRecord('api.example.com', 'A', '192.0.2.1');
await cfAccount.convenience.createRecord('www.example.com', 'CNAME', 'example.com');
// Create a worker and set up routes
const workerCode = `
addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (url.pathname.startsWith('/api/')) {
event.respondWith(new Response(JSON.stringify({ status: 'ok' }), {
headers: { 'Content-Type': 'application/json' }
}));
} else {
event.respondWith(fetch(event.request));
}
})`;
const worker = await cfAccount.workerManager.createWorker('api-handler', workerCode);
await worker.setRoutes([
{ zoneName: 'example.com', pattern: 'https://api.example.com/*' }
]);
// Purge cache for specific URLs
await myZone.purgeUrls(['https://example.com/css/styles.css']);
console.log('Configuration completed successfully');
2024-06-15 19:55:48 +02:00
} catch (error) {
console.error('Error managing Cloudflare:', error);
2024-06-15 19:55:48 +02:00
}
}
manageCloudflare();
2024-06-15 19:55:48 +02:00
```
## API Documentation
2024-06-15 19:55:48 +02:00
### CloudflareAccount
2024-06-15 19:55:48 +02:00
The main entry point for all Cloudflare operations.
2024-06-15 19:55:48 +02:00
```typescript
class CloudflareAccount {
constructor(apiToken: string);
// Account selection
async listAccounts(): Promise<any[]>;
async preselectAccountByName(accountName: string): Promise<void>;
// Managers
readonly zoneManager: ZoneManager;
readonly workerManager: WorkerManager;
// Direct API access
async request(endpoint: string, method?: string, data?: any): Promise<any>;
// Convenience namespace with helper methods
readonly convenience: {
// Zone operations
listZones(): Promise<CloudflareZone[]>;
getZoneId(domainName: string): Promise<string>;
purgeZone(domainName: string): Promise<void>;
// DNS operations
listRecords(domainName: string): Promise<CloudflareRecord[]>;
getRecord(domainName: string, recordType: string): Promise<CloudflareRecord>;
createRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<any>;
updateRecord(domainName: string, recordType: string, content: string, ttl?: number): Promise<any>;
removeRecord(domainName: string, recordType: string): Promise<any>;
cleanRecord(domainName: string, recordType: string): Promise<void>;
// ACME operations
acmeSetDnsChallenge(domainName: string, token: string): Promise<any>;
acmeRemoveDnsChallenge(domainName: string): Promise<any>;
};
}
2024-06-15 19:55:48 +02:00
```
### CloudflareZone
2024-06-15 19:55:48 +02:00
Represents a Cloudflare zone (domain).
2024-06-15 19:55:48 +02:00
```typescript
class CloudflareZone {
// Properties
readonly id: string;
readonly name: string;
readonly status: string;
readonly paused: boolean;
readonly type: string;
readonly nameServers: string[];
// Methods
async purgeCache(): Promise<any>;
async purgeUrls(urls: string[]): Promise<any>;
async isActive(): Promise<boolean>;
async isUsingCloudflareNameservers(): Promise<boolean>;
async isDevelopmentModeActive(): Promise<boolean>;
async enableDevelopmentMode(): Promise<any>;
async disableDevelopmentMode(): Promise<any>;
}
2024-06-15 19:55:48 +02:00
```
### CloudflareRecord
2024-06-15 19:55:48 +02:00
Represents a DNS record.
2024-06-15 19:55:48 +02:00
```typescript
class CloudflareRecord {
// Properties
readonly id: string;
readonly type: string;
readonly name: string;
readonly content: string;
readonly ttl: number;
readonly proxied: boolean;
// Methods
async update(content: string, ttl?: number): Promise<any>;
async delete(): Promise<any>;
}
2024-06-15 19:55:48 +02:00
```
### CloudflareWorker
2024-06-15 19:55:48 +02:00
Represents a Cloudflare Worker.
2024-06-15 19:55:48 +02:00
```typescript
class CloudflareWorker {
// Properties
readonly id: string;
readonly name: string;
// Methods
async getRoutes(): Promise<any[]>;
async setRoutes(routes: Array<{ zoneName: string, pattern: string }>): Promise<any>;
}
```
2024-06-15 19:55:48 +02:00
## Utility Functions
2024-06-15 19:55:48 +02:00
The library includes helpful utility functions:
2024-06-15 19:55:48 +02:00
```typescript
// Validate a domain name
CloudflareUtils.isValidDomain('example.com'); // true
2024-06-15 19:55:48 +02:00
// Extract zone name from a domain
CloudflareUtils.getZoneName('subdomain.example.com'); // 'example.com'
2024-06-15 19:55:48 +02:00
// Validate a record type
CloudflareUtils.isValidRecordType('A'); // true
2024-06-15 19:55:48 +02:00
// Format URL for cache purging
CloudflareUtils.formatUrlForPurge('example.com/page'); // 'https://example.com/page'
```
2024-06-15 19:55:48 +02:00
## Development & Testing
2024-06-15 19:55:48 +02:00
To build the project:
2024-06-15 19:55:48 +02:00
```bash
npm run build
```
2024-06-15 19:55:48 +02:00
To run tests:
2024-06-15 19:55:48 +02:00
```bash
npm test
2024-06-15 19:55:48 +02:00
```
2020-02-09 17:54:33 +00:00
## License
MIT © [Lossless GmbH](https://lossless.gmbh)