UNPKG

12.8 kBTypeScriptView Raw
1/// <reference types="node" />
2import { AuthClient, GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
3import { CredentialBody } from 'google-auth-library';
4import * as r from 'teeny-request';
5import { Duplex, DuplexOptions, Readable, Writable } from 'stream';
6import { Interceptor } from './service-object';
7export declare type ResponseBody = any;
8export interface DuplexifyOptions extends DuplexOptions {
9 autoDestroy?: boolean;
10 end?: boolean;
11}
12export interface Duplexify extends Duplex {
13 readonly destroyed: boolean;
14 setWritable(writable: Writable | false | null): void;
15 setReadable(readable: Readable | false | null): void;
16}
17export interface DuplexifyConstructor {
18 obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
19 new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
20 (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
21}
22export interface ParsedHttpRespMessage {
23 resp: r.Response;
24 err?: ApiError;
25}
26export interface MakeAuthenticatedRequest {
27 (reqOpts: DecorateRequestOptions): Duplexify;
28 (reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable;
29 (reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable;
30 (reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify;
31 getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void;
32 authClient: GoogleAuth<AuthClient>;
33}
34export interface Abortable {
35 abort(): void;
36}
37export declare type AbortableDuplex = Duplexify & Abortable;
38export interface PackageJson {
39 name: string;
40 version: string;
41}
42export interface MakeAuthenticatedRequestFactoryConfig extends Omit<GoogleAuthOptions, 'authClient'> {
43 /**
44 * Automatically retry requests if the response is related to rate limits or
45 * certain intermittent server errors. We will exponentially backoff
46 * subsequent requests by default. (default: true)
47 */
48 autoRetry?: boolean;
49 /**
50 * If true, just return the provided request options. Default: false.
51 */
52 customEndpoint?: boolean;
53 /**
54 * If true, will authenticate when using a custom endpoint. Default: false.
55 */
56 useAuthWithCustomEndpoint?: boolean;
57 /**
58 * Account email address, required for PEM/P12 usage.
59 */
60 email?: string;
61 /**
62 * Maximum number of automatic retries attempted before returning the error.
63 * (default: 3)
64 */
65 maxRetries?: number;
66 stream?: Duplexify;
67 /**
68 * A pre-instantiated `AuthClient` or `GoogleAuth` client that should be used.
69 * A new will be created if this is not set.
70 */
71 authClient?: AuthClient | GoogleAuth;
72 /**
73 * Determines if a projectId is required for authenticated requests. Defaults to `true`.
74 */
75 projectIdRequired?: boolean;
76}
77export interface MakeAuthenticatedRequestOptions {
78 onAuthenticated: OnAuthenticatedCallback;
79}
80export interface OnAuthenticatedCallback {
81 (err: Error | null, reqOpts?: DecorateRequestOptions): void;
82}
83export interface GoogleErrorBody {
84 code: number;
85 errors?: GoogleInnerError[];
86 response: r.Response;
87 message?: string;
88}
89export interface GoogleInnerError {
90 reason?: string;
91 message?: string;
92}
93export interface MakeWritableStreamOptions {
94 /**
95 * A connection instance used to get a token with and send the request
96 * through.
97 */
98 connection?: {};
99 /**
100 * Metadata to send at the head of the request.
101 */
102 metadata?: {
103 contentType?: string;
104 };
105 /**
106 * Request object, in the format of a standard Node.js http.request() object.
107 */
108 request?: r.Options;
109 makeAuthenticatedRequest(reqOpts: r.OptionsWithUri, fnobj: {
110 onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void;
111 }): void;
112}
113export interface DecorateRequestOptions extends r.CoreOptions {
114 autoPaginate?: boolean;
115 autoPaginateVal?: boolean;
116 objectMode?: boolean;
117 maxRetries?: number;
118 uri: string;
119 interceptors_?: Interceptor[];
120 shouldReturnStream?: boolean;
121 projectId?: string;
122}
123export interface ParsedHttpResponseBody {
124 body: ResponseBody;
125 err?: Error;
126}
127/**
128 * Custom error type for API errors.
129 *
130 * @param {object} errorBody - Error object.
131 */
132export declare class ApiError extends Error {
133 code?: number;
134 errors?: GoogleInnerError[];
135 response?: r.Response;
136 constructor(errorMessage: string);
137 constructor(errorBody: GoogleErrorBody);
138 /**
139 * Pieces together an error message by combining all unique error messages
140 * returned from a single GoogleError
141 *
142 * @private
143 *
144 * @param {GoogleErrorBody} err The original error.
145 * @param {GoogleInnerError[]} [errors] Inner errors, if any.
146 * @returns {string}
147 */
148 static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string;
149}
150/**
151 * Custom error type for partial errors returned from the API.
152 *
153 * @param {object} b - Error object.
154 */
155export declare class PartialFailureError extends Error {
156 errors?: GoogleInnerError[];
157 response?: r.Response;
158 constructor(b: GoogleErrorBody);
159}
160export interface BodyResponseCallback {
161 (err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void;
162}
163export interface RetryOptions {
164 retryDelayMultiplier?: number;
165 totalTimeout?: number;
166 maxRetryDelay?: number;
167 autoRetry?: boolean;
168 maxRetries?: number;
169 retryableErrorFn?: (err: ApiError) => boolean;
170}
171export interface MakeRequestConfig {
172 /**
173 * Automatically retry requests if the response is related to rate limits or
174 * certain intermittent server errors. We will exponentially backoff
175 * subsequent requests by default. (default: true)
176 */
177 autoRetry?: boolean;
178 /**
179 * Maximum number of automatic retries attempted before returning the error.
180 * (default: 3)
181 */
182 maxRetries?: number;
183 retries?: number;
184 retryOptions?: RetryOptions;
185 stream?: Duplexify;
186 shouldRetryFn?: (response?: r.Response) => boolean;
187}
188export declare class Util {
189 ApiError: typeof ApiError;
190 PartialFailureError: typeof PartialFailureError;
191 /**
192 * No op.
193 *
194 * @example
195 * function doSomething(callback) {
196 * callback = callback || noop;
197 * }
198 */
199 noop(): void;
200 /**
201 * Uniformly process an API response.
202 *
203 * @param {*} err - Error value.
204 * @param {*} resp - Response value.
205 * @param {*} body - Body value.
206 * @param {function} callback - The callback function.
207 */
208 handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void;
209 /**
210 * Sniff an incoming HTTP response message for errors.
211 *
212 * @param {object} httpRespMessage - An incoming HTTP response message from `request`.
213 * @return {object} parsedHttpRespMessage - The parsed response.
214 * @param {?error} parsedHttpRespMessage.err - An error detected.
215 * @param {object} parsedHttpRespMessage.resp - The original response object.
216 */
217 parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage;
218 /**
219 * Parse the response body from an HTTP request.
220 *
221 * @param {object} body - The response body.
222 * @return {object} parsedHttpRespMessage - The parsed response.
223 * @param {?error} parsedHttpRespMessage.err - An error detected.
224 * @param {object} parsedHttpRespMessage.body - The original body value provided
225 * will try to be JSON.parse'd. If it's successful, the parsed value will
226 * be returned here, otherwise the original value and an error will be returned.
227 */
228 parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody;
229 /**
230 * Take a Duplexify stream, fetch an authenticated connection header, and
231 * create an outgoing writable stream.
232 *
233 * @param {Duplexify} dup - Duplexify stream.
234 * @param {object} options - Configuration object.
235 * @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through.
236 * @param {object} options.metadata - Metadata to send at the head of the request.
237 * @param {object} options.request - Request object, in the format of a standard Node.js http.request() object.
238 * @param {string=} options.request.method - Default: "POST".
239 * @param {string=} options.request.qs.uploadType - Default: "multipart".
240 * @param {string=} options.streamContentType - Default: "application/octet-stream".
241 * @param {function} onComplete - Callback, executed after the writable Request stream has completed.
242 */
243 makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void;
244 /**
245 * Returns true if the API request should be retried, given the error that was
246 * given the first time the request was attempted. This is used for rate limit
247 * related errors as well as intermittent server errors.
248 *
249 * @param {error} err - The API error to check if it is appropriate to retry.
250 * @return {boolean} True if the API request should be retried, false otherwise.
251 */
252 shouldRetryRequest(err?: ApiError): boolean;
253 /**
254 * Get a function for making authenticated requests.
255 *
256 * @param {object} config - Configuration object.
257 * @param {boolean=} config.autoRetry - Automatically retry requests if the
258 * response is related to rate limits or certain intermittent server
259 * errors. We will exponentially backoff subsequent requests by default.
260 * (default: true)
261 * @param {object=} config.credentials - Credentials object.
262 * @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false.
263 * @param {boolean=} config.useAuthWithCustomEndpoint - If true, will authenticate when using a custom endpoint. Default: false.
264 * @param {string=} config.email - Account email address, required for PEM/P12 usage.
265 * @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3)
266 * @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile.
267 * @param {array} config.scopes - Array of scopes required for the API.
268 */
269 makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest;
270 /**
271 * Make a request through the `retryRequest` module with built-in error
272 * handling and exponential back off.
273 *
274 * @param {object} reqOpts - Request options in the format `request` expects.
275 * @param {object=} config - Configuration object.
276 * @param {boolean=} config.autoRetry - Automatically retry requests if the
277 * response is related to rate limits or certain intermittent server
278 * errors. We will exponentially backoff subsequent requests by default.
279 * (default: true)
280 * @param {number=} config.maxRetries - Maximum number of automatic retries
281 * attempted before returning the error. (default: 3)
282 * @param {object=} config.request - HTTP module for request calls.
283 * @param {function} callback - The callback function.
284 */
285 makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable;
286 /**
287 * Decorate the options about to be made in a request.
288 *
289 * @param {object} reqOpts - The options to be passed to `request`.
290 * @param {string} projectId - The project ID.
291 * @return {object} reqOpts - The decorated reqOpts.
292 */
293 decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions;
294 isCustomType(unknown: any, module: string): boolean;
295 /**
296 * Create a properly-formatted User-Agent string from a package.json file.
297 *
298 * @param {object} packageJson - A module's package.json file.
299 * @return {string} userAgent - The formatted User-Agent string.
300 */
301 getUserAgentFromPackageJson(packageJson: PackageJson): string;
302 /**
303 * Given two parameters, figure out if this is either:
304 * - Just a callback function
305 * - An options object, and then a callback function
306 * @param optionsOrCallback An options object or callback.
307 * @param cb A potentially undefined callback.
308 */
309 maybeOptionsOrCallback<T = {}, C = (err?: Error) => void>(optionsOrCallback?: T | C, cb?: C): [T, C];
310}
311declare const util: Util;
312export { util };