UNPKG

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