Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 609bcbc6db | |||
| 2da9370742 | |||
| 18afafd3b3 | |||
| 5ce1520e2b |
23
changelog.md
23
changelog.md
@@ -1,5 +1,28 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-11-18 - 7.1.0 - feat(cloudflare)
|
||||||
|
Release 7.0.0 — manager-based API, ConvenientDnsProvider, improved utils and worker/zone/record management
|
||||||
|
|
||||||
|
- Introduce manager-based architecture: ZoneManager, RecordManager, WorkerManager for clearer, consistent API surface
|
||||||
|
- Add ConvenientDnsProvider adapter implementing IConvenientDnsProvider for third-party integrations
|
||||||
|
- New CloudflareUtils helpers (domain validation, API token check, record type validation, URL/TTL formatting, pagination)
|
||||||
|
- Improved Worker support: create/update/delete scripts, route management, and robust listing with fallbacks
|
||||||
|
- Zone and record operations enhanced (create/update/delete/purge) with type-safe wrappers and CloudflareZone/CloudflareRecord models
|
||||||
|
- Deprecated old convenience namespace in favor of managers (kept for backward compatibility with migration guidance)
|
||||||
|
- Full TypeScript exports and typings, updated package metadata for v7.0.0
|
||||||
|
|
||||||
|
## 2025-11-18 - 7.0.0 - BREAKING CHANGE(core)
|
||||||
|
Introduce RecordManager and ConvenientDnsProvider; rename list/get methods for consistent API and deprecate convenience namespace
|
||||||
|
|
||||||
|
- Add RecordManager with listRecords, getRecord, createRecord, updateRecord, deleteRecord and cleanRecords to centralize DNS record operations
|
||||||
|
- Add ConvenientDnsProvider adapter and CloudflareAccount.getConvenientDnsProvider() to provide IConvenientDnsProvider compatibility for third-party modules
|
||||||
|
- Rename methods to consistent list* naming: worker.getRoutes -> worker.listRoutes, WorkerManager.listWorkerScripts -> WorkerManager.listWorkers, ZoneManager.getZones -> ZoneManager.listZones, convenience.listRecords -> recordManager.listRecords
|
||||||
|
- Add ZoneManager.getZoneId() and ZoneManager.purgeZone() (zone cache purge helper)
|
||||||
|
- Deprecate the legacy convenience.* methods (getZoneId, getRecord, createRecord, removeRecord, cleanRecord, updateRecord, listRecords, listZones, isDomainSupported, purgeZone, acmeSetDnsChallenge, acmeRemoveDnsChallenge) — kept for backward compatibility but marked deprecated
|
||||||
|
- Export RecordManager and ConvenientDnsProvider from ts/index.ts and expose cfAccount.recordManager on CloudflareAccount
|
||||||
|
- Update tests to use new method names (listWorkers) and extend test runner timeout; package.json test script updated
|
||||||
|
- Documentation (readme) updated to describe the new manager-based API and migration guide; prepares project for major version 7.0.0
|
||||||
|
|
||||||
## 2025-11-17 - 6.4.3 - fix(cloudflare.plugins)
|
## 2025-11-17 - 6.4.3 - fix(cloudflare.plugins)
|
||||||
Switch to smartrequest namespace export and improve request typing and JSON parsing
|
Switch to smartrequest namespace export and improve request typing and JSON parsing
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"name": "@apiclient.xyz/cloudflare",
|
"name": "@apiclient.xyz/cloudflare",
|
||||||
"version": "6.4.3",
|
"version": "7.1.0",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.",
|
"description": "A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
"typings": "dist_ts/index.d.ts",
|
"typings": "dist_ts/index.d.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "(tstest test/)",
|
"test": "(tstest test/ --verbose --timeout 600)",
|
||||||
"build": "(tsbuild --web --allowimplicitany)",
|
"build": "(tsbuild --web --allowimplicitany)",
|
||||||
"buildDocs": "tsdoc",
|
"buildDocs": "tsdoc",
|
||||||
"updateOpenapi": "openapi-typescript https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.yaml --output ts/openapi.spec.ts"
|
"updateOpenapi": "openapi-typescript https://raw.githubusercontent.com/cloudflare/api-schemas/main/openapi.yaml --output ts/openapi.spec.ts"
|
||||||
|
|||||||
638
readme.md
638
readme.md
@@ -1,407 +1,493 @@
|
|||||||
# @apiclient.xyz/cloudflare
|
# @apiclient.xyz/cloudflare
|
||||||
|
|
||||||
An elegant, class-based TypeScript client for the Cloudflare API that makes managing your Cloudflare resources simple and type-safe.
|
> 🚀 A modern, elegant TypeScript client for the Cloudflare API with clean manager-based architecture
|
||||||
|
|
||||||
[](https://www.npmjs.com/package/@apiclient.xyz/cloudflare)
|
[](https://www.npmjs.com/package/@apiclient.xyz/cloudflare)
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
## Features
|
Stop fighting with the Cloudflare API. This library gives you an intuitive, type-safe way to manage zones, DNS records, and Workers—all with clean, predictable method names and excellent IDE support.
|
||||||
|
|
||||||
- **Comprehensive coverage** of the Cloudflare API including zones, DNS records, and Workers
|
## ✨ Why This Library?
|
||||||
- **Class-based design** with intuitive methods for all Cloudflare operations
|
|
||||||
- **Strong TypeScript typing** for excellent IDE autocompletion and type safety
|
|
||||||
- **Fully integrated with the official Cloudflare client** using modern async iterators
|
|
||||||
- **Convenience methods** for common operations to reduce boilerplate code
|
|
||||||
- **Promise-based API** for easy async/await usage
|
|
||||||
- **ESM compatible** for modern JavaScript projects
|
|
||||||
- **Comprehensive error handling** for robust applications
|
|
||||||
|
|
||||||
## Installation
|
- **🎯 Logical & Consistent**: Manager-based architecture with predictable method naming (`listZones()`, `listRecords()`, `listWorkers()`)
|
||||||
|
- **💪 Strongly Typed**: Full TypeScript support with excellent autocompletion
|
||||||
|
- **🔌 Framework Integration**: Built-in `IConvenientDnsProvider` adapter for third-party modules
|
||||||
|
- **⚡ Modern**: Uses async/await, ES modules, and the official Cloudflare SDK
|
||||||
|
- **🛡️ Reliable**: Comprehensive error handling and detailed logging
|
||||||
|
- **📦 Zero Config**: Works out of the box with just your API token
|
||||||
|
|
||||||
|
## 🚀 Quick Start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Using npm
|
|
||||||
npm install @apiclient.xyz/cloudflare
|
npm install @apiclient.xyz/cloudflare
|
||||||
|
|
||||||
# Using yarn
|
|
||||||
yarn add @apiclient.xyz/cloudflare
|
|
||||||
|
|
||||||
# Using pnpm
|
|
||||||
pnpm add @apiclient.xyz/cloudflare
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
// Initialize with your API token
|
const cf = new CloudflareAccount('your-api-token');
|
||||||
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
|
|
||||||
|
|
||||||
// Use convenience methods for quick operations
|
// Manage DNS records with ease
|
||||||
await cfAccount.convenience.createRecord('subdomain.example.com', 'A', '192.0.2.1', 3600);
|
await cf.recordManager.createRecord('api.example.com', 'A', '192.0.2.1');
|
||||||
|
await cf.recordManager.updateRecord('api.example.com', 'A', '203.0.113.1');
|
||||||
|
|
||||||
// Or work with the powerful class-based API
|
// Work with zones
|
||||||
const zone = await cfAccount.zoneManager.getZoneByName('example.com');
|
const zones = await cf.zoneManager.listZones();
|
||||||
await zone.purgeCache();
|
await cf.zoneManager.purgeZone('example.com');
|
||||||
|
|
||||||
|
// Deploy workers
|
||||||
|
const worker = await cf.workerManager.createWorker('my-api', workerScript);
|
||||||
|
await worker.setRoutes([{ zoneName: 'example.com', pattern: 'api.example.com/*' }]);
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage Guide
|
## 📚 Core Concepts
|
||||||
|
|
||||||
### Account Management
|
### Managers: Your Gateway to Cloudflare
|
||||||
|
|
||||||
Initialize your Cloudflare account with your API token:
|
The library is organized around **managers**—specialized classes that handle specific Cloudflare resources:
|
||||||
|
|
||||||
|
- **`recordManager`** - DNS record operations
|
||||||
|
- **`zoneManager`** - Zone (domain) management
|
||||||
|
- **`workerManager`** - Cloudflare Workers deployment
|
||||||
|
|
||||||
|
Each manager provides consistent, predictable methods that feel natural to use.
|
||||||
|
|
||||||
|
## 🎓 Complete Guide
|
||||||
|
|
||||||
|
### Account Setup
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
const cfAccount = new cflare.CloudflareAccount('your-cloudflare-api-token');
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
|
||||||
// If you have multiple accounts, you can preselect one
|
// If you have multiple accounts, select one
|
||||||
await cfAccount.preselectAccountByName('My Company Account');
|
await cf.preselectAccountByName('Production Account');
|
||||||
|
|
||||||
// List all accounts you have access to
|
|
||||||
const myAccounts = await cfAccount.listAccounts();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Zone Management
|
### 🌐 Zone Management
|
||||||
|
|
||||||
Zones represent your domains in Cloudflare.
|
Zones are your domains in Cloudflare.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Get all zones in your account
|
// List all zones
|
||||||
const allZones = await cfAccount.convenience.listZones();
|
const zones = await cf.zoneManager.listZones();
|
||||||
|
|
||||||
// Get a specific zone by domain name
|
// Find a specific zone
|
||||||
const myZone = await cfAccount.zoneManager.getZoneByName('example.com');
|
const zone = await cf.zoneManager.getZoneByName('example.com');
|
||||||
|
|
||||||
// Get zone ID directly
|
// Get zone ID for API calls
|
||||||
const zoneId = await cfAccount.convenience.getZoneId('example.com');
|
const zoneId = await cf.zoneManager.getZoneId('example.com');
|
||||||
|
|
||||||
// Create a new zone
|
// Create a new zone
|
||||||
const newZone = await cfAccount.zoneManager.createZone('newdomain.com');
|
await cf.zoneManager.createZone('newdomain.com');
|
||||||
|
|
||||||
// Purge cache for an entire zone
|
// Purge entire zone cache
|
||||||
await cfAccount.convenience.purgeZone('example.com');
|
await cf.zoneManager.purgeZone('example.com');
|
||||||
// Or using the zone object
|
|
||||||
await myZone.purgeCache();
|
|
||||||
|
|
||||||
// Purge specific URLs
|
// Work with zone objects
|
||||||
await myZone.purgeUrls(['https://example.com/css/styles.css', 'https://example.com/js/app.js']);
|
if (await zone.isActive()) {
|
||||||
|
await zone.purgeCache();
|
||||||
|
await zone.purgeUrls(['https://example.com/css/app.css']);
|
||||||
|
|
||||||
// Enable/disable development mode
|
// Development mode (bypasses cache for 3 hours)
|
||||||
await myZone.enableDevelopmentMode(); // Enables dev mode for 3 hours
|
await zone.enableDevelopmentMode();
|
||||||
await myZone.disableDevelopmentMode();
|
await zone.disableDevelopmentMode();
|
||||||
|
}
|
||||||
// Check zone status
|
|
||||||
const isActive = await myZone.isActive();
|
|
||||||
const usingCfNameservers = await myZone.isUsingCloudflareNameservers();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### DNS Record Management
|
### 📝 DNS Records
|
||||||
|
|
||||||
Manage DNS records for your domains with ease.
|
The `recordManager` gives you complete control over DNS records.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// List all DNS records for a domain
|
// List all records for a domain
|
||||||
const allRecords = await cfAccount.convenience.listRecords('example.com');
|
const records = await cf.recordManager.listRecords('example.com');
|
||||||
|
|
||||||
// Create a new DNS record
|
// Create different record types
|
||||||
await cfAccount.convenience.createRecord('api.example.com', 'A', '192.0.2.1', 3600);
|
await cf.recordManager.createRecord('www.example.com', 'CNAME', 'example.com', 3600);
|
||||||
|
await cf.recordManager.createRecord('api.example.com', 'A', '192.0.2.1', 300);
|
||||||
|
await cf.recordManager.createRecord('_dmarc.example.com', 'TXT', 'v=DMARC1; p=reject', 3600);
|
||||||
|
|
||||||
// Create a CNAME record
|
// Get a specific record
|
||||||
await cfAccount.convenience.createRecord('www.example.com', 'CNAME', 'example.com', 3600);
|
const record = await cf.recordManager.getRecord('api.example.com', 'A');
|
||||||
|
console.log(record.content); // "192.0.2.1"
|
||||||
|
|
||||||
// Get a specific DNS record
|
// Update or create (upsert behavior)
|
||||||
const record = await cfAccount.convenience.getRecord('api.example.com', 'A');
|
await cf.recordManager.updateRecord('api.example.com', 'A', '203.0.113.1');
|
||||||
|
|
||||||
// Update a DNS record (automatically creates it if it doesn't exist)
|
// Delete a record
|
||||||
await cfAccount.convenience.updateRecord('api.example.com', 'A', '192.0.2.2', 3600);
|
await cf.recordManager.deleteRecord('old.example.com', 'A');
|
||||||
|
|
||||||
// Remove a specific DNS record
|
// Clean up all records of a type (useful for wildcard cleanup)
|
||||||
await cfAccount.convenience.removeRecord('api.example.com', 'A');
|
await cf.recordManager.cleanRecords('example.com', 'TXT');
|
||||||
|
|
||||||
// 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({
|
|
||||||
hostName: '_acme-challenge.example.com',
|
|
||||||
challenge: 'token-validation-string',
|
|
||||||
});
|
|
||||||
await cfAccount.convenience.acmeRemoveDnsChallenge({
|
|
||||||
hostName: '_acme-challenge.example.com',
|
|
||||||
challenge: 'token-validation-string',
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Workers Management
|
### ⚙️ Cloudflare Workers
|
||||||
|
|
||||||
Create and manage Cloudflare Workers with full TypeScript support.
|
Deploy and manage serverless functions at the edge.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Create or update a worker
|
// Worker code
|
||||||
const workerScript = `
|
const workerScript = `
|
||||||
addEventListener('fetch', event => {
|
addEventListener('fetch', event => {
|
||||||
event.respondWith(new Response('Hello from Cloudflare Workers!'))
|
event.respondWith(handleRequest(event.request));
|
||||||
})`;
|
});
|
||||||
|
|
||||||
const worker = await cfAccount.workerManager.createWorker('my-worker', workerScript);
|
async function handleRequest(request) {
|
||||||
|
return new Response('Hello from the edge!', {
|
||||||
|
headers: { 'content-type': 'text/plain' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Create/update a worker
|
||||||
|
const worker = await cf.workerManager.createWorker('my-api-worker', workerScript);
|
||||||
|
|
||||||
// List all workers
|
// List all workers
|
||||||
const allWorkers = await cfAccount.workerManager.listWorkerScripts();
|
const workers = await cf.workerManager.listWorkers();
|
||||||
|
|
||||||
// Get an existing worker
|
// Get existing worker
|
||||||
const existingWorker = await cfAccount.workerManager.getWorker('my-worker');
|
const existingWorker = await cf.workerManager.getWorker('my-api-worker');
|
||||||
|
|
||||||
// Set routes for a worker
|
// Set up routes
|
||||||
await worker.setRoutes([
|
await worker.setRoutes([
|
||||||
{
|
{ zoneName: 'example.com', pattern: 'api.example.com/*' },
|
||||||
zoneName: 'example.com',
|
{ zoneName: 'example.com', pattern: 'example.com/api/*' }
|
||||||
pattern: 'https://api.example.com/*',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
zoneName: 'example.com',
|
|
||||||
pattern: 'https://app.example.com/api/*',
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// Get all routes for a worker
|
// Check worker routes
|
||||||
const routes = await worker.getRoutes();
|
await worker.listRoutes();
|
||||||
|
console.log(worker.routes); // Array of routes
|
||||||
|
|
||||||
// Update a worker's script
|
// Update worker script
|
||||||
await worker.updateScript(`
|
await worker.updateScript(updatedWorkerScript);
|
||||||
addEventListener('fetch', event => {
|
|
||||||
event.respondWith(new Response('Updated worker content!'))
|
|
||||||
})`);
|
|
||||||
|
|
||||||
// Delete a worker
|
// Delete worker
|
||||||
await worker.delete();
|
await worker.delete();
|
||||||
// Or using the worker manager
|
// or
|
||||||
await cfAccount.workerManager.deleteWorker('my-worker');
|
await cf.workerManager.deleteWorker('my-api-worker');
|
||||||
```
|
```
|
||||||
|
|
||||||
### Complete Example
|
### 🔐 ACME DNS Challenges (Let's Encrypt)
|
||||||
|
|
||||||
Here's a complete example showing how to manage multiple aspects of your Cloudflare account:
|
Use the `ConvenientDnsProvider` adapter for certificate automation.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import * as cflare from '@apiclient.xyz/cloudflare';
|
const dnsProvider = cf.getConvenientDnsProvider();
|
||||||
|
|
||||||
async function manageCloudflare() {
|
// Set DNS challenge
|
||||||
try {
|
await dnsProvider.acmeSetDnsChallenge({
|
||||||
// Initialize with API token from environment variable
|
hostName: '_acme-challenge.example.com',
|
||||||
const cfAccount = new cflare.CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
challenge: 'your-validation-token'
|
||||||
|
});
|
||||||
|
|
||||||
// Preselect account if needed
|
// Remove challenge after validation
|
||||||
await cfAccount.preselectAccountByName('My Company');
|
await dnsProvider.acmeRemoveDnsChallenge({
|
||||||
|
hostName: '_acme-challenge.example.com',
|
||||||
// Get zone and check status
|
challenge: 'your-validation-token'
|
||||||
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');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error managing Cloudflare:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
manageCloudflare();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## API Documentation
|
### 🔌 Third-Party Module Integration
|
||||||
|
|
||||||
|
If you're using a framework or library that expects `IConvenientDnsProvider`, use the adapter:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
const dnsProvider = cf.getConvenientDnsProvider();
|
||||||
|
|
||||||
|
// Now pass this to any library expecting IConvenientDnsProvider
|
||||||
|
await someFramework.setDnsProvider(dnsProvider);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 Real-World Example
|
||||||
|
|
||||||
|
Here's a complete example showing a typical deployment workflow:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { CloudflareAccount } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
async function deployApplication() {
|
||||||
|
const cf = new CloudflareAccount(process.env.CLOUDFLARE_API_TOKEN);
|
||||||
|
await cf.preselectAccountByName('Production');
|
||||||
|
|
||||||
|
// 1. Set up DNS
|
||||||
|
console.log('📝 Configuring DNS...');
|
||||||
|
await cf.recordManager.createRecord('app.example.com', 'A', '192.0.2.10');
|
||||||
|
await cf.recordManager.createRecord('www.example.com', 'CNAME', 'example.com');
|
||||||
|
|
||||||
|
// 2. Deploy API worker
|
||||||
|
console.log('⚙️ Deploying API worker...');
|
||||||
|
const apiWorker = await cf.workerManager.createWorker('api-handler', `
|
||||||
|
addEventListener('fetch', event => {
|
||||||
|
const response = new Response(JSON.stringify({ status: 'ok' }), {
|
||||||
|
headers: { 'content-type': 'application/json' }
|
||||||
|
});
|
||||||
|
event.respondWith(response);
|
||||||
|
});
|
||||||
|
`);
|
||||||
|
|
||||||
|
await apiWorker.setRoutes([
|
||||||
|
{ zoneName: 'example.com', pattern: 'api.example.com/*' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 3. Configure security headers worker
|
||||||
|
console.log('🛡️ Setting up security...');
|
||||||
|
const securityWorker = await cf.workerManager.createWorker('security-headers', `
|
||||||
|
addEventListener('fetch', event => {
|
||||||
|
event.respondWith(addSecurityHeaders(event.request));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function addSecurityHeaders(request) {
|
||||||
|
const response = await fetch(request);
|
||||||
|
const newHeaders = new Headers(response.headers);
|
||||||
|
newHeaders.set('X-Frame-Options', 'DENY');
|
||||||
|
newHeaders.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
|
||||||
|
return new Response(response.body, {
|
||||||
|
status: response.status,
|
||||||
|
headers: newHeaders
|
||||||
|
});
|
||||||
|
}
|
||||||
|
`);
|
||||||
|
|
||||||
|
await securityWorker.setRoutes([
|
||||||
|
{ zoneName: 'example.com', pattern: 'example.com/*' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 4. Verify and purge cache
|
||||||
|
console.log('🔄 Purging cache...');
|
||||||
|
const zone = await cf.zoneManager.getZoneByName('example.com');
|
||||||
|
await zone.purgeCache();
|
||||||
|
|
||||||
|
console.log('✅ Deployment complete!');
|
||||||
|
}
|
||||||
|
|
||||||
|
deployApplication().catch(console.error);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📖 API Reference
|
||||||
|
|
||||||
### CloudflareAccount
|
### CloudflareAccount
|
||||||
|
|
||||||
The main entry point for all Cloudflare operations.
|
Main entry point for all operations.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareAccount {
|
class CloudflareAccount {
|
||||||
constructor(apiToken: string);
|
constructor(apiToken: string)
|
||||||
|
|
||||||
// Account management
|
|
||||||
async listAccounts(): Promise<Array<ICloudflareTypes['Account']>>;
|
|
||||||
async preselectAccountByName(accountName: string): Promise<void>;
|
|
||||||
|
|
||||||
// Managers
|
// Managers
|
||||||
readonly zoneManager: ZoneManager;
|
readonly recordManager: RecordManager
|
||||||
readonly workerManager: WorkerManager;
|
readonly zoneManager: ZoneManager
|
||||||
|
readonly workerManager: WorkerManager
|
||||||
|
|
||||||
// Official Cloudflare client
|
// Methods
|
||||||
readonly apiAccount: cloudflare.Cloudflare;
|
async preselectAccountByName(name: string): Promise<void>
|
||||||
|
getConvenientDnsProvider(): ConvenientDnsProvider
|
||||||
|
|
||||||
// Convenience namespace with helper methods
|
// Official Cloudflare SDK client (for advanced use)
|
||||||
readonly convenience: {
|
readonly apiAccount: Cloudflare
|
||||||
// Zone operations
|
}
|
||||||
listZones(domainName?: string): Promise<CloudflareZone[]>;
|
```
|
||||||
getZoneId(domainName: string): Promise<string>;
|
|
||||||
purgeZone(domainName: string): Promise<void>;
|
|
||||||
|
|
||||||
// DNS operations
|
### RecordManager
|
||||||
listRecords(domainName: string): Promise<CloudflareRecord[]>;
|
|
||||||
getRecord(domainName: string, recordType: string): Promise<CloudflareRecord | undefined>;
|
|
||||||
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
|
DNS record management with clean, predictable methods.
|
||||||
acmeSetDnsChallenge(dnsChallenge: IDnsChallenge): Promise<any>;
|
|
||||||
acmeRemoveDnsChallenge(dnsChallenge: IDnsChallenge): Promise<any>;
|
```typescript
|
||||||
};
|
class RecordManager {
|
||||||
|
async listRecords(domain: string): Promise<CloudflareRecord[]>
|
||||||
|
async getRecord(domain: string, type: string): Promise<CloudflareRecord | undefined>
|
||||||
|
async createRecord(domain: string, type: string, content: string, ttl?: number): Promise<CloudflareRecord>
|
||||||
|
async updateRecord(domain: string, type: string, content: string, ttl?: number): Promise<CloudflareRecord>
|
||||||
|
async deleteRecord(domain: string, type: string): Promise<void>
|
||||||
|
async cleanRecords(domain: string, type: string): Promise<void>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### ZoneManager
|
||||||
|
|
||||||
|
Zone (domain) management operations.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
class ZoneManager {
|
||||||
|
async listZones(name?: string): Promise<CloudflareZone[]>
|
||||||
|
async getZoneById(id: string): Promise<CloudflareZone | undefined>
|
||||||
|
async getZoneByName(name: string): Promise<CloudflareZone | undefined>
|
||||||
|
async getZoneId(domain: string): Promise<string>
|
||||||
|
async createZone(name: string): Promise<CloudflareZone | undefined>
|
||||||
|
async deleteZone(id: string): Promise<boolean>
|
||||||
|
async purgeZone(domain: string): Promise<void>
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareZone
|
### CloudflareZone
|
||||||
|
|
||||||
Represents a Cloudflare zone (domain).
|
Zone instance with convenience methods.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareZone {
|
class CloudflareZone {
|
||||||
// Properties
|
readonly id: string
|
||||||
readonly id: string;
|
readonly name: string
|
||||||
readonly name: string;
|
readonly status: string
|
||||||
readonly status: string;
|
|
||||||
readonly paused: boolean;
|
|
||||||
readonly type: string;
|
|
||||||
readonly nameServers: string[];
|
|
||||||
|
|
||||||
// Methods
|
async purgeCache(): Promise<void>
|
||||||
async purgeCache(): Promise<any>;
|
async purgeUrls(urls: string[]): Promise<void>
|
||||||
async purgeUrls(urls: string[]): Promise<any>;
|
async isActive(): Promise<boolean>
|
||||||
async isActive(): Promise<boolean>;
|
async isUsingCloudflareNameservers(): Promise<boolean>
|
||||||
async isUsingCloudflareNameservers(): Promise<boolean>;
|
async enableDevelopmentMode(): Promise<void>
|
||||||
async isDevelopmentModeActive(): Promise<boolean>;
|
async disableDevelopmentMode(): Promise<void>
|
||||||
async enableDevelopmentMode(): Promise<any>;
|
|
||||||
async disableDevelopmentMode(): Promise<any>;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareRecord
|
### WorkerManager
|
||||||
|
|
||||||
Represents a DNS record.
|
Cloudflare Workers deployment and management.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareRecord {
|
class WorkerManager {
|
||||||
// Properties
|
async listWorkers(): Promise<WorkerScript[]>
|
||||||
readonly id: string;
|
async getWorker(name: string): Promise<CloudflareWorker | undefined>
|
||||||
readonly type: string;
|
async createWorker(name: string, script: string): Promise<CloudflareWorker>
|
||||||
readonly name: string;
|
async deleteWorker(name: string): Promise<boolean>
|
||||||
readonly content: string;
|
|
||||||
readonly ttl: number;
|
|
||||||
readonly proxied: boolean;
|
|
||||||
|
|
||||||
// Methods
|
|
||||||
async update(content: string, ttl?: number): Promise<any>;
|
|
||||||
async delete(): Promise<any>;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### CloudflareWorker
|
### CloudflareWorker
|
||||||
|
|
||||||
Represents a Cloudflare Worker.
|
Worker instance for route management and updates.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
class CloudflareWorker {
|
class CloudflareWorker {
|
||||||
// Properties
|
readonly id: string
|
||||||
readonly id: string;
|
readonly script: string
|
||||||
readonly script: string;
|
readonly routes: WorkerRoute[]
|
||||||
readonly routes: IWorkerRoute[];
|
|
||||||
|
|
||||||
// Methods
|
async listRoutes(): Promise<void>
|
||||||
async getRoutes(): Promise<IWorkerRoute[]>;
|
async setRoutes(routes: WorkerRouteDefinition[]): Promise<void>
|
||||||
async setRoutes(routes: Array<IWorkerRouteDefinition>): Promise<void>;
|
async updateScript(script: string): Promise<CloudflareWorker>
|
||||||
async updateScript(scriptContent: string): Promise<CloudflareWorker>;
|
async delete(): Promise<boolean>
|
||||||
async delete(): Promise<boolean>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface IWorkerRouteDefinition {
|
interface WorkerRouteDefinition {
|
||||||
zoneName: string;
|
zoneName: string
|
||||||
pattern: string;
|
pattern: string
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Utility Functions
|
### ConvenientDnsProvider
|
||||||
|
|
||||||
The library includes helpful utility functions:
|
Adapter for third-party modules requiring `IConvenientDnsProvider`.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Validate a domain name
|
class ConvenientDnsProvider implements IConvenientDnsProvider {
|
||||||
CloudflareUtils.isValidDomain('example.com'); // true
|
async createRecord(domain: string, type: string, content: string, ttl?: number): Promise<any>
|
||||||
|
async updateRecord(domain: string, type: string, content: string, ttl?: number): Promise<any>
|
||||||
// Extract zone name from a domain
|
async removeRecord(domain: string, type: string): Promise<any>
|
||||||
CloudflareUtils.getZoneName('subdomain.example.com'); // 'example.com'
|
async getRecord(domain: string, type: string): Promise<any | undefined>
|
||||||
|
async listRecords(domain: string): Promise<any[]>
|
||||||
// Validate a record type
|
async cleanRecord(domain: string, type: string): Promise<void>
|
||||||
CloudflareUtils.isValidRecordType('A'); // true
|
async isDomainSupported(domain: string): Promise<boolean>
|
||||||
|
async acmeSetDnsChallenge(challenge: DnsChallenge): Promise<void>
|
||||||
// Format URL for cache purging
|
async acmeRemoveDnsChallenge(challenge: DnsChallenge): Promise<void>
|
||||||
CloudflareUtils.formatUrlForPurge('example.com/page'); // 'https://example.com/page'
|
}
|
||||||
|
|
||||||
// Format TTL value
|
|
||||||
CloudflareUtils.formatTtl(3600); // '1 hour'
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## What's New in 6.2.0
|
## 🔄 Migration from 6.x
|
||||||
|
|
||||||
- **Improved async iterator support**: Fully leverages the official Cloudflare client's async iterator pattern
|
Version 7.0 introduces a cleaner architecture while maintaining **full backward compatibility**.
|
||||||
- **Enhanced error handling**: Better error detection and recovery
|
|
||||||
- **Simplified API**: More consistent method signatures and return types
|
|
||||||
- **Better type safety**: Improved TypeScript typing throughout the library
|
|
||||||
- **Detailed logging**: More informative logging for easier debugging
|
|
||||||
|
|
||||||
## Development & Testing
|
### What Changed
|
||||||
|
|
||||||
To build the project:
|
✅ **New manager-based API** - Clean, logical organization
|
||||||
|
✅ **Consistent naming** - All list operations use `list*()`
|
||||||
|
✅ **IConvenientDnsProvider support** - Better third-party integration
|
||||||
|
⚠️ **Deprecated `convenience` namespace** - Still works, but use managers instead
|
||||||
|
|
||||||
|
### Migration Examples
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// ❌ Old (deprecated but still works)
|
||||||
|
await cf.convenience.createRecord('example.com', 'A', '1.2.3.4');
|
||||||
|
await cf.convenience.listZones();
|
||||||
|
await cf.workerManager.listWorkerScripts();
|
||||||
|
await worker.getRoutes();
|
||||||
|
|
||||||
|
// ✅ New (recommended)
|
||||||
|
await cf.recordManager.createRecord('example.com', 'A', '1.2.3.4');
|
||||||
|
await cf.zoneManager.listZones();
|
||||||
|
await cf.workerManager.listWorkers();
|
||||||
|
await worker.listRoutes();
|
||||||
|
```
|
||||||
|
|
||||||
|
**No Breaking Changes**: Your existing code will continue to work. The old `convenience` namespace methods now show deprecation warnings in TypeScript with clear migration paths.
|
||||||
|
|
||||||
|
## 🛠️ Development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm run build
|
# Install dependencies
|
||||||
# or
|
pnpm install
|
||||||
pnpm run build
|
|
||||||
|
# Build
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
# Run tests
|
||||||
|
pnpm test
|
||||||
```
|
```
|
||||||
|
|
||||||
To run tests:
|
## 📝 TypeScript Configuration
|
||||||
|
|
||||||
```bash
|
This library is written in TypeScript and provides complete type definitions. No `@types` package needed!
|
||||||
npm test
|
|
||||||
# or
|
```typescript
|
||||||
pnpm run test
|
import { CloudflareAccount, CloudflareZone, CloudflareRecord } from '@apiclient.xyz/cloudflare';
|
||||||
|
|
||||||
|
// Full type inference and autocompletion
|
||||||
|
const cf = new CloudflareAccount(token);
|
||||||
|
const zones: CloudflareZone[] = await cf.zoneManager.listZones();
|
||||||
|
const record: CloudflareRecord = await cf.recordManager.createRecord(/* ... */);
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## 🤔 FAQ
|
||||||
|
|
||||||
MIT © [Lossless GmbH](https://lossless.gmbh)
|
**Q: Can I use this with the official Cloudflare SDK?**
|
||||||
|
A: Yes! The library wraps the official SDK. You can access it directly via `cfAccount.apiAccount` for advanced operations.
|
||||||
|
|
||||||
|
**Q: Does this support Cloudflare Workers KV, R2, D1?**
|
||||||
|
A: Currently focuses on zones, DNS, and Workers. Additional features coming in future releases.
|
||||||
|
|
||||||
|
**Q: How do I handle errors?**
|
||||||
|
A: All methods throw descriptive errors. Wrap calls in try/catch for error handling.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
try {
|
||||||
|
await cf.recordManager.createRecord('example.com', 'A', 'invalid-ip');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to create record:', error.message);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Q: Is this production-ready?**
|
||||||
|
A: Absolutely! Used in production environments. Comprehensive error handling and logging built-in.
|
||||||
|
|
||||||
|
## License and Legal Information
|
||||||
|
|
||||||
|
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||||
|
|
||||||
|
**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 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, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||||
|
|
||||||
|
### Company Information
|
||||||
|
|
||||||
|
Task Venture Capital GmbH
|
||||||
|
Registered at District court Bremen HRB 35230 HB, Germany
|
||||||
|
|
||||||
|
For any legal inquiries or if you require 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.
|
||||||
|
|||||||
@@ -236,7 +236,7 @@ tap.test('should list workers', async (tools) => {
|
|||||||
tools.timeout(600000);
|
tools.timeout(600000);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const workerArray = await testCloudflareAccount.workerManager.listWorkerScripts();
|
const workerArray = await testCloudflareAccount.workerManager.listWorkers();
|
||||||
expect(workerArray).toBeTypeOf('array');
|
expect(workerArray).toBeTypeOf('array');
|
||||||
console.log(`Found ${workerArray.length} workers in account`);
|
console.log(`Found ${workerArray.length} workers in account`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@apiclient.xyz/cloudflare',
|
name: '@apiclient.xyz/cloudflare',
|
||||||
version: '6.4.3',
|
version: '7.1.0',
|
||||||
description: 'A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.'
|
description: 'A TypeScript client for managing Cloudflare accounts, zones, DNS records, and workers with ease.'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import * as interfaces from './interfaces/index.js';
|
|||||||
// interfaces
|
// interfaces
|
||||||
import { WorkerManager } from './cloudflare.classes.workermanager.js';
|
import { WorkerManager } from './cloudflare.classes.workermanager.js';
|
||||||
import { ZoneManager } from './cloudflare.classes.zonemanager.js';
|
import { ZoneManager } from './cloudflare.classes.zonemanager.js';
|
||||||
|
import { RecordManager } from './cloudflare.classes.recordmanager.js';
|
||||||
|
import { ConvenientDnsProvider } from './cloudflare.classes.convenientdnsprovider.js';
|
||||||
|
|
||||||
export class CloudflareAccount implements plugins.tsclass.network.IConvenientDnsProvider {
|
export class CloudflareAccount implements plugins.tsclass.network.IConvenientDnsProvider {
|
||||||
private authToken: string;
|
private authToken: string;
|
||||||
@@ -12,6 +14,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
|
|
||||||
public workerManager = new WorkerManager(this);
|
public workerManager = new WorkerManager(this);
|
||||||
public zoneManager = new ZoneManager(this);
|
public zoneManager = new ZoneManager(this);
|
||||||
|
public recordManager = new RecordManager(this);
|
||||||
|
|
||||||
public apiAccount: plugins.cloudflare.Cloudflare;
|
public apiAccount: plugins.cloudflare.Cloudflare;
|
||||||
|
|
||||||
@@ -133,6 +136,16 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a ConvenientDnsProvider instance that implements IConvenientDnsProvider
|
||||||
|
* This allows third-party modules to use the standard DNS provider interface
|
||||||
|
* while internally delegating to the clean RecordManager and ZoneManager structure
|
||||||
|
* @returns ConvenientDnsProvider instance
|
||||||
|
*/
|
||||||
|
public getConvenientDnsProvider(): ConvenientDnsProvider {
|
||||||
|
return new ConvenientDnsProvider(this);
|
||||||
|
}
|
||||||
|
|
||||||
public convenience = {
|
public convenience = {
|
||||||
/**
|
/**
|
||||||
* Lists all accounts accessible with the current API token
|
* Lists all accounts accessible with the current API token
|
||||||
@@ -157,6 +170,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
/**
|
/**
|
||||||
* gets a zone id of a domain from cloudflare
|
* gets a zone id of a domain from cloudflare
|
||||||
* @param domainName
|
* @param domainName
|
||||||
|
* @deprecated Use zoneManager.getZoneId() instead
|
||||||
*/
|
*/
|
||||||
getZoneId: async (domainName: string) => {
|
getZoneId: async (domainName: string) => {
|
||||||
const domain = new plugins.smartstring.Domain(domainName);
|
const domain = new plugins.smartstring.Domain(domainName);
|
||||||
@@ -175,6 +189,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
* gets a record
|
* gets a record
|
||||||
* @param domainNameArg
|
* @param domainNameArg
|
||||||
* @param typeArg
|
* @param typeArg
|
||||||
|
* @deprecated Use recordManager.getRecord() or getConvenientDnsProvider().getRecord() instead
|
||||||
*/
|
*/
|
||||||
getRecord: async (
|
getRecord: async (
|
||||||
domainNameArg: string,
|
domainNameArg: string,
|
||||||
@@ -204,6 +219,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* creates a record
|
* creates a record
|
||||||
|
* @deprecated Use recordManager.createRecord() or getConvenientDnsProvider().createRecord() instead
|
||||||
*/
|
*/
|
||||||
createRecord: async (
|
createRecord: async (
|
||||||
domainNameArg: string,
|
domainNameArg: string,
|
||||||
@@ -226,6 +242,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
* removes a record from Cloudflare
|
* removes a record from Cloudflare
|
||||||
* @param domainNameArg
|
* @param domainNameArg
|
||||||
* @param typeArg
|
* @param typeArg
|
||||||
|
* @deprecated Use recordManager.deleteRecord() or getConvenientDnsProvider().removeRecord() instead
|
||||||
*/
|
*/
|
||||||
removeRecord: async (
|
removeRecord: async (
|
||||||
domainNameArg: string,
|
domainNameArg: string,
|
||||||
@@ -251,6 +268,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* cleanrecord allows the cleaning of any previous records to avoid unwanted sideeffects
|
* cleanrecord allows the cleaning of any previous records to avoid unwanted sideeffects
|
||||||
|
* @deprecated Use recordManager.cleanRecords() or getConvenientDnsProvider().cleanRecord() instead
|
||||||
*/
|
*/
|
||||||
cleanRecord: async (domainNameArg: string, typeArg: plugins.tsclass.network.TDnsRecordType) => {
|
cleanRecord: async (domainNameArg: string, typeArg: plugins.tsclass.network.TDnsRecordType) => {
|
||||||
try {
|
try {
|
||||||
@@ -312,6 +330,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
* @param contentArg New content for the record
|
* @param contentArg New content for the record
|
||||||
* @param ttlArg Time to live in seconds (optional)
|
* @param ttlArg Time to live in seconds (optional)
|
||||||
* @returns Updated record
|
* @returns Updated record
|
||||||
|
* @deprecated Use recordManager.updateRecord() or getConvenientDnsProvider().updateRecord() instead
|
||||||
*/
|
*/
|
||||||
updateRecord: async (
|
updateRecord: async (
|
||||||
domainNameArg: string,
|
domainNameArg: string,
|
||||||
@@ -348,6 +367,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
/**
|
/**
|
||||||
* list all records of a specified domain name
|
* list all records of a specified domain name
|
||||||
* @param domainNameArg - the domain name that you want to get the records from
|
* @param domainNameArg - the domain name that you want to get the records from
|
||||||
|
* @deprecated Use recordManager.listRecords() or getConvenientDnsProvider().listRecords() instead
|
||||||
*/
|
*/
|
||||||
listRecords: async (domainNameArg: string) => {
|
listRecords: async (domainNameArg: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -372,6 +392,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
/**
|
/**
|
||||||
* list all zones in the associated authenticated account
|
* list all zones in the associated authenticated account
|
||||||
* @param domainName optional filter by domain name
|
* @param domainName optional filter by domain name
|
||||||
|
* @deprecated Use zoneManager.listZones() instead
|
||||||
*/
|
*/
|
||||||
listZones: async (domainName?: string) => {
|
listZones: async (domainName?: string) => {
|
||||||
try {
|
try {
|
||||||
@@ -401,6 +422,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
* Determines whether the given domain can be managed by this account
|
* Determines whether the given domain can be managed by this account
|
||||||
* @param domainName Full domain name to check (e.g., "sub.example.com")
|
* @param domainName Full domain name to check (e.g., "sub.example.com")
|
||||||
* @returns True if the zone for the domain exists in the account, false otherwise
|
* @returns True if the zone for the domain exists in the account, false otherwise
|
||||||
|
* @deprecated Use getConvenientDnsProvider().isDomainSupported() instead
|
||||||
*/
|
*/
|
||||||
isDomainSupported: async (domainName: string): Promise<boolean> => {
|
isDomainSupported: async (domainName: string): Promise<boolean> => {
|
||||||
try {
|
try {
|
||||||
@@ -417,6 +439,7 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* purges a zone
|
* purges a zone
|
||||||
|
* @deprecated Use zoneManager.purgeZone() instead
|
||||||
*/
|
*/
|
||||||
purgeZone: async (domainName: string): Promise<void> => {
|
purgeZone: async (domainName: string): Promise<void> => {
|
||||||
const domain = new plugins.smartstring.Domain(domainName);
|
const domain = new plugins.smartstring.Domain(domainName);
|
||||||
@@ -428,6 +451,9 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
},
|
},
|
||||||
|
|
||||||
// acme convenience functions
|
// acme convenience functions
|
||||||
|
/**
|
||||||
|
* @deprecated Use getConvenientDnsProvider().acmeSetDnsChallenge() instead
|
||||||
|
*/
|
||||||
acmeSetDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
|
acmeSetDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
|
||||||
await this.convenience.cleanRecord(dnsChallenge.hostName, 'TXT');
|
await this.convenience.cleanRecord(dnsChallenge.hostName, 'TXT');
|
||||||
await this.convenience.createRecord(
|
await this.convenience.createRecord(
|
||||||
@@ -437,6 +463,9 @@ export class CloudflareAccount implements plugins.tsclass.network.IConvenientDns
|
|||||||
120,
|
120,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* @deprecated Use getConvenientDnsProvider().acmeRemoveDnsChallenge() instead
|
||||||
|
*/
|
||||||
acmeRemoveDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
|
acmeRemoveDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
|
||||||
await this.convenience.removeRecord(dnsChallenge.hostName, 'TXT');
|
await this.convenience.removeRecord(dnsChallenge.hostName, 'TXT');
|
||||||
},
|
},
|
||||||
|
|||||||
178
ts/cloudflare.classes.convenientdnsprovider.ts
Normal file
178
ts/cloudflare.classes.convenientdnsprovider.ts
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
import * as plugins from './cloudflare.plugins.js';
|
||||||
|
import { logger } from './cloudflare.logger.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adapter class that implements IConvenientDnsProvider interface
|
||||||
|
* Delegates to RecordManager and ZoneManager internally for clean architecture
|
||||||
|
* This allows third-party modules to use the standard DNS provider interface
|
||||||
|
*/
|
||||||
|
export class ConvenientDnsProvider implements plugins.tsclass.network.IConvenientDnsProvider {
|
||||||
|
/**
|
||||||
|
* The convenience property is required by IConvenientDnsProvider interface
|
||||||
|
* It returns this instance to maintain interface compatibility
|
||||||
|
*/
|
||||||
|
public convenience = this;
|
||||||
|
|
||||||
|
constructor(private cfAccount: any) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new DNS record
|
||||||
|
* @param domainNameArg - The domain name for the record
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
* @param contentArg - The record content (IP address, CNAME target, etc.)
|
||||||
|
* @param ttlArg - Time to live in seconds (default: 1 = automatic)
|
||||||
|
* @returns Created record as raw API object
|
||||||
|
*/
|
||||||
|
public async createRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
contentArg: string,
|
||||||
|
ttlArg: number = 1,
|
||||||
|
): Promise<any> {
|
||||||
|
const record = await this.cfAccount.recordManager.createRecord(
|
||||||
|
domainNameArg,
|
||||||
|
typeArg,
|
||||||
|
contentArg,
|
||||||
|
ttlArg,
|
||||||
|
);
|
||||||
|
// Return raw API object format for interface compatibility
|
||||||
|
return this.recordToApiObject(record);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates an existing DNS record, or creates it if it doesn't exist
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
* @param contentArg - The new record content
|
||||||
|
* @param ttlArg - Time to live in seconds (default: 1 = automatic)
|
||||||
|
* @returns Updated record as raw API object
|
||||||
|
*/
|
||||||
|
public async updateRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
contentArg: string,
|
||||||
|
ttlArg: number = 1,
|
||||||
|
): Promise<any> {
|
||||||
|
const record = await this.cfAccount.recordManager.updateRecord(
|
||||||
|
domainNameArg,
|
||||||
|
typeArg,
|
||||||
|
contentArg,
|
||||||
|
ttlArg,
|
||||||
|
);
|
||||||
|
return this.recordToApiObject(record);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a DNS record
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
*/
|
||||||
|
public async removeRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<any> {
|
||||||
|
await this.cfAccount.recordManager.deleteRecord(domainNameArg, typeArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a specific DNS record by domain and type
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
* @returns Record as raw API object or undefined if not found
|
||||||
|
*/
|
||||||
|
public async getRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<any | undefined> {
|
||||||
|
const record = await this.cfAccount.recordManager.getRecord(domainNameArg, typeArg);
|
||||||
|
return record ? this.recordToApiObject(record) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lists all DNS records for a domain
|
||||||
|
* @param domainNameArg - The domain name to list records for
|
||||||
|
* @returns Array of records as raw API objects
|
||||||
|
*/
|
||||||
|
public async listRecords(domainNameArg: string): Promise<any[]> {
|
||||||
|
const records = await this.cfAccount.recordManager.listRecords(domainNameArg);
|
||||||
|
return records.map((record: any) => this.recordToApiObject(record));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes all DNS records of a specific type for a domain
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type to clean
|
||||||
|
*/
|
||||||
|
public async cleanRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.cfAccount.recordManager.cleanRecords(domainNameArg, typeArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines whether the given domain can be managed by this account
|
||||||
|
* @param domainName - Full domain name to check (e.g., "sub.example.com")
|
||||||
|
* @returns True if the zone for the domain exists in the account, false otherwise
|
||||||
|
*/
|
||||||
|
public async isDomainSupported(domainName: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
// Parse out the apex/zone name from the full domain
|
||||||
|
const domain = new plugins.smartstring.Domain(domainName);
|
||||||
|
// List zones filtered by the zone name
|
||||||
|
const zones = await this.cfAccount.zoneManager.listZones(domain.zoneName);
|
||||||
|
// If any zone matches, we can manage this domain
|
||||||
|
return Array.isArray(zones) && zones.length > 0;
|
||||||
|
} catch (error) {
|
||||||
|
logger.log('error', `Error checking domain support for ${domainName}: ${error.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets an ACME DNS challenge for domain verification
|
||||||
|
* @param dnsChallenge - The DNS challenge object
|
||||||
|
*/
|
||||||
|
public async acmeSetDnsChallenge(
|
||||||
|
dnsChallenge: plugins.tsclass.network.IDnsChallenge,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.cfAccount.recordManager.cleanRecords(dnsChallenge.hostName, 'TXT');
|
||||||
|
await this.cfAccount.recordManager.createRecord(
|
||||||
|
dnsChallenge.hostName,
|
||||||
|
'TXT',
|
||||||
|
dnsChallenge.challenge,
|
||||||
|
120,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes an ACME DNS challenge
|
||||||
|
* @param dnsChallenge - The DNS challenge object
|
||||||
|
*/
|
||||||
|
public async acmeRemoveDnsChallenge(
|
||||||
|
dnsChallenge: plugins.tsclass.network.IDnsChallenge,
|
||||||
|
): Promise<void> {
|
||||||
|
await this.cfAccount.recordManager.deleteRecord(dnsChallenge.hostName, 'TXT');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to convert CloudflareRecord instance to raw API object format
|
||||||
|
* This ensures compatibility with the IConvenientDnsProvider interface
|
||||||
|
*/
|
||||||
|
private recordToApiObject(record: any): any {
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
type: record.type,
|
||||||
|
name: record.name,
|
||||||
|
content: record.content,
|
||||||
|
proxiable: record.proxiable,
|
||||||
|
proxied: record.proxied,
|
||||||
|
ttl: record.ttl,
|
||||||
|
locked: record.locked,
|
||||||
|
zone_id: record.zone_id,
|
||||||
|
zone_name: record.zone_name,
|
||||||
|
created_on: record.created_on,
|
||||||
|
modified_on: record.modified_on,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
198
ts/cloudflare.classes.recordmanager.ts
Normal file
198
ts/cloudflare.classes.recordmanager.ts
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
import * as plugins from './cloudflare.plugins.js';
|
||||||
|
import { logger } from './cloudflare.logger.js';
|
||||||
|
import { CloudflareRecord } from './cloudflare.classes.record.js';
|
||||||
|
|
||||||
|
export class RecordManager {
|
||||||
|
constructor(private cfAccount: any) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lists all DNS records for a domain
|
||||||
|
* @param domainNameArg - The domain name to list records for
|
||||||
|
* @returns Array of CloudflareRecord instances
|
||||||
|
*/
|
||||||
|
public async listRecords(domainNameArg: string): Promise<CloudflareRecord[]> {
|
||||||
|
try {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain.zoneName);
|
||||||
|
const records: plugins.ICloudflareTypes['Record'][] = [];
|
||||||
|
|
||||||
|
// Collect all records using async iterator
|
||||||
|
for await (const record of this.cfAccount.apiAccount.dns.records.list({
|
||||||
|
zone_id: zoneId,
|
||||||
|
})) {
|
||||||
|
records.push(record);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.log('info', `Found ${records.length} DNS records for ${domainNameArg}`);
|
||||||
|
|
||||||
|
// Convert to CloudflareRecord instances
|
||||||
|
return records.map(record => CloudflareRecord.createFromApiObject(record));
|
||||||
|
} catch (error) {
|
||||||
|
logger.log('error', `Failed to list records for ${domainNameArg}: ${error.message}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a specific DNS record by domain and type
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type (A, AAAA, CNAME, TXT, etc.)
|
||||||
|
* @returns CloudflareRecord instance or undefined if not found
|
||||||
|
*/
|
||||||
|
public async getRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<CloudflareRecord | undefined> {
|
||||||
|
try {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const recordArray = await this.listRecords(domain.zoneName);
|
||||||
|
|
||||||
|
const filteredRecords = recordArray.filter((recordArg) => {
|
||||||
|
return recordArg.type === typeArg && recordArg.name === domainNameArg;
|
||||||
|
});
|
||||||
|
|
||||||
|
return filteredRecords.length > 0 ? filteredRecords[0] : undefined;
|
||||||
|
} catch (error) {
|
||||||
|
logger.log('error', `Error getting record for ${domainNameArg}: ${error.message}`);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new DNS record
|
||||||
|
* @param domainNameArg - The domain name for the record
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
* @param contentArg - The record content (IP address, CNAME target, etc.)
|
||||||
|
* @param ttlArg - Time to live in seconds (default: 1 = automatic)
|
||||||
|
* @returns Created CloudflareRecord instance
|
||||||
|
*/
|
||||||
|
public async createRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
contentArg: string,
|
||||||
|
ttlArg: number = 1,
|
||||||
|
): Promise<CloudflareRecord> {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain.zoneName);
|
||||||
|
|
||||||
|
const response = await this.cfAccount.apiAccount.dns.records.create({
|
||||||
|
zone_id: zoneId,
|
||||||
|
type: typeArg as any,
|
||||||
|
name: domain.fullName,
|
||||||
|
content: contentArg,
|
||||||
|
ttl: ttlArg,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.log('info', `Created ${typeArg} record for ${domainNameArg}`);
|
||||||
|
return CloudflareRecord.createFromApiObject(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates an existing DNS record, or creates it if it doesn't exist
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
* @param contentArg - The new record content
|
||||||
|
* @param ttlArg - Time to live in seconds (default: 1 = automatic)
|
||||||
|
* @returns Updated CloudflareRecord instance
|
||||||
|
*/
|
||||||
|
public async updateRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
contentArg: string,
|
||||||
|
ttlArg: number = 1,
|
||||||
|
): Promise<CloudflareRecord> {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain.zoneName);
|
||||||
|
|
||||||
|
// Find existing record
|
||||||
|
const existingRecord = await this.getRecord(domainNameArg, typeArg);
|
||||||
|
|
||||||
|
if (!existingRecord) {
|
||||||
|
logger.log(
|
||||||
|
'warn',
|
||||||
|
`Record ${domainNameArg} of type ${typeArg} not found for update, creating instead`,
|
||||||
|
);
|
||||||
|
return this.createRecord(domainNameArg, typeArg, contentArg, ttlArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the record
|
||||||
|
const updatedRecord = await this.cfAccount.apiAccount.dns.records.edit(existingRecord.id, {
|
||||||
|
zone_id: zoneId,
|
||||||
|
type: typeArg as any,
|
||||||
|
name: domain.fullName,
|
||||||
|
content: contentArg,
|
||||||
|
ttl: ttlArg,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.log('info', `Updated ${typeArg} record for ${domainNameArg}`);
|
||||||
|
return CloudflareRecord.createFromApiObject(updatedRecord);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes a DNS record
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type
|
||||||
|
*/
|
||||||
|
public async deleteRecord(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<void> {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain.zoneName);
|
||||||
|
const record = await this.getRecord(domainNameArg, typeArg);
|
||||||
|
|
||||||
|
if (record) {
|
||||||
|
await this.cfAccount.apiAccount.dns.records.delete(record.id, {
|
||||||
|
zone_id: zoneId,
|
||||||
|
});
|
||||||
|
logger.log('info', `Deleted ${typeArg} record for ${domainNameArg}`);
|
||||||
|
} else {
|
||||||
|
logger.log('warn', `Record ${domainNameArg} of type ${typeArg} not found for deletion`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes all DNS records of a specific type for a domain
|
||||||
|
* @param domainNameArg - The domain name
|
||||||
|
* @param typeArg - The DNS record type to clean
|
||||||
|
*/
|
||||||
|
public async cleanRecords(
|
||||||
|
domainNameArg: string,
|
||||||
|
typeArg: plugins.tsclass.network.TDnsRecordType,
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.log('info', `Cleaning ${typeArg} records for ${domainNameArg}`);
|
||||||
|
const domain = new plugins.smartstring.Domain(domainNameArg);
|
||||||
|
const zoneId = await this.cfAccount.zoneManager.getZoneId(domain.zoneName);
|
||||||
|
|
||||||
|
// List all records in the zone for this domain
|
||||||
|
const records = await this.listRecords(domain.zoneName);
|
||||||
|
|
||||||
|
// Only delete records matching the specified name and type
|
||||||
|
const recordsToDelete = records.filter((recordArg) => {
|
||||||
|
return recordArg.type === typeArg && recordArg.name === domainNameArg;
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.log(
|
||||||
|
'info',
|
||||||
|
`Found ${recordsToDelete.length} ${typeArg} records to delete for ${domainNameArg}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const recordToDelete of recordsToDelete) {
|
||||||
|
try {
|
||||||
|
await this.cfAccount.apiAccount.dns.records.delete(recordToDelete.id, {
|
||||||
|
zone_id: zoneId,
|
||||||
|
});
|
||||||
|
logger.log('info', `Deleted ${typeArg} record ${recordToDelete.id} for ${domainNameArg}`);
|
||||||
|
} catch (deleteError) {
|
||||||
|
logger.log('error', `Failed to delete record: ${deleteError.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.log(
|
||||||
|
'error',
|
||||||
|
`Error cleaning ${typeArg} records for ${domainNameArg}: ${error.message}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ export class CloudflareWorker {
|
|||||||
): Promise<CloudflareWorker> {
|
): Promise<CloudflareWorker> {
|
||||||
const newWorker = new CloudflareWorker(workerManager);
|
const newWorker = new CloudflareWorker(workerManager);
|
||||||
Object.assign(newWorker, apiObject);
|
Object.assign(newWorker, apiObject);
|
||||||
await newWorker.getRoutes();
|
await newWorker.listRoutes();
|
||||||
return newWorker;
|
return newWorker;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,9 +41,9 @@ export class CloudflareWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* gets all routes for a worker
|
* Lists all routes for this worker
|
||||||
*/
|
*/
|
||||||
public async getRoutes() {
|
public async listRoutes() {
|
||||||
try {
|
try {
|
||||||
this.routes = []; // Reset routes before fetching
|
this.routes = []; // Reset routes before fetching
|
||||||
|
|
||||||
@@ -102,7 +102,7 @@ export class CloudflareWorker {
|
|||||||
*/
|
*/
|
||||||
public async setRoutes(routeArray: IWorkerRouteDefinition[]) {
|
public async setRoutes(routeArray: IWorkerRouteDefinition[]) {
|
||||||
// First get all existing routes to determine what we need to create/update
|
// First get all existing routes to determine what we need to create/update
|
||||||
await this.getRoutes();
|
await this.listRoutes();
|
||||||
|
|
||||||
for (const newRoute of routeArray) {
|
for (const newRoute of routeArray) {
|
||||||
// Determine whether a route is new, needs an update, or is already up to date
|
// Determine whether a route is new, needs an update, or is already up to date
|
||||||
@@ -156,7 +156,7 @@ export class CloudflareWorker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Refresh routes after all changes
|
// Refresh routes after all changes
|
||||||
await this.getRoutes();
|
await this.listRoutes();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ export class WorkerManager {
|
|||||||
|
|
||||||
// Initialize the worker and get its routes
|
// Initialize the worker and get its routes
|
||||||
try {
|
try {
|
||||||
await worker.getRoutes();
|
await worker.listRoutes();
|
||||||
} catch (routeError) {
|
} catch (routeError) {
|
||||||
logger.log('warn', `Failed to get routes for worker ${workerName}: ${routeError.message}`);
|
logger.log('warn', `Failed to get routes for worker ${workerName}: ${routeError.message}`);
|
||||||
// Continue anyway since the worker was created
|
// Continue anyway since the worker was created
|
||||||
@@ -79,7 +79,7 @@ export class WorkerManager {
|
|||||||
|
|
||||||
// Initialize the worker and get its routes
|
// Initialize the worker and get its routes
|
||||||
try {
|
try {
|
||||||
await worker.getRoutes();
|
await worker.listRoutes();
|
||||||
} catch (routeError) {
|
} catch (routeError) {
|
||||||
logger.log('warn', `Failed to get routes for worker ${workerName}: ${routeError.message}`);
|
logger.log('warn', `Failed to get routes for worker ${workerName}: ${routeError.message}`);
|
||||||
// Continue anyway since we found the worker
|
// Continue anyway since we found the worker
|
||||||
@@ -96,7 +96,7 @@ export class WorkerManager {
|
|||||||
* Lists all worker scripts
|
* Lists all worker scripts
|
||||||
* @returns Array of worker scripts
|
* @returns Array of worker scripts
|
||||||
*/
|
*/
|
||||||
public async listWorkerScripts() {
|
public async listWorkers() {
|
||||||
if (!this.cfAccount.preselectedAccountId) {
|
if (!this.cfAccount.preselectedAccountId) {
|
||||||
throw new Error('No account selected. Please select it first on the account.');
|
throw new Error('No account selected. Please select it first on the account.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ export class ZoneManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all zones, optionally filtered by name
|
* Lists all zones, optionally filtered by name
|
||||||
* @param zoneName Optional zone name to filter by
|
* @param zoneName Optional zone name to filter by
|
||||||
* @returns Array of CloudflareZone instances
|
* @returns Array of CloudflareZone instances
|
||||||
*/
|
*/
|
||||||
public async getZones(zoneName?: string): Promise<CloudflareZone[]> {
|
public async listZones(zoneName?: string): Promise<CloudflareZone[]> {
|
||||||
try {
|
try {
|
||||||
const options: any = { per_page: 50 };
|
const options: any = { per_page: 50 };
|
||||||
|
|
||||||
@@ -37,13 +37,33 @@ export class ZoneManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the zone ID for a domain name
|
||||||
|
* @param domainName Domain name to get the zone ID for
|
||||||
|
* @returns Zone ID string
|
||||||
|
* @throws Error if domain is not found in this account
|
||||||
|
*/
|
||||||
|
public async getZoneId(domainName: string): Promise<string> {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainName);
|
||||||
|
const zoneArray = await this.listZones(domain.zoneName);
|
||||||
|
const filteredResponse = zoneArray.filter((zoneArg) => {
|
||||||
|
return zoneArg.name === domainName;
|
||||||
|
});
|
||||||
|
if (filteredResponse.length >= 1) {
|
||||||
|
return filteredResponse[0].id;
|
||||||
|
} else {
|
||||||
|
logger.log('error', `the domain ${domainName} does not appear to be in this account!`);
|
||||||
|
throw new Error(`the domain ${domainName} does not appear to be in this account!`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a single zone by name
|
* Get a single zone by name
|
||||||
* @param zoneName Zone name to find
|
* @param zoneName Zone name to find
|
||||||
* @returns CloudflareZone instance or undefined if not found
|
* @returns CloudflareZone instance or undefined if not found
|
||||||
*/
|
*/
|
||||||
public async getZoneByName(zoneName: string): Promise<CloudflareZone | undefined> {
|
public async getZoneByName(zoneName: string): Promise<CloudflareZone | undefined> {
|
||||||
const zones = await this.getZones(zoneName);
|
const zones = await this.listZones(zoneName);
|
||||||
return zones.find((zone) => zone.name === zoneName);
|
return zones.find((zone) => zone.name === zoneName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +150,7 @@ export class ZoneManager {
|
|||||||
* @returns True if the zone exists
|
* @returns True if the zone exists
|
||||||
*/
|
*/
|
||||||
public async zoneExists(zoneName: string): Promise<boolean> {
|
public async zoneExists(zoneName: string): Promise<boolean> {
|
||||||
const zones = await this.getZones(zoneName);
|
const zones = await this.listZones(zoneName);
|
||||||
return zones.some((zone) => zone.name === zoneName);
|
return zones.some((zone) => zone.name === zoneName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,4 +200,18 @@ export class ZoneManager {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Purges all cached files for a zone
|
||||||
|
* @param domainName Domain name to purge cache for
|
||||||
|
*/
|
||||||
|
public async purgeZone(domainName: string): Promise<void> {
|
||||||
|
const domain = new plugins.smartstring.Domain(domainName);
|
||||||
|
const zoneId = await this.getZoneId(domain.zoneName);
|
||||||
|
await this.cfAccount.apiAccount.cache.purge({
|
||||||
|
zone_id: zoneId,
|
||||||
|
purge_everything: true,
|
||||||
|
});
|
||||||
|
logger.log('info', `Purged cache for zone ${domainName}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ export {
|
|||||||
} from './cloudflare.classes.worker.js';
|
} from './cloudflare.classes.worker.js';
|
||||||
export { WorkerManager } from './cloudflare.classes.workermanager.js';
|
export { WorkerManager } from './cloudflare.classes.workermanager.js';
|
||||||
export { CloudflareRecord, type ICloudflareRecordInfo } from './cloudflare.classes.record.js';
|
export { CloudflareRecord, type ICloudflareRecordInfo } from './cloudflare.classes.record.js';
|
||||||
|
export { RecordManager } from './cloudflare.classes.recordmanager.js';
|
||||||
export { CloudflareZone } from './cloudflare.classes.zone.js';
|
export { CloudflareZone } from './cloudflare.classes.zone.js';
|
||||||
export { ZoneManager } from './cloudflare.classes.zonemanager.js';
|
export { ZoneManager } from './cloudflare.classes.zonemanager.js';
|
||||||
|
export { ConvenientDnsProvider } from './cloudflare.classes.convenientdnsprovider.js';
|
||||||
export { CloudflareUtils } from './cloudflare.utils.js';
|
export { CloudflareUtils } from './cloudflare.utils.js';
|
||||||
export { commitinfo } from './00_commitinfo_data.js';
|
export { commitinfo } from './00_commitinfo_data.js';
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user