cloudflare/cloudflare-typescript

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
e9c649d2b4a4bce5bb01d8495e072f078128bc95

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/index.ts

569lines · modecode

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