cloudflare/cloudflare-typescript

Public

mirrored from https://github.com/cloudflare/cloudflare-typescriptAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
f363fafacc4eeb2d50cb3a317b6e0884f5b155f2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/index.ts

594lines · modecode

1// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
3import * as Errors from './error';
4import * as Uploads from './uploads';
5import { type Agent } from './_shims/index';
6import * as qs from 'qs';
7import * as Core from './core';
8import * as Pagination from './pagination';
9import * as API from './resources/index';
10
11export interface ClientOptions {
12 /**
13 * Defaults to process.env['CLOUDFLARE_API_TOKEN'].
14 */
15 apiToken?: string | null | undefined;
16
17 /**
18 * Defaults to process.env['CLOUDFLARE_API_KEY'].
19 */
20 apiKey?: string | null | undefined;
21
22 /**
23 * Defaults to process.env['CLOUDFLARE_EMAIL'].
24 */
25 apiEmail?: string | null | undefined;
26
27 /**
28 * Defaults to process.env['CLOUDFLARE_API_USER_SERVICE_KEY'].
29 */
30 userServiceKey?: string | null | undefined;
31
32 /**
33 * Override the default base URL for the API, e.g., "https://api.example.com/v2/"
34 *
35 * Defaults to process.env['CLOUDFLARE_BASE_URL'].
36 */
37 baseURL?: string | null | undefined;
38
39 /**
40 * The maximum amount of time (in milliseconds) that the client should wait for a response
41 * from the server before timing out a single request.
42 *
43 * Note that request timeouts are retried by default, so in a worst-case scenario you may wait
44 * much longer than this timeout before the promise succeeds or fails.
45 */
46 timeout?: number;
47
48 /**
49 * An HTTP agent used to manage HTTP(S) connections.
50 *
51 * If not provided, an agent will be constructed by default in the Node.js environment,
52 * otherwise no agent is used.
53 */
54 httpAgent?: Agent;
55
56 /**
57 * Specify a custom `fetch` function implementation.
58 *
59 * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
60 * defined globally.
61 */
62 fetch?: Core.Fetch | undefined;
63
64 /**
65 * The maximum number of times that the client will retry a request in case of a
66 * temporary failure, like a network error or a 5XX error from the server.
67 *
68 * @default 2
69 */
70 maxRetries?: number;
71
72 /**
73 * Default headers to include with every request to the API.
74 *
75 * These can be removed in individual requests by explicitly setting the
76 * header to `undefined` or `null` in request options.
77 */
78 defaultHeaders?: Core.Headers;
79
80 /**
81 * Default query parameters to include with every request to the API.
82 *
83 * These can be removed in individual requests by explicitly setting the
84 * param to `undefined` in request options.
85 */
86 defaultQuery?: Core.DefaultQuery;
87}
88
89/**
90 * API Client for interfacing with the Cloudflare API.
91 */
92export class Cloudflare extends Core.APIClient {
93 apiToken: string | null;
94 apiKey: string | null;
95 apiEmail: string | null;
96 userServiceKey: string | null;
97
98 private _options: ClientOptions;
99
100 /**
101 * API Client for interfacing with the Cloudflare API.
102 *
103 * @param {string | null | undefined} [opts.apiToken=process.env['CLOUDFLARE_API_TOKEN'] ?? null]
104 * @param {string | null | undefined} [opts.apiKey=process.env['CLOUDFLARE_API_KEY'] ?? null]
105 * @param {string | null | undefined} [opts.apiEmail=process.env['CLOUDFLARE_EMAIL'] ?? null]
106 * @param {string | null | undefined} [opts.userServiceKey=process.env['CLOUDFLARE_API_USER_SERVICE_KEY'] ?? null]
107 * @param {string} [opts.baseURL=process.env['CLOUDFLARE_BASE_URL'] ?? https://api.cloudflare.com/client/v4] - Override the default base URL for the API.
108 * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
109 * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
110 * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
111 * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
112 * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
113 * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
114 */
115 constructor({
116 baseURL = Core.readEnv('CLOUDFLARE_BASE_URL'),
117 apiToken = Core.readEnv('CLOUDFLARE_API_TOKEN') ?? null,
118 apiKey = Core.readEnv('CLOUDFLARE_API_KEY') ?? null,
119 apiEmail = Core.readEnv('CLOUDFLARE_EMAIL') ?? null,
120 userServiceKey = Core.readEnv('CLOUDFLARE_API_USER_SERVICE_KEY') ?? null,
121 ...opts
122 }: ClientOptions = {}) {
123 const options: ClientOptions = {
124 apiToken,
125 apiKey,
126 apiEmail,
127 userServiceKey,
128 ...opts,
129 baseURL: baseURL || `https://api.cloudflare.com/client/v4`,
130 };
131
132 super({
133 baseURL: options.baseURL!,
134 timeout: options.timeout ?? 60000 /* 1 minute */,
135 httpAgent: options.httpAgent,
136 maxRetries: options.maxRetries,
137 fetch: options.fetch,
138 });
139
140 this._options = options;
141
142 this.apiToken = apiToken;
143 this.apiKey = apiKey;
144 this.apiEmail = apiEmail;
145 this.userServiceKey = userServiceKey;
146 }
147
148 accounts: API.Accounts = new API.Accounts(this);
149 originCACertificates: API.OriginCACertificates = new API.OriginCACertificates(this);
150 ips: API.IPs = new API.IPs(this);
151 memberships: API.Memberships = new API.Memberships(this);
152 user: API.User = new API.User(this);
153 zones: API.Zones = new API.Zones(this);
154 loadBalancers: API.LoadBalancers = new API.LoadBalancers(this);
155 cache: API.Cache = new API.Cache(this);
156 ssl: API.SSL = new API.SSL(this);
157 subscriptions: API.Subscriptions = new API.Subscriptions(this);
158 acm: API.ACM = new API.ACM(this);
159 argo: API.Argo = new API.Argo(this);
160 plans: API.Plans = new API.Plans(this);
161 ratePlans: API.RatePlans = new API.RatePlans(this);
162 certificateAuthorities: API.CertificateAuthorities = new API.CertificateAuthorities(this);
163 clientCertificates: API.ClientCertificates = new API.ClientCertificates(this);
164 customCertificates: API.CustomCertificates = new API.CustomCertificates(this);
165 customHostnames: API.CustomHostnames = new API.CustomHostnames(this);
166 customNameservers: API.CustomNameservers = new API.CustomNameservers(this);
167 dns: API.DNS = new API.DNS(this);
168 dnssec: API.DNSSECResource = new API.DNSSECResource(this);
169 emailSecurity: API.EmailSecurity = new API.EmailSecurity(this);
170 emailRouting: API.EmailRouting = new API.EmailRouting(this);
171 filters: API.Filters = new API.Filters(this);
172 firewall: API.Firewall = new API.Firewall(this);
173 healthchecks: API.Healthchecks = new API.Healthchecks(this);
174 keylessCertificates: API.KeylessCertificates = new API.KeylessCertificates(this);
175 logpush: API.Logpush = new API.Logpush(this);
176 logs: API.Logs = new API.Logs(this);
177 originTLSClientAuth: API.OriginTLSClientAuth = new API.OriginTLSClientAuth(this);
178 pagerules: API.Pagerules = new API.Pagerules(this);
179 rateLimits: API.RateLimits = new API.RateLimits(this);
180 secondaryDNS: API.SecondaryDNS = new API.SecondaryDNS(this);
181 waitingRooms: API.WaitingRooms = new API.WaitingRooms(this);
182 web3: API.Web3 = new API.Web3(this);
183 workers: API.Workers = new API.Workers(this);
184 kv: API.KV = new API.KV(this);
185 durableObjects: API.DurableObjects = new API.DurableObjects(this);
186 queues: API.Queues = new API.Queues(this);
187 apiGateway: API.APIGateway = new API.APIGateway(this);
188 managedHeaders: API.ManagedHeaders = new API.ManagedHeaders(this);
189 pageShield: API.PageShield = new API.PageShield(this);
190 rulesets: API.Rulesets = new API.Rulesets(this);
191 urlNormalization: API.URLNormalization = new API.URLNormalization(this);
192 spectrum: API.Spectrum = new API.Spectrum(this);
193 addressing: API.Addressing = new API.Addressing(this);
194 auditLogs: API.AuditLogs = new API.AuditLogs(this);
195 billing: API.Billing = new API.Billing(this);
196 brandProtection: API.BrandProtection = new API.BrandProtection(this);
197 diagnostics: API.Diagnostics = new API.Diagnostics(this);
198 images: API.Images = new API.Images(this);
199 intel: API.Intel = new API.Intel(this);
200 magicTransit: API.MagicTransit = new API.MagicTransit(this);
201 magicNetworkMonitoring: API.MagicNetworkMonitoring = new API.MagicNetworkMonitoring(this);
202 mtlsCertificates: API.MTLSCertificates = new API.MTLSCertificates(this);
203 pages: API.Pages = new API.Pages(this);
204 pcaps: API.PCAPs = new API.PCAPs(this);
205 registrar: API.Registrar = new API.Registrar(this);
206 requestTracers: API.RequestTracers = new API.RequestTracers(this);
207 rules: API.Rules = new API.Rules(this);
208 storage: API.Storage = new API.Storage(this);
209 stream: API.Stream = new API.Stream(this);
210 alerting: API.Alerting = new API.Alerting(this);
211 d1: API.D1Resource = new API.D1Resource(this);
212 r2: API.R2 = new API.R2(this);
213 warpConnector: API.WARPConnector = new API.WARPConnector(this);
214 workersForPlatforms: API.WorkersForPlatforms = new API.WorkersForPlatforms(this);
215 zeroTrust: API.ZeroTrust = new API.ZeroTrust(this);
216 challenges: API.Challenges = new API.Challenges(this);
217 hyperdrive: API.HyperdriveResource = new API.HyperdriveResource(this);
218 rum: API.RUM = new API.RUM(this);
219 vectorize: API.Vectorize = new API.Vectorize(this);
220 urlScanner: API.URLScanner = new API.URLScanner(this);
221 radar: API.Radar = new API.Radar(this);
222 botManagement: API.BotManagement = new API.BotManagement(this);
223 originPostQuantumEncryption: API.OriginPostQuantumEncryption = new API.OriginPostQuantumEncryption(this);
224 speed: API.Speed = new API.Speed(this);
225 dcvDelegation: API.DCVDelegation = new API.DCVDelegation(this);
226 hostnames: API.Hostnames = new API.Hostnames(this);
227 snippets: API.Snippets = new API.Snippets(this);
228 calls: API.Calls = new API.Calls(this);
229 cloudforceOne: API.CloudforceOne = new API.CloudforceOne(this);
230 eventNotifications: API.EventNotifications = new API.EventNotifications(this);
231 aiGateway: API.AIGateway = new API.AIGateway(this);
232 iam: API.IAM = new API.IAM(this);
233 cloudConnector: API.CloudConnector = new API.CloudConnector(this);
234 botnetFeed: API.BotnetFeed = new API.BotnetFeed(this);
235
236 protected override defaultQuery(): Core.DefaultQuery | undefined {
237 return this._options.defaultQuery;
238 }
239
240 protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
241 return {
242 ...super.defaultHeaders(opts),
243 'X-Auth-Key': this.apiKey,
244 'X-Auth-Email': this.apiEmail,
245 ...this._options.defaultHeaders,
246 };
247 }
248
249 protected override validateHeaders(headers: Core.Headers, customHeaders: Core.Headers) {
250 if (this.apiEmail && headers['x-auth-email']) {
251 return;
252 }
253 if (customHeaders['x-auth-email'] === null) {
254 return;
255 }
256
257 if (this.apiKey && headers['x-auth-key']) {
258 return;
259 }
260 if (customHeaders['x-auth-key'] === null) {
261 return;
262 }
263
264 if (this.apiToken && headers['authorization']) {
265 return;
266 }
267 if (customHeaders['authorization'] === null) {
268 return;
269 }
270
271 if (this.userServiceKey && headers['x-auth-user-service-key']) {
272 return;
273 }
274 if (customHeaders['x-auth-user-service-key'] === null) {
275 return;
276 }
277
278 throw new Error(
279 'Could not resolve authentication method. Expected one of apiEmail, apiKey, apiToken or userServiceKey to be set. Or for one of the "X-Auth-Email", "X-Auth-Key", "Authorization" or "X-Auth-User-Service-Key" headers to be explicitly omitted',
280 );
281 }
282
283 protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
284 const apiEmailAuth = this.apiEmailAuth(opts);
285 const apiKeyAuth = this.apiKeyAuth(opts);
286 const apiTokenAuth = this.apiTokenAuth(opts);
287 const userServiceKeyAuth = this.userServiceKeyAuth(opts);
288
289 if (
290 apiEmailAuth != null &&
291 !Core.isEmptyObj(apiEmailAuth) &&
292 apiKeyAuth != null &&
293 !Core.isEmptyObj(apiKeyAuth)
294 ) {
295 return { ...apiEmailAuth, ...apiKeyAuth };
296 }
297
298 if (apiTokenAuth != null && !Core.isEmptyObj(apiTokenAuth)) {
299 return apiTokenAuth;
300 }
301
302 if (userServiceKeyAuth != null && !Core.isEmptyObj(userServiceKeyAuth)) {
303 return userServiceKeyAuth;
304 }
305 return {};
306 }
307
308 protected apiEmailAuth(opts: Core.FinalRequestOptions): Core.Headers {
309 if (this.apiEmail == null) {
310 return {};
311 }
312 return { 'X-Auth-Email': this.apiEmail };
313 }
314
315 protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
316 if (this.apiKey == null) {
317 return {};
318 }
319 return { 'X-Auth-Key': this.apiKey };
320 }
321
322 protected apiTokenAuth(opts: Core.FinalRequestOptions): Core.Headers {
323 if (this.apiToken == null) {
324 return {};
325 }
326 return { Authorization: `Bearer ${this.apiToken}` };
327 }
328
329 protected userServiceKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
330 if (this.userServiceKey == null) {
331 return {};
332 }
333 return { 'X-Auth-User-Service-Key': this.userServiceKey };
334 }
335
336 protected override stringifyQuery(query: Record<string, unknown>): string {
337 return qs.stringify(query, { allowDots: true, arrayFormat: 'repeat' });
338 }
339
340 static Cloudflare = this;
341 static DEFAULT_TIMEOUT = 60000; // 1 minute
342
343 static CloudflareError = Errors.CloudflareError;
344 static APIError = Errors.APIError;
345 static APIConnectionError = Errors.APIConnectionError;
346 static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
347 static APIUserAbortError = Errors.APIUserAbortError;
348 static NotFoundError = Errors.NotFoundError;
349 static ConflictError = Errors.ConflictError;
350 static RateLimitError = Errors.RateLimitError;
351 static BadRequestError = Errors.BadRequestError;
352 static AuthenticationError = Errors.AuthenticationError;
353 static InternalServerError = Errors.InternalServerError;
354 static PermissionDeniedError = Errors.PermissionDeniedError;
355 static UnprocessableEntityError = Errors.UnprocessableEntityError;
356
357 static toFile = Uploads.toFile;
358 static fileFromPath = Uploads.fileFromPath;
359}
360
361export const {
362 CloudflareError,
363 APIError,
364 APIConnectionError,
365 APIConnectionTimeoutError,
366 APIUserAbortError,
367 NotFoundError,
368 ConflictError,
369 RateLimitError,
370 BadRequestError,
371 AuthenticationError,
372 InternalServerError,
373 PermissionDeniedError,
374 UnprocessableEntityError,
375} = Errors;
376
377export import toFile = Uploads.toFile;
378export import fileFromPath = Uploads.fileFromPath;
379
380export namespace Cloudflare {
381 export import RequestOptions = Core.RequestOptions;
382
383 export import V4PagePagination = Pagination.V4PagePagination;
384 export import V4PagePaginationParams = Pagination.V4PagePaginationParams;
385 export import V4PagePaginationResponse = Pagination.V4PagePaginationResponse;
386
387 export import V4PagePaginationArray = Pagination.V4PagePaginationArray;
388 export import V4PagePaginationArrayParams = Pagination.V4PagePaginationArrayParams;
389 export import V4PagePaginationArrayResponse = Pagination.V4PagePaginationArrayResponse;
390
391 export import CursorPagination = Pagination.CursorPagination;
392 export import CursorPaginationParams = Pagination.CursorPaginationParams;
393 export import CursorPaginationResponse = Pagination.CursorPaginationResponse;
394
395 export import CursorLimitPagination = Pagination.CursorLimitPagination;
396 export import CursorLimitPaginationParams = Pagination.CursorLimitPaginationParams;
397 export import CursorLimitPaginationResponse = Pagination.CursorLimitPaginationResponse;
398
399 export import SinglePage = Pagination.SinglePage;
400 export import SinglePageResponse = Pagination.SinglePageResponse;
401
402 export import Accounts = API.Accounts;
403
404 export import OriginCACertificates = API.OriginCACertificates;
405
406 export import IPs = API.IPs;
407
408 export import Memberships = API.Memberships;
409
410 export import User = API.User;
411
412 export import Zones = API.Zones;
413
414 export import LoadBalancers = API.LoadBalancers;
415
416 export import Cache = API.Cache;
417
418 export import SSL = API.SSL;
419
420 export import Subscriptions = API.Subscriptions;
421
422 export import ACM = API.ACM;
423
424 export import Argo = API.Argo;
425
426 export import Plans = API.Plans;
427
428 export import RatePlans = API.RatePlans;
429
430 export import CertificateAuthorities = API.CertificateAuthorities;
431
432 export import ClientCertificates = API.ClientCertificates;
433
434 export import CustomCertificates = API.CustomCertificates;
435
436 export import CustomHostnames = API.CustomHostnames;
437
438 export import CustomNameservers = API.CustomNameservers;
439
440 export import DNS = API.DNS;
441
442 export import DNSSECResource = API.DNSSECResource;
443
444 export import EmailSecurity = API.EmailSecurity;
445
446 export import EmailRouting = API.EmailRouting;
447
448 export import Filters = API.Filters;
449
450 export import Firewall = API.Firewall;
451
452 export import Healthchecks = API.Healthchecks;
453
454 export import KeylessCertificates = API.KeylessCertificates;
455
456 export import Logpush = API.Logpush;
457
458 export import Logs = API.Logs;
459
460 export import OriginTLSClientAuth = API.OriginTLSClientAuth;
461
462 export import Pagerules = API.Pagerules;
463
464 export import RateLimits = API.RateLimits;
465
466 export import SecondaryDNS = API.SecondaryDNS;
467
468 export import WaitingRooms = API.WaitingRooms;
469
470 export import Web3 = API.Web3;
471
472 export import Workers = API.Workers;
473
474 export import KV = API.KV;
475
476 export import DurableObjects = API.DurableObjects;
477
478 export import Queues = API.Queues;
479
480 export import APIGateway = API.APIGateway;
481
482 export import ManagedHeaders = API.ManagedHeaders;
483
484 export import PageShield = API.PageShield;
485
486 export import Rulesets = API.Rulesets;
487
488 export import URLNormalization = API.URLNormalization;
489
490 export import Spectrum = API.Spectrum;
491
492 export import Addressing = API.Addressing;
493
494 export import AuditLogs = API.AuditLogs;
495
496 export import Billing = API.Billing;
497
498 export import BrandProtection = API.BrandProtection;
499
500 export import Diagnostics = API.Diagnostics;
501
502 export import Images = API.Images;
503
504 export import Intel = API.Intel;
505
506 export import MagicTransit = API.MagicTransit;
507
508 export import MagicNetworkMonitoring = API.MagicNetworkMonitoring;
509
510 export import MTLSCertificates = API.MTLSCertificates;
511
512 export import Pages = API.Pages;
513
514 export import PCAPs = API.PCAPs;
515
516 export import Registrar = API.Registrar;
517
518 export import RequestTracers = API.RequestTracers;
519
520 export import Rules = API.Rules;
521
522 export import Storage = API.Storage;
523
524 export import Stream = API.Stream;
525
526 export import Alerting = API.Alerting;
527
528 export import D1Resource = API.D1Resource;
529
530 export import R2 = API.R2;
531
532 export import WARPConnector = API.WARPConnector;
533
534 export import WorkersForPlatforms = API.WorkersForPlatforms;
535
536 export import ZeroTrust = API.ZeroTrust;
537
538 export import Challenges = API.Challenges;
539
540 export import HyperdriveResource = API.HyperdriveResource;
541
542 export import RUM = API.RUM;
543
544 export import Vectorize = API.Vectorize;
545
546 export import URLScanner = API.URLScanner;
547
548 export import Radar = API.Radar;
549
550 export import BotManagement = API.BotManagement;
551
552 export import OriginPostQuantumEncryption = API.OriginPostQuantumEncryption;
553
554 export import Speed = API.Speed;
555
556 export import DCVDelegation = API.DCVDelegation;
557
558 export import Hostnames = API.Hostnames;
559
560 export import Snippets = API.Snippets;
561
562 export import Calls = API.Calls;
563
564 export import CloudforceOne = API.CloudforceOne;
565
566 export import EventNotifications = API.EventNotifications;
567
568 export import AIGateway = API.AIGateway;
569
570 export import IAM = API.IAM;
571
572 export import CloudConnector = API.CloudConnector;
573
574 export import BotnetFeed = API.BotnetFeed;
575
576 export import ASN = API.ASN;
577 export import AuditLog = API.AuditLog;
578 export import CertificateCA = API.CertificateCA;
579 export import CertificateRequestType = API.CertificateRequestType;
580 export import CloudflareTunnel = API.CloudflareTunnel;
581 export import ErrorData = API.ErrorData;
582 export import Identifier = API.Identifier;
583 export import LoadBalancerPreview = API.LoadBalancerPreview;
584 export import Member = API.Member;
585 export import PaginationInfo = API.PaginationInfo;
586 export import Permission = API.Permission;
587 export import PermissionGrant = API.PermissionGrant;
588 export import ResponseInfo = API.ResponseInfo;
589 export import Result = API.Result;
590 export import Role = API.Role;
591 export import SortDirection = API.SortDirection;
592}
593
594export default Cloudflare;
595