bởi Wenli

Full-featured TypeScript/JavaScript client for the Cloudflare REST API, providing typed request/response models, auto-pagination, retries, file uploads, and cross-runtime shim support.
This block provides the full Cloudflare REST API client for Node.js and TypeScript, generated from Cloudflare's OpenAPI spec via Stainless. It covers every Cloudflare product surface (DNS, KV, Workers, R2, Pages, Zero Trust, and many more) through a strongly-typed SDK with built-in pagination, file upload helpers, and structured error handling. Typical buyers are backend engineers building Cloudflare automation, provisioning scripts, or SaaS platforms that manage Cloudflare resources programmatically.
_shims/ - Runtime shims that normalize fetch, File, FormData, and Agent across Node.js versionsinternal/ - Internal utilities; includes the qs query-string serializer used by the HTTP layerinternal/qs/ - A self-contained query-string stringify library (port of qs) with RFC1738/RFC3986 format supportresources/ - One subdirectory per Cloudflare product (accounts, dns, kv, r2, workers, pages, etc.) with typed request/response classesshims/ - Public re-exports of _shims for consumers who need to swap fetch implementationscore.ts - Base APIClient class, request pipeline, retry logic, timeout handling, and response parsingerror.ts - APIError hierarchy (BadRequestError, AuthenticationError, RateLimitError, etc.)index.ts - Main Cloudflare client class; re-exports all resource namespaces and typespagination.ts - Generic pagination classes: V4PagePagination, CursorPagination, SinglePage, etc.resource.ts - APIResource base class that all product namespaces extendresources.ts - Barrel re-export of every resource namespaceuploads.ts - toFile helper and multipart upload utilitiesversion.ts - SDK version string constantnpm install @types/node @types/node-fetch abort-controller agentkeepalive form-data-encoder formdata-node node-fetch
No native build steps, CocoaPods, or Android linking are required. This is a pure Node.js library; it does not support browser environments without a custom fetch shim.
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 455df31a8128e656…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 7 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
Copy the source/ directory into your project, for example at src/cloudflare-sdk/.
In tsconfig.json, ensure moduleResolution is node16 or bundler, and strict is enabled:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"paths": {
"cloudflare-sdk": ["./src/cloudflare-sdk/index.ts"],
"cloudflare-sdk/*": ["./src/cloudflare-sdk/*"]
}
}
}
export CLOUDFLARE_API_TOKEN="your_token_here"
# Optional alternatives:
export CLOUDFLARE_API_KEY="your_global_key"
export CLOUDFLARE_API_EMAIL="user@example.com"
import Cloudflare from './src/cloudflare-sdk/index';
apiToken defaults to process.env.CLOUDFLARE_API_TOKEN if omitted.Cloudflare (default export)import Cloudflare from './src/cloudflare-sdk/index';
const client = new Cloudflare({
apiToken?: string; // defaults to CLOUDFLARE_API_TOKEN env var
apiKey?: string; // alternative: global API key
apiEmail?: string; // required when using apiKey
baseURL?: string; // override API base URL
timeout?: number; // request timeout in ms (default: 60000)
maxRetries?: number; // automatic retries on 429/5xx (default: 2)
});
The root client exposes every Cloudflare product as a property (e.g., client.zones, client.kv, client.dns, client.r2). Use this when you need a single long-lived client instance shared across your application.
toFileimport { toFile } from './src/cloudflare-sdk/uploads';
const file: File = await toFile(
source: Buffer | Uint8Array | ReadableStream | Blob,
filename?: string,
options?: { type?: string }
): Promise<File>;
Converts arbitrary binary sources into a File object suitable for multipart upload parameters. Use this when you have raw bytes or a stream and need to pass them to any SDK method that accepts a file upload parameter.
APIError and subclassesimport {
APIError,
BadRequestError, // 400
AuthenticationError, // 401
PermissionDeniedError, // 403
NotFoundError, // 404
RateLimitError, // 429
InternalServerError, // 500
} from './src/cloudflare-sdk/error';
// Properties available on any APIError:
error.status: number
error.message: string
error.headers: Headers
Catch APIError to handle all API failures uniformly, or catch specific subclasses for targeted error handling (e.g., exponential backoff on RateLimitError, redirect to login on AuthenticationError).
import {
V4PagePaginationResponse,
CursorPaginationResponse,
SinglePageResponse,
} from './src/cloudflare-sdk/pagination';
All list methods return async iterables. Use for await to transparently walk pages, or call .getPaginatedItems() for the current page's array. The SDK handles fetching subsequent pages automatically.
Create an A record in a zone using the fully typed dns.records.create method.
import Cloudflare from './src/cloudflare-sdk/index';
import { APIError } from './src/cloudflare-sdk/error';
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
async function addDNSRecord(zoneId: string) {
try {
const record = await client.dns.records.create({
zone_id: zoneId,
type: 'A',
name: 'api.example.com',
content: '192.0.2.1',
ttl: 3600,
proxied: false,
});
console.log('Created record:', record.id);
} catch (err) {
if (err instanceof APIError) {
console.error(`API error ${err.status}: ${err.message}`);
}
throw err;
}
}
Iterate over all keys in a KV namespace without manually managing cursors.
import Cloudflare from './src/cloudflare-sdk/index';
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
async function listAllKeys(accountId: string, namespaceId: string) {
const keys: string[] = [];
for await (const key of await client.kv.namespaces.keys.list(namespaceId, {
account_id: accountId,
limit: 100,
})) {
keys.push(key.name);
}
console.log(`Total keys: ${keys.length}`);
return keys;
}
Upload a local file as a KV value using the toFile helper and fs.createReadStream.
import fs from 'fs';
import Cloudflare from './src/cloudflare-sdk/index';
import { toFile } from './src/cloudflare-sdk/uploads';
import { RateLimitError } from './src/cloudflare-sdk/error';
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
async function uploadFileToKV(
accountId: string,
namespaceId: string,
key: string,
filePath: string,
) {
try {
await client.kv.namespaces.values.update(namespaceId, key, {
account_id: accountId,
value: fs.createReadStream(filePath),
metadata: JSON.stringify({ uploadedAt: new Date().toISOString() }),
});
console.log(`Uploaded ${key} successfully`);
} catch (err) {
if (err instanceof RateLimitError) {
console.warn('Rate limited; back off and retry');
}
throw err;
}
}
Provision a new zone under an account with typed request parameters.
import Cloudflare, { type ZoneCreateParams } from './src/cloudflare-sdk/index';
const client = new Cloudflare({ apiToken: process.env.CLOUDFLARE_API_TOKEN });
async function createZone(accountId: string, domainName: string) {
const params: ZoneCreateParams = {
account: { id: accountId },
name: domainName,
type: 'full',
};
const zone = await client.zones.create(params);
console.log(`Zone created: ${zone.id} (status: ${zone.status})`);
return zone;
}
_shims/ - Detects the runtime environment and exports the correct fetch, File, Request, Response, and FormData implementations. Do not import this directly; core.ts consumes it.internal/qs/ - Standalone query-string serializer supporting nested objects, arrays, and RFC1738/RFC3986 encoding. Used by core.ts to serialize URL query parameters.resources/ - Each subdirectory is one Cloudflare product. Every file follows the pattern: a class extending APIResource with methods that call this._client.get/post/put/delete. Index files barrel-export types.shims/ - Thin public wrappers around _shims allowing consumers to import and register custom fetch implementations (e.g., for testing or edge runtimes).core.ts - Houses APIClient with get(), post(), put(), patch(), delete() methods, retry logic with exponential backoff, streaming response support, and header/auth management.error.ts - Defines APIError and all HTTP-status-specific subclasses. APIError.generate() is used internally to produce the right subclass from a raw response.index.ts - Instantiates and wires the top-level Cloudflare class with all resource namespaces attached as properties. This is the consumer entry point.pagination.ts - Generic AbstractPage<T> base class and concrete implementations (V4PagePagination, CursorPagination, SinglePage) that make list results async-iterable.resource.ts - APIResource base class storing a reference to the root client; all resource namespaces extend this.resources.ts - Single barrel file re-exporting every named resource class for convenience imports.uploads.ts - toFile utility and multipart form construction helpers used when request parameters include file data.version.ts - Exports the SDK version string used in the User-Agent header.CLOUDFLARE_API_TOKEN at runtime: The constructor will throw if neither apiToken, apiKey, nor their env vars are present; always validate env vars at app startup.node-fetch: node-fetch v3 is ESM-only; pin to node-fetch@2 if your project uses CommonJS ("type": "commonjs" in package.json).AbortController is not defined on Node < 15: Install and globally assign abort-controller before importing the SDK: global.AbortController = require('abort-controller').for await or call .iterPages() on list results; calling .list() and accessing .result directly gives only the first page."strict": true and "esModuleInterop": true in tsconfig.json; the SDK uses conditional types that require strict mode to resolve correctly.formdata-node version conflicts: If another dependency brings in a different FormData global, the multipart shim may break; explicitly import FormData from formdata-node and pass it via the shim registration before constructing the client.I have dropped the Cloudflare TypeScript SDK source into `src/cloudflare-sdk/` in my project.
The entry point is `src/cloudflare-sdk/index.ts` and exports the default `Cloudflare` client class
along with all resource namespaces (dns, kv, zones, r2, accounts, workers, pages, etc.).
Please read `USAGE.md` and `src/cloudflare-sdk/index.ts` for the full public API surface.
The upstream package this was taken from is `user@example.com`.
My project is a Node.js/TypeScript Express application. I need you to:
1. Install all required dependencies listed in USAGE.md.
2. Create a `src/cloudflare.ts` singleton that instantiates the `Cloudflare` client using
`process.env.CLOUDFLARE_API_TOKEN`.
3. Implement the following feature using real SDK methods from `src/cloudflare-sdk/`:
[DESCRIBE YOUR FEATURE HERE - e.g., "list all DNS records for a zone and return them as JSON
from a GET /dns/:zoneId endpoint"]
4. Add proper error handling using the `APIError` subclasses from `src/cloudflare-sdk/error.ts`.
5. Use `for await` for any paginated list calls.
6. Show me the updated `tsconfig.json` if any path aliases are needed.
Do not invent SDK methods. Only use exports visible in `src/cloudflare-sdk/index.ts`
and the resource index files under `src/cloudflare-sdk/resources/`.
The source is generated from the Cloudflare OpenAPI specification using Stainless. The upstream package is cloudflare published by Cloudflare, Inc. License terms are MIT; see source/LICENSE if present in the distributed archive, or refer to the upstream repository for the authoritative license file.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí