1
0
mirror of https://github.com/musix-org/musix-oss synced 2025-06-17 17:06:00 +00:00
This commit is contained in:
MatteZ02
2020-03-03 22:30:50 +02:00
parent edfcc6f474
commit 30022c7634
11800 changed files with 1984416 additions and 1 deletions

36
node_modules/@google-cloud/common/build/src/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,36 @@
/*!
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { GoogleAuthOptions } from 'google-auth-library';
/**
* @type {module:common/operation}
* @private
*/
export { Operation } from './operation';
/**
* @type {module:common/service}
* @private
*/
export { Service, ServiceConfig, ServiceOptions, StreamRequestOptions, } from './service';
/**
* @type {module:common/serviceObject}
* @private
*/
export { DeleteCallback, ExistsCallback, GetConfig, InstanceResponseCallback, Interceptor, Metadata, MetadataCallback, MetadataResponse, Methods, ResponseCallback, ServiceObject, ServiceObjectConfig, ServiceObjectParent, SetMetadataResponse, } from './service-object';
/**
* @type {module:common/util}
* @private
*/
export { Abortable, AbortableDuplex, ApiError, BodyResponseCallback, DecorateRequestOptions, ResponseBody, util, } from './util';

43
node_modules/@google-cloud/common/build/src/index.js generated vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
/*!
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @type {module:common/operation}
* @private
*/
var operation_1 = require("./operation");
exports.Operation = operation_1.Operation;
/**
* @type {module:common/service}
* @private
*/
var service_1 = require("./service");
exports.Service = service_1.Service;
/**
* @type {module:common/serviceObject}
* @private
*/
var service_object_1 = require("./service-object");
exports.ServiceObject = service_object_1.ServiceObject;
/**
* @type {module:common/util}
* @private
*/
var util_1 = require("./util");
exports.ApiError = util_1.ApiError;
exports.util = util_1.util;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,68 @@
/*!
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!
* @module common/operation
*/
import { MetadataCallback, ServiceObject, ServiceObjectConfig } from './service-object';
export declare class Operation<T = any> extends ServiceObject<T> {
completeListeners: number;
hasActiveListeners: boolean;
/**
* An Operation object allows you to interact with APIs that take longer to
* process things.
*
* @constructor
* @alias module:common/operation
*
* @param {object} config - Configuration object.
* @param {module:common/service|module:common/serviceObject|module:common/grpcService|module:common/grpcServiceObject} config.parent - The parent object.
*/
constructor(config: ServiceObjectConfig);
/**
* Wraps the `complete` and `error` events in a Promise.
*
* @return {promise}
*/
promise(): Promise<unknown>;
/**
* Begin listening for events on the operation. This method keeps track of how
* many "complete" listeners are registered and removed, making sure polling
* is handled automatically.
*
* As long as there is one active "complete" listener, the connection is open.
* When there are no more listeners, the polling stops.
*
* @private
*/
protected listenForEvents_(): void;
/**
* Poll for a status update. Returns null for an incomplete
* status, and metadata for a complete status.
*
* @private
*/
protected poll_(callback: MetadataCallback): void;
/**
* Poll `getMetadata` to check the operation's status. This runs a loop to
* ping the API on an interval.
*
* Note: This method is automatically called once a "complete" event handler
* is registered on the operation.
*
* @private
*/
protected startPolling_(): Promise<void>;
}

View File

@ -0,0 +1,148 @@
"use strict";
/*!
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/*!
* @module common/operation
*/
const service_object_1 = require("./service-object");
const util_1 = require("util");
// tslint:disable-next-line no-any
class Operation extends service_object_1.ServiceObject {
/**
* An Operation object allows you to interact with APIs that take longer to
* process things.
*
* @constructor
* @alias module:common/operation
*
* @param {object} config - Configuration object.
* @param {module:common/service|module:common/serviceObject|module:common/grpcService|module:common/grpcServiceObject} config.parent - The parent object.
*/
constructor(config) {
const methods = {
/**
* Checks to see if an operation exists.
*/
exists: true,
/**
* Retrieves the operation.
*/
get: true,
/**
* Retrieves metadata for the operation.
*/
getMetadata: {
reqOpts: {
name: config.id,
},
},
};
config = Object.assign({
baseUrl: '',
}, config);
// tslint:disable-next-line:no-any
config.methods = (config.methods || methods);
super(config);
this.completeListeners = 0;
this.hasActiveListeners = false;
this.listenForEvents_();
}
/**
* Wraps the `complete` and `error` events in a Promise.
*
* @return {promise}
*/
promise() {
return new this.Promise((resolve, reject) => {
this.on('error', reject).on('complete', (metadata) => {
resolve([metadata]);
});
});
}
/**
* Begin listening for events on the operation. This method keeps track of how
* many "complete" listeners are registered and removed, making sure polling
* is handled automatically.
*
* As long as there is one active "complete" listener, the connection is open.
* When there are no more listeners, the polling stops.
*
* @private
*/
listenForEvents_() {
this.on('newListener', (event) => {
if (event === 'complete') {
this.completeListeners++;
if (!this.hasActiveListeners) {
this.hasActiveListeners = true;
this.startPolling_();
}
}
});
this.on('removeListener', (event) => {
if (event === 'complete' && --this.completeListeners === 0) {
this.hasActiveListeners = false;
}
});
}
/**
* Poll for a status update. Returns null for an incomplete
* status, and metadata for a complete status.
*
* @private
*/
poll_(callback) {
this.getMetadata((err, body) => {
if (err || body.error) {
callback(err || body.error);
return;
}
if (!body.done) {
callback(null);
return;
}
callback(null, body);
});
}
/**
* Poll `getMetadata` to check the operation's status. This runs a loop to
* ping the API on an interval.
*
* Note: This method is automatically called once a "complete" event handler
* is registered on the operation.
*
* @private
*/
async startPolling_() {
if (!this.hasActiveListeners) {
return;
}
try {
const metadata = await util_1.promisify(this.poll_.bind(this))();
if (!metadata) {
setTimeout(this.startPolling_.bind(this), this.pollIntervalMs || 500);
return;
}
this.emit('complete', metadata);
}
catch (err) {
this.emit('error', err);
}
}
}
exports.Operation = Operation;
//# sourceMappingURL=operation.js.map

View File

@ -0,0 +1,216 @@
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types="node" />
import { EventEmitter } from 'events';
import * as r from 'teeny-request';
import { ApiError, BodyResponseCallback, DecorateRequestOptions } from './util';
export declare type RequestResponse = [Metadata, r.Response];
export interface ServiceObjectParent {
Promise?: PromiseConstructor;
requestStream(reqOpts: DecorateRequestOptions): r.Request;
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
}
export interface Interceptor {
request(opts: r.Options): DecorateRequestOptions;
}
export declare type GetMetadataOptions = object;
export declare type Metadata = any;
export declare type MetadataResponse = [Metadata, r.Response];
export declare type MetadataCallback = (err: Error | null, metadata?: Metadata, apiResponse?: r.Response) => void;
export declare type ExistsOptions = object;
export interface ExistsCallback {
(err: Error | null, exists?: boolean): void;
}
export interface ServiceObjectConfig {
/**
* The base URL to make API requests to.
*/
baseUrl?: string;
/**
* The method which creates this object.
*/
createMethod?: Function;
/**
* The identifier of the object. For example, the name of a Storage bucket or
* Pub/Sub topic.
*/
id?: string;
/**
* A map of each method name that should be inherited.
*/
methods?: Methods;
/**
* The parent service instance. For example, an instance of Storage if the
* object is Bucket.
*/
parent: ServiceObjectParent;
/**
* For long running operations, how often should the client poll
* for completion.
*/
pollIntervalMs?: number;
}
export interface Methods {
[methodName: string]: {
reqOpts?: r.CoreOptions;
} | boolean;
}
export interface InstanceResponseCallback<T> {
(err: ApiError | null, instance?: T | null, apiResponse?: r.Response): void;
}
export interface CreateOptions {
}
export declare type CreateResponse<T> = any[];
export interface CreateCallback<T> {
(err: ApiError | null, instance?: T | null, ...args: any[]): void;
}
export declare type DeleteOptions = object;
export interface DeleteCallback {
(err: Error | null, apiResponse?: r.Response): void;
}
export interface GetConfig {
/**
* Create the object if it doesn't already exist.
*/
autoCreate?: boolean;
}
declare type GetOrCreateOptions = GetConfig & CreateOptions;
export declare type GetResponse<T> = [T, r.Response];
export interface ResponseCallback {
(err?: Error | null, apiResponse?: r.Response): void;
}
export declare type SetMetadataResponse = [Metadata];
export declare type SetMetadataOptions = object;
/**
* ServiceObject is a base class, meant to be inherited from by a "service
* object," like a BigQuery dataset or Storage bucket.
*
* Most of the time, these objects share common functionality; they can be
* created or deleted, and you can get or set their metadata.
*
* By inheriting from this class, a service object will be extended with these
* shared behaviors. Note that any method can be overridden when the service
* object requires specific behavior.
*/
declare class ServiceObject<T = any> extends EventEmitter {
metadata: Metadata;
baseUrl?: string;
parent: ServiceObjectParent;
id?: string;
pollIntervalMs?: number;
private createMethod?;
protected methods: Methods;
protected interceptors: Interceptor[];
Promise?: PromiseConstructor;
constructor(config: ServiceObjectConfig);
/**
* Create the object.
*
* @param {object=} options - Configuration object.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.instance - The instance.
* @param {object} callback.apiResponse - The full API response.
*/
create(options?: CreateOptions): Promise<CreateResponse<T>>;
create(options: CreateOptions, callback: CreateCallback<T>): void;
create(callback: CreateCallback<T>): void;
/**
* Delete the object.
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.apiResponse - The full API response.
*/
delete(options?: DeleteOptions): Promise<[r.Response]>;
delete(options: DeleteOptions, callback: DeleteCallback): void;
delete(callback: DeleteCallback): void;
/**
* Check if the object exists.
*
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {boolean} callback.exists - Whether the object exists or not.
*/
exists(options?: ExistsOptions): Promise<[boolean]>;
exists(options: ExistsOptions, callback: ExistsCallback): void;
exists(callback: ExistsCallback): void;
/**
* Get the object if it exists. Optionally have the object created if an
* options object is provided with `autoCreate: true`.
*
* @param {object=} options - The configuration object that will be used to
* create the object if necessary.
* @param {boolean} options.autoCreate - Create the object if it doesn't already exist.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.instance - The instance.
* @param {object} callback.apiResponse - The full API response.
*/
get(options?: GetOrCreateOptions): Promise<GetResponse<T>>;
get(callback: InstanceResponseCallback<T>): void;
get(options: GetOrCreateOptions, callback: InstanceResponseCallback<T>): void;
/**
* Get the metadata of this object.
*
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.metadata - The metadata for this object.
* @param {object} callback.apiResponse - The full API response.
*/
getMetadata(options?: GetMetadataOptions): Promise<MetadataResponse>;
getMetadata(options: GetMetadataOptions, callback: MetadataCallback): void;
getMetadata(callback: MetadataCallback): void;
/**
* Set the metadata for this object.
*
* @param {object} metadata - The metadata to set on this object.
* @param {object=} options - Configuration options.
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.apiResponse - The full API response.
*/
setMetadata(metadata: Metadata, options?: SetMetadataOptions): Promise<SetMetadataResponse>;
setMetadata(metadata: Metadata, callback: MetadataCallback): void;
setMetadata(metadata: Metadata, options: SetMetadataOptions, callback: MetadataCallback): void;
/**
* Make an authenticated API request.
*
* @private
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
* @param {function} callback - The callback function passed to `request`.
*/
private request_;
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
* @param {function} callback - The callback function passed to `request`.
*/
request(reqOpts: DecorateRequestOptions): Promise<RequestResponse>;
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
*/
requestStream(reqOpts: DecorateRequestOptions): r.Request;
}
export { ServiceObject };

View File

@ -0,0 +1,249 @@
"use strict";
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/*!
* @module common/service-object
*/
const promisify_1 = require("@google-cloud/promisify");
const arrify = require("arrify");
const events_1 = require("events");
const extend = require("extend");
const util_1 = require("./util");
/**
* ServiceObject is a base class, meant to be inherited from by a "service
* object," like a BigQuery dataset or Storage bucket.
*
* Most of the time, these objects share common functionality; they can be
* created or deleted, and you can get or set their metadata.
*
* By inheriting from this class, a service object will be extended with these
* shared behaviors. Note that any method can be overridden when the service
* object requires specific behavior.
*/
// tslint:disable-next-line no-any
class ServiceObject extends events_1.EventEmitter {
/*
* @constructor
* @alias module:common/service-object
*
* @private
*
* @param {object} config - Configuration object.
* @param {string} config.baseUrl - The base URL to make API requests to.
* @param {string} config.createMethod - The method which creates this object.
* @param {string=} config.id - The identifier of the object. For example, the
* name of a Storage bucket or Pub/Sub topic.
* @param {object=} config.methods - A map of each method name that should be inherited.
* @param {object} config.methods[].reqOpts - Default request options for this
* particular method. A common use case is when `setMetadata` requires a
* `PUT` method to override the default `PATCH`.
* @param {object} config.parent - The parent service instance. For example, an
* instance of Storage if the object is Bucket.
*/
constructor(config) {
super();
this.metadata = {};
this.baseUrl = config.baseUrl;
this.parent = config.parent; // Parent class.
this.id = config.id; // Name or ID (e.g. dataset ID, bucket name, etc).
this.createMethod = config.createMethod;
this.methods = config.methods || {};
this.interceptors = [];
this.pollIntervalMs = config.pollIntervalMs;
this.Promise = this.parent ? this.parent.Promise : undefined;
if (config.methods) {
Object.getOwnPropertyNames(ServiceObject.prototype)
.filter(methodName => {
return (
// All ServiceObjects need `request`.
// clang-format off
!/^request/.test(methodName) &&
// clang-format on
// The ServiceObject didn't redefine the method.
// tslint:disable-next-line no-any
this[methodName] ===
// tslint:disable-next-line no-any
ServiceObject.prototype[methodName] &&
// This method isn't wanted.
!config.methods[methodName]);
})
.forEach(methodName => {
// tslint:disable-next-line no-any
this[methodName] = undefined;
});
}
}
create(optionsOrCallback, callback) {
const self = this;
const args = [this.id];
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
}
if (typeof optionsOrCallback === 'object') {
args.push(optionsOrCallback);
}
// Wrap the callback to return *this* instance of the object, not the
// newly-created one.
// tslint: disable-next-line no-any
function onCreate(...args) {
const [err, instance] = args;
if (!err) {
self.metadata = instance.metadata;
args[1] = self; // replace the created `instance` with this one.
}
callback(...args);
}
args.push(onCreate);
this.createMethod.apply(null, args);
}
delete(optionsOrCallback, cb) {
const [options, callback] = util_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const methodConfig = (typeof this.methods.delete === 'object' && this.methods.delete) || {};
const reqOpts = extend(true, {
method: 'DELETE',
uri: '',
}, methodConfig.reqOpts, {
qs: options,
});
// The `request` method may have been overridden to hold any special
// behavior. Ensure we call the original `request` method.
ServiceObject.prototype.request.call(this, reqOpts, callback);
}
exists(optionsOrCallback, cb) {
const [options, callback] = util_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
this.get(options, err => {
if (err) {
if (err.code === 404) {
callback(null, false);
}
else {
callback(err);
}
return;
}
callback(null, true);
});
}
get(optionsOrCallback, cb) {
const self = this;
const [opts, callback] = util_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const options = Object.assign({}, opts);
const autoCreate = options.autoCreate && typeof this.create === 'function';
delete options.autoCreate;
function onCreate(err, instance, apiResponse) {
if (err) {
if (err.code === 409) {
self.get(options, callback);
return;
}
callback(err, null, apiResponse);
return;
}
callback(null, instance, apiResponse);
}
this.getMetadata(options, (err, metadata) => {
if (err) {
if (err.code === 404 && autoCreate) {
const args = [];
if (Object.keys(options).length > 0) {
args.push(options);
}
args.push(onCreate);
self.create(...args);
return;
}
callback(err, null, metadata);
return;
}
callback(null, self, metadata);
});
}
getMetadata(optionsOrCallback, cb) {
const [options, callback] = util_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const methodConfig = (typeof this.methods.getMetadata === 'object' &&
this.methods.getMetadata) ||
{};
const reqOpts = extend(true, {
uri: '',
}, methodConfig.reqOpts, {
qs: options,
});
// The `request` method may have been overridden to hold any special
// behavior. Ensure we call the original `request` method.
ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => {
this.metadata = body;
callback(err, this.metadata, res);
});
}
setMetadata(metadata, optionsOrCallback, cb) {
const [options, callback] = util_1.util.maybeOptionsOrCallback(optionsOrCallback, cb);
const methodConfig = (typeof this.methods.setMetadata === 'object' &&
this.methods.setMetadata) ||
{};
const reqOpts = extend(true, {}, {
method: 'PATCH',
uri: '',
}, methodConfig.reqOpts, {
json: metadata,
qs: options,
});
// The `request` method may have been overridden to hold any special
// behavior. Ensure we call the original `request` method.
ServiceObject.prototype.request.call(this, reqOpts, (err, body, res) => {
this.metadata = body;
callback(err, this.metadata, res);
});
}
request_(reqOpts, callback) {
reqOpts = extend(true, {}, reqOpts);
const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0;
const uriComponents = [this.baseUrl, this.id || '', reqOpts.uri];
if (isAbsoluteUrl) {
uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri));
}
reqOpts.uri = uriComponents
.filter(x => x.trim()) // Limit to non-empty strings.
.map(uriComponent => {
const trimSlashesRegex = /^\/*|\/*$/g;
return uriComponent.replace(trimSlashesRegex, '');
})
.join('/');
const childInterceptors = arrify(reqOpts.interceptors_);
const localInterceptors = [].slice.call(this.interceptors);
reqOpts.interceptors_ = childInterceptors.concat(localInterceptors);
if (reqOpts.shouldReturnStream) {
return this.parent.requestStream(reqOpts);
}
this.parent.request(reqOpts, callback);
}
request(reqOpts, callback) {
this.request_(reqOpts, callback);
}
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
*/
requestStream(reqOpts) {
const opts = extend(true, reqOpts, { shouldReturnStream: true });
return this.request_(opts);
}
}
exports.ServiceObject = ServiceObject;
promisify_1.promisifyAll(ServiceObject);
//# sourceMappingURL=service-object.js.map

View File

@ -0,0 +1,113 @@
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
import * as r from 'teeny-request';
import { Interceptor } from './service-object';
import { BodyResponseCallback, DecorateRequestOptions, MakeAuthenticatedRequest, PackageJson } from './util';
export interface StreamRequestOptions extends DecorateRequestOptions {
shouldReturnStream: true;
}
export interface ServiceConfig {
/**
* The base URL to make API requests to.
*/
baseUrl: string;
/**
* The API Endpoint to use when connecting to the service.
* Example: storage.googleapis.com
*/
apiEndpoint: string;
/**
* The scopes required for the request.
*/
scopes: string[];
projectIdRequired?: boolean;
packageJson: PackageJson;
/**
* Reuse an existing GoogleAuth client instead of creating a new one.
*/
authClient?: GoogleAuth;
}
export interface ServiceOptions extends GoogleAuthOptions {
interceptors_?: Interceptor[];
promise?: PromiseConstructor;
email?: string;
token?: string;
timeout?: number;
}
export declare class Service {
baseUrl: string;
private globalInterceptors;
private interceptors;
private packageJson;
projectId: string;
private projectIdRequired;
Promise: PromiseConstructor;
makeAuthenticatedRequest: MakeAuthenticatedRequest;
authClient: GoogleAuth;
private getCredentials;
readonly apiEndpoint: string;
timeout?: number;
/**
* Service is a base class, meant to be inherited from by a "service," like
* BigQuery or Storage.
*
* This handles making authenticated requests by exposing a `makeReq_`
* function.
*
* @constructor
* @alias module:common/service
*
* @param {object} config - Configuration object.
* @param {string} config.baseUrl - The base URL to make API requests to.
* @param {string[]} config.scopes - The scopes required for the request.
* @param {object=} options - [Configuration object](#/docs).
*/
constructor(config: ServiceConfig, options?: ServiceOptions);
/**
* Get and update the Service's project ID.
*
* @param {function} callback - The callback function.
*/
getProjectId(): Promise<string>;
getProjectId(callback: (err: Error | null, projectId?: string) => void): void;
protected getProjectIdAsync(): Promise<string>;
/**
* Make an authenticated API request.
*
* @private
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
* @param {function} callback - The callback function passed to `request`.
*/
private request_;
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
* @param {function} callback - The callback function passed to `request`.
*/
request(reqOpts: DecorateRequestOptions, callback: BodyResponseCallback): void;
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
*/
requestStream(reqOpts: DecorateRequestOptions): r.Request;
}

154
node_modules/@google-cloud/common/build/src/service.js generated vendored Normal file
View File

@ -0,0 +1,154 @@
"use strict";
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/*!
* @module common/service
*/
const arrify = require("arrify");
const extend = require("extend");
const util_1 = require("./util");
const PROJECT_ID_TOKEN = '{{projectId}}';
class Service {
/**
* Service is a base class, meant to be inherited from by a "service," like
* BigQuery or Storage.
*
* This handles making authenticated requests by exposing a `makeReq_`
* function.
*
* @constructor
* @alias module:common/service
*
* @param {object} config - Configuration object.
* @param {string} config.baseUrl - The base URL to make API requests to.
* @param {string[]} config.scopes - The scopes required for the request.
* @param {object=} options - [Configuration object](#/docs).
*/
constructor(config, options = {}) {
this.baseUrl = config.baseUrl;
this.apiEndpoint = config.apiEndpoint;
this.timeout = options.timeout;
this.globalInterceptors = arrify(options.interceptors_);
this.interceptors = [];
this.packageJson = config.packageJson;
this.projectId = options.projectId || PROJECT_ID_TOKEN;
this.projectIdRequired = config.projectIdRequired !== false;
this.Promise = options.promise || Promise;
const reqCfg = extend({}, config, {
projectIdRequired: this.projectIdRequired,
projectId: this.projectId,
credentials: options.credentials,
keyFile: options.keyFilename,
email: options.email,
token: options.token,
});
this.makeAuthenticatedRequest = util_1.util.makeAuthenticatedRequestFactory(reqCfg);
this.authClient = this.makeAuthenticatedRequest.authClient;
this.getCredentials = this.makeAuthenticatedRequest.getCredentials;
const isCloudFunctionEnv = !!process.env.FUNCTION_NAME;
if (isCloudFunctionEnv) {
this.interceptors.push({
request(reqOpts) {
reqOpts.forever = false;
return reqOpts;
},
});
}
}
getProjectId(callback) {
if (!callback) {
return this.getProjectIdAsync();
}
this.getProjectIdAsync().then(p => callback(null, p), callback);
}
async getProjectIdAsync() {
const projectId = await this.authClient.getProjectId();
if (this.projectId === PROJECT_ID_TOKEN && projectId) {
this.projectId = projectId;
}
return this.projectId;
}
request_(reqOpts, callback) {
reqOpts = extend(true, {}, reqOpts, { timeout: this.timeout });
const isAbsoluteUrl = reqOpts.uri.indexOf('http') === 0;
const uriComponents = [this.baseUrl];
if (this.projectIdRequired) {
uriComponents.push('projects');
uriComponents.push(this.projectId);
}
uriComponents.push(reqOpts.uri);
if (isAbsoluteUrl) {
uriComponents.splice(0, uriComponents.indexOf(reqOpts.uri));
}
reqOpts.uri = uriComponents
.map(uriComponent => {
const trimSlashesRegex = /^\/*|\/*$/g;
return uriComponent.replace(trimSlashesRegex, '');
})
.join('/')
// Some URIs have colon separators.
// Bad: https://.../projects/:list
// Good: https://.../projects:list
.replace(/\/:/g, ':');
// Interceptors should be called in the order they were assigned.
const combinedInterceptors = [].slice
.call(this.globalInterceptors)
.concat(this.interceptors)
.concat(arrify(reqOpts.interceptors_));
let interceptor;
while (
// tslint:disable-next-line:no-conditional-assignment
(interceptor = combinedInterceptors.shift()) &&
interceptor.request) {
reqOpts = interceptor.request(reqOpts);
}
delete reqOpts.interceptors_;
const pkg = this.packageJson;
reqOpts.headers = extend({}, reqOpts.headers, {
'User-Agent': util_1.util.getUserAgentFromPackageJson(pkg),
'x-goog-api-client': `gl-node/${process.versions.node} gccl/${pkg.version}`,
});
if (reqOpts.shouldReturnStream) {
return this.makeAuthenticatedRequest(reqOpts);
}
else {
this.makeAuthenticatedRequest(reqOpts, callback);
}
}
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
* @param {function} callback - The callback function passed to `request`.
*/
request(reqOpts, callback) {
Service.prototype.request_.call(this, reqOpts, callback);
}
/**
* Make an authenticated API request.
*
* @param {object} reqOpts - Request options that are passed to `request`.
* @param {string} reqOpts.uri - A URI relative to the baseUrl.
*/
requestStream(reqOpts) {
const opts = extend(true, reqOpts, { shouldReturnStream: true });
return Service.prototype.request_.call(this, opts);
}
}
exports.Service = Service;
//# sourceMappingURL=service.js.map

293
node_modules/@google-cloud/common/build/src/util.d.ts generated vendored Normal file
View File

@ -0,0 +1,293 @@
/// <reference types="node" />
import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
import { CredentialBody } from 'google-auth-library';
import * as r from 'teeny-request';
import { Duplex, DuplexOptions, Readable, Writable } from 'stream';
import { Interceptor } from './service-object';
export declare type ResponseBody = any;
export interface DuplexifyOptions extends DuplexOptions {
autoDestroy?: boolean;
end?: boolean;
}
export interface Duplexify extends Duplex {
readonly destroyed: boolean;
setWritable(writable: Writable | false | null): void;
setReadable(readable: Readable | false | null): void;
}
export interface DuplexifyConstructor {
obj(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
new (writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
(writable?: Writable | false | null, readable?: Readable | false | null, options?: DuplexifyOptions): Duplexify;
}
export interface ParsedHttpRespMessage {
resp: r.Response;
err?: ApiError;
}
export interface MakeAuthenticatedRequest {
(reqOpts: DecorateRequestOptions): Duplexify;
(reqOpts: DecorateRequestOptions, options?: MakeAuthenticatedRequestOptions): void | Abortable;
(reqOpts: DecorateRequestOptions, callback?: BodyResponseCallback): void | Abortable;
(reqOpts: DecorateRequestOptions, optionsOrCallback?: MakeAuthenticatedRequestOptions | BodyResponseCallback): void | Abortable | Duplexify;
getCredentials: (callback: (err?: Error | null, credentials?: CredentialBody) => void) => void;
authClient: GoogleAuth;
}
export interface Abortable {
abort(): void;
}
export declare type AbortableDuplex = Duplexify & Abortable;
export interface PackageJson {
name: string;
version: string;
}
export interface MakeAuthenticatedRequestFactoryConfig extends GoogleAuthOptions {
/**
* Automatically retry requests if the response is related to rate limits or
* certain intermittent server errors. We will exponentially backoff
* subsequent requests by default. (default: true)
*/
autoRetry?: boolean;
/**
* If true, just return the provided request options. Default: false.
*/
customEndpoint?: boolean;
/**
* Account email address, required for PEM/P12 usage.
*/
email?: string;
/**
* Maximum number of automatic retries attempted before returning the error.
* (default: 3)
*/
maxRetries?: number;
stream?: Duplexify;
/**
* A pre-instantiated GoogleAuth client that should be used.
* A new will be created if this is not set.
*/
authClient?: GoogleAuth;
}
export interface MakeAuthenticatedRequestOptions {
onAuthenticated: OnAuthenticatedCallback;
}
export interface OnAuthenticatedCallback {
(err: Error | null, reqOpts?: DecorateRequestOptions): void;
}
export interface GoogleErrorBody {
code: number;
errors?: GoogleInnerError[];
response: r.Response;
message?: string;
}
export interface GoogleInnerError {
reason?: string;
message?: string;
}
export interface MakeWritableStreamOptions {
/**
* A connection instance used to get a token with and send the request
* through.
*/
connection?: {};
/**
* Metadata to send at the head of the request.
*/
metadata?: {
contentType?: string;
};
/**
* Request object, in the format of a standard Node.js http.request() object.
*/
request?: r.Options;
makeAuthenticatedRequest(reqOpts: r.OptionsWithUri, fnobj: {
onAuthenticated(err: Error | null, authenticatedReqOpts?: r.Options): void;
}): void;
}
export interface DecorateRequestOptions extends r.CoreOptions {
autoPaginate?: boolean;
autoPaginateVal?: boolean;
objectMode?: boolean;
maxRetries?: number;
uri: string;
interceptors_?: Interceptor[];
shouldReturnStream?: boolean;
}
export interface ParsedHttpResponseBody {
body: ResponseBody;
err?: Error;
}
/**
* Custom error type for API errors.
*
* @param {object} errorBody - Error object.
*/
export declare class ApiError extends Error {
code?: number;
errors?: GoogleInnerError[];
response?: r.Response;
constructor(errorMessage: string);
constructor(errorBody: GoogleErrorBody);
/**
* Pieces together an error message by combining all unique error messages
* returned from a single GoogleError
*
* @private
*
* @param {GoogleErrorBody} err The original error.
* @param {GoogleInnerError[]} [errors] Inner errors, if any.
* @returns {string}
*/
static createMultiErrorMessage(err: GoogleErrorBody, errors?: GoogleInnerError[]): string;
}
/**
* Custom error type for partial errors returned from the API.
*
* @param {object} b - Error object.
*/
export declare class PartialFailureError extends Error {
errors?: GoogleInnerError[];
response?: r.Response;
constructor(b: GoogleErrorBody);
}
export interface BodyResponseCallback {
(err: Error | ApiError | null, body?: ResponseBody, res?: r.Response): void;
}
export interface MakeRequestConfig {
/**
* Automatically retry requests if the response is related to rate limits or
* certain intermittent server errors. We will exponentially backoff
* subsequent requests by default. (default: true)
*/
autoRetry?: boolean;
/**
* Maximum number of automatic retries attempted before returning the error.
* (default: 3)
*/
maxRetries?: number;
retries?: number;
stream?: Duplexify;
shouldRetryFn?: (response?: r.Response) => boolean;
}
export declare class Util {
ApiError: typeof ApiError;
PartialFailureError: typeof PartialFailureError;
/**
* No op.
*
* @example
* function doSomething(callback) {
* callback = callback || noop;
* }
*/
noop(): void;
/**
* Uniformly process an API response.
*
* @param {*} err - Error value.
* @param {*} resp - Response value.
* @param {*} body - Body value.
* @param {function} callback - The callback function.
*/
handleResp(err: Error | null, resp?: r.Response | null, body?: ResponseBody, callback?: BodyResponseCallback): void;
/**
* Sniff an incoming HTTP response message for errors.
*
* @param {object} httpRespMessage - An incoming HTTP response message from `request`.
* @return {object} parsedHttpRespMessage - The parsed response.
* @param {?error} parsedHttpRespMessage.err - An error detected.
* @param {object} parsedHttpRespMessage.resp - The original response object.
*/
parseHttpRespMessage(httpRespMessage: r.Response): ParsedHttpRespMessage;
/**
* Parse the response body from an HTTP request.
*
* @param {object} body - The response body.
* @return {object} parsedHttpRespMessage - The parsed response.
* @param {?error} parsedHttpRespMessage.err - An error detected.
* @param {object} parsedHttpRespMessage.body - The original body value provided
* will try to be JSON.parse'd. If it's successful, the parsed value will
* be returned here, otherwise the original value and an error will be returned.
*/
parseHttpRespBody(body: ResponseBody): ParsedHttpResponseBody;
/**
* Take a Duplexify stream, fetch an authenticated connection header, and
* create an outgoing writable stream.
*
* @param {Duplexify} dup - Duplexify stream.
* @param {object} options - Configuration object.
* @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through.
* @param {object} options.metadata - Metadata to send at the head of the request.
* @param {object} options.request - Request object, in the format of a standard Node.js http.request() object.
* @param {string=} options.request.method - Default: "POST".
* @param {string=} options.request.qs.uploadType - Default: "multipart".
* @param {string=} options.streamContentType - Default: "application/octet-stream".
* @param {function} onComplete - Callback, executed after the writable Request stream has completed.
*/
makeWritableStream(dup: Duplexify, options: MakeWritableStreamOptions, onComplete?: Function): void;
/**
* Returns true if the API request should be retried, given the error that was
* given the first time the request was attempted. This is used for rate limit
* related errors as well as intermittent server errors.
*
* @param {error} err - The API error to check if it is appropriate to retry.
* @return {boolean} True if the API request should be retried, false otherwise.
*/
shouldRetryRequest(err?: ApiError): boolean;
/**
* Get a function for making authenticated requests.
*
* @param {object} config - Configuration object.
* @param {boolean=} config.autoRetry - Automatically retry requests if the
* response is related to rate limits or certain intermittent server
* errors. We will exponentially backoff subsequent requests by default.
* (default: true)
* @param {object=} config.credentials - Credentials object.
* @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false.
* @param {string=} config.email - Account email address, required for PEM/P12 usage.
* @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3)
* @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile.
* @param {array} config.scopes - Array of scopes required for the API.
*/
makeAuthenticatedRequestFactory(config: MakeAuthenticatedRequestFactoryConfig): MakeAuthenticatedRequest;
/**
* Make a request through the `retryRequest` module with built-in error
* handling and exponential back off.
*
* @param {object} reqOpts - Request options in the format `request` expects.
* @param {object=} config - Configuration object.
* @param {boolean=} config.autoRetry - Automatically retry requests if the
* response is related to rate limits or certain intermittent server
* errors. We will exponentially backoff subsequent requests by default.
* (default: true)
* @param {number=} config.maxRetries - Maximum number of automatic retries
* attempted before returning the error. (default: 3)
* @param {object=} config.request - HTTP module for request calls.
* @param {function} callback - The callback function.
*/
makeRequest(reqOpts: DecorateRequestOptions, config: MakeRequestConfig, callback: BodyResponseCallback): void | Abortable;
/**
* Decorate the options about to be made in a request.
*
* @param {object} reqOpts - The options to be passed to `request`.
* @param {string} projectId - The project ID.
* @return {object} reqOpts - The decorated reqOpts.
*/
decorateRequest(reqOpts: DecorateRequestOptions, projectId: string): DecorateRequestOptions;
isCustomType(unknown: any, module: string): boolean;
/**
* Create a properly-formatted User-Agent string from a package.json file.
*
* @param {object} packageJson - A module's package.json file.
* @return {string} userAgent - The formatted User-Agent string.
*/
getUserAgentFromPackageJson(packageJson: PackageJson): string;
/**
* Given two parameters, figure out if this is either:
* - Just a callback function
* - An options object, and then a callback function
* @param optionsOrCallback An options object or callback.
* @param cb A potentially undefined callback.
*/
maybeOptionsOrCallback<T = {}, C = (err?: Error) => void>(optionsOrCallback?: T | C, cb?: C): [T, C];
}
declare const util: Util;
export { util };

532
node_modules/@google-cloud/common/build/src/util.js generated vendored Normal file
View File

@ -0,0 +1,532 @@
"use strict";
// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Object.defineProperty(exports, "__esModule", { value: true });
/*!
* @module common/util
*/
const projectify_1 = require("@google-cloud/projectify");
const ent = require("ent");
const extend = require("extend");
const google_auth_library_1 = require("google-auth-library");
const retryRequest = require("retry-request");
const stream_1 = require("stream");
const teeny_request_1 = require("teeny-request");
const duplexify = require('duplexify');
const requestDefaults = {
timeout: 60000,
gzip: true,
forever: true,
pool: {
maxSockets: Infinity,
},
};
/**
* Custom error type for API errors.
*
* @param {object} errorBody - Error object.
*/
class ApiError extends Error {
constructor(errorBodyOrMessage) {
super();
if (typeof errorBodyOrMessage !== 'object') {
this.message = errorBodyOrMessage || '';
return;
}
const errorBody = errorBodyOrMessage;
this.code = errorBody.code;
this.errors = errorBody.errors;
this.response = errorBody.response;
try {
this.errors = JSON.parse(this.response.body).error.errors;
}
catch (e) {
this.errors = errorBody.errors;
}
this.message = ApiError.createMultiErrorMessage(errorBody, this.errors);
Error.captureStackTrace(this);
}
/**
* Pieces together an error message by combining all unique error messages
* returned from a single GoogleError
*
* @private
*
* @param {GoogleErrorBody} err The original error.
* @param {GoogleInnerError[]} [errors] Inner errors, if any.
* @returns {string}
*/
static createMultiErrorMessage(err, errors) {
const messages = new Set();
if (err.message) {
messages.add(err.message);
}
if (errors && errors.length) {
errors.forEach(({ message }) => messages.add(message));
}
else if (err.response && err.response.body) {
messages.add(ent.decode(err.response.body.toString()));
}
else if (!err.message) {
messages.add('A failure occurred during this request.');
}
let messageArr = Array.from(messages);
if (messageArr.length > 1) {
messageArr = messageArr.map((message, i) => ` ${i + 1}. ${message}`);
messageArr.unshift('Multiple errors occurred during the request. Please see the `errors` array for complete details.\n');
messageArr.push('\n');
}
return messageArr.join('\n');
}
}
exports.ApiError = ApiError;
/**
* Custom error type for partial errors returned from the API.
*
* @param {object} b - Error object.
*/
class PartialFailureError extends Error {
constructor(b) {
super();
const errorObject = b;
this.errors = errorObject.errors;
this.name = 'PartialFailureError';
this.response = errorObject.response;
this.message = ApiError.createMultiErrorMessage(errorObject, this.errors);
}
}
exports.PartialFailureError = PartialFailureError;
class Util {
constructor() {
this.ApiError = ApiError;
this.PartialFailureError = PartialFailureError;
}
/**
* No op.
*
* @example
* function doSomething(callback) {
* callback = callback || noop;
* }
*/
noop() { }
/**
* Uniformly process an API response.
*
* @param {*} err - Error value.
* @param {*} resp - Response value.
* @param {*} body - Body value.
* @param {function} callback - The callback function.
*/
handleResp(err, resp, body, callback) {
callback = callback || util.noop;
const parsedResp = extend(true, { err: err || null }, resp && util.parseHttpRespMessage(resp), body && util.parseHttpRespBody(body));
// Assign the parsed body to resp.body, even if { json: false } was passed
// as a request option.
// We assume that nobody uses the previously unparsed value of resp.body.
if (!parsedResp.err && resp && typeof parsedResp.body === 'object') {
parsedResp.resp.body = parsedResp.body;
}
if (parsedResp.err && resp) {
parsedResp.err.response = resp;
}
callback(parsedResp.err, parsedResp.body, parsedResp.resp);
}
/**
* Sniff an incoming HTTP response message for errors.
*
* @param {object} httpRespMessage - An incoming HTTP response message from `request`.
* @return {object} parsedHttpRespMessage - The parsed response.
* @param {?error} parsedHttpRespMessage.err - An error detected.
* @param {object} parsedHttpRespMessage.resp - The original response object.
*/
parseHttpRespMessage(httpRespMessage) {
const parsedHttpRespMessage = {
resp: httpRespMessage,
};
if (httpRespMessage.statusCode < 200 || httpRespMessage.statusCode > 299) {
// Unknown error. Format according to ApiError standard.
parsedHttpRespMessage.err = new ApiError({
errors: new Array(),
code: httpRespMessage.statusCode,
message: httpRespMessage.statusMessage,
response: httpRespMessage,
});
}
return parsedHttpRespMessage;
}
/**
* Parse the response body from an HTTP request.
*
* @param {object} body - The response body.
* @return {object} parsedHttpRespMessage - The parsed response.
* @param {?error} parsedHttpRespMessage.err - An error detected.
* @param {object} parsedHttpRespMessage.body - The original body value provided
* will try to be JSON.parse'd. If it's successful, the parsed value will
* be returned here, otherwise the original value and an error will be returned.
*/
parseHttpRespBody(body) {
const parsedHttpRespBody = {
body,
};
if (typeof body === 'string') {
try {
parsedHttpRespBody.body = JSON.parse(body);
}
catch (err) {
parsedHttpRespBody.err = new ApiError(`Cannot parse response as JSON: ${body}`);
}
}
if (parsedHttpRespBody.body && parsedHttpRespBody.body.error) {
// Error from JSON API.
parsedHttpRespBody.err = new ApiError(parsedHttpRespBody.body.error);
}
return parsedHttpRespBody;
}
/**
* Take a Duplexify stream, fetch an authenticated connection header, and
* create an outgoing writable stream.
*
* @param {Duplexify} dup - Duplexify stream.
* @param {object} options - Configuration object.
* @param {module:common/connection} options.connection - A connection instance used to get a token with and send the request through.
* @param {object} options.metadata - Metadata to send at the head of the request.
* @param {object} options.request - Request object, in the format of a standard Node.js http.request() object.
* @param {string=} options.request.method - Default: "POST".
* @param {string=} options.request.qs.uploadType - Default: "multipart".
* @param {string=} options.streamContentType - Default: "application/octet-stream".
* @param {function} onComplete - Callback, executed after the writable Request stream has completed.
*/
makeWritableStream(dup, options, onComplete) {
onComplete = onComplete || util.noop;
const writeStream = new stream_1.PassThrough();
dup.setWritable(writeStream);
const defaultReqOpts = {
method: 'POST',
qs: {
uploadType: 'multipart',
},
timeout: 0,
maxRetries: 0,
};
const metadata = options.metadata || {};
const reqOpts = extend(true, defaultReqOpts, options.request, {
multipart: [
{
'Content-Type': 'application/json',
body: JSON.stringify(metadata),
},
{
'Content-Type': metadata.contentType || 'application/octet-stream',
body: writeStream,
},
],
});
options.makeAuthenticatedRequest(reqOpts, {
onAuthenticated(err, authenticatedReqOpts) {
if (err) {
dup.destroy(err);
return;
}
const request = teeny_request_1.teenyRequest.defaults(requestDefaults);
request(authenticatedReqOpts, (err, resp, body) => {
util.handleResp(err, resp, body, (err, data) => {
if (err) {
dup.destroy(err);
return;
}
dup.emit('response', resp);
onComplete(data);
});
});
},
});
}
/**
* Returns true if the API request should be retried, given the error that was
* given the first time the request was attempted. This is used for rate limit
* related errors as well as intermittent server errors.
*
* @param {error} err - The API error to check if it is appropriate to retry.
* @return {boolean} True if the API request should be retried, false otherwise.
*/
shouldRetryRequest(err) {
if (err) {
if ([429, 500, 502, 503].indexOf(err.code) !== -1) {
return true;
}
if (err.errors) {
for (const e of err.errors) {
const reason = e.reason;
if (reason === 'rateLimitExceeded') {
return true;
}
if (reason === 'userRateLimitExceeded') {
return true;
}
}
}
}
return false;
}
/**
* Get a function for making authenticated requests.
*
* @param {object} config - Configuration object.
* @param {boolean=} config.autoRetry - Automatically retry requests if the
* response is related to rate limits or certain intermittent server
* errors. We will exponentially backoff subsequent requests by default.
* (default: true)
* @param {object=} config.credentials - Credentials object.
* @param {boolean=} config.customEndpoint - If true, just return the provided request options. Default: false.
* @param {string=} config.email - Account email address, required for PEM/P12 usage.
* @param {number=} config.maxRetries - Maximum number of automatic retries attempted before returning the error. (default: 3)
* @param {string=} config.keyFile - Path to a .json, .pem, or .p12 keyfile.
* @param {array} config.scopes - Array of scopes required for the API.
*/
makeAuthenticatedRequestFactory(config) {
const googleAutoAuthConfig = extend({}, config);
if (googleAutoAuthConfig.projectId === '{{projectId}}') {
delete googleAutoAuthConfig.projectId;
}
const authClient = googleAutoAuthConfig.authClient || new google_auth_library_1.GoogleAuth(googleAutoAuthConfig);
function makeAuthenticatedRequest(reqOpts, optionsOrCallback) {
let stream;
const reqConfig = extend({}, config);
let activeRequest_;
if (!optionsOrCallback) {
stream = duplexify();
reqConfig.stream = stream;
}
const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : undefined;
const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : undefined;
const onAuthenticated = (err, authenticatedReqOpts) => {
const authLibraryError = err;
const autoAuthFailed = err &&
err.message.indexOf('Could not load the default credentials') > -1;
if (autoAuthFailed) {
// Even though authentication failed, the API might not actually
// care.
authenticatedReqOpts = reqOpts;
}
if (!err || autoAuthFailed) {
// tslint:disable-next-line:no-any
let projectId = authClient._cachedProjectId;
if (config.projectId && config.projectId !== '{{projectId}}') {
projectId = config.projectId;
}
try {
authenticatedReqOpts = util.decorateRequest(authenticatedReqOpts, projectId);
err = null;
}
catch (e) {
// A projectId was required, but we don't have one.
// Re-use the "Could not load the default credentials error" if
// auto auth failed.
err = err || e;
}
}
if (err) {
if (stream) {
stream.destroy(err);
}
else {
const fn = options && options.onAuthenticated
? options.onAuthenticated
: callback;
fn(err);
}
return;
}
if (options && options.onAuthenticated) {
options.onAuthenticated(null, authenticatedReqOpts);
}
else {
activeRequest_ = util.makeRequest(authenticatedReqOpts, reqConfig, (apiResponseError, ...params) => {
if (apiResponseError &&
apiResponseError.code === 401 &&
authLibraryError) {
// Re-use the "Could not load the default credentials error" if
// the API request failed due to missing credentials.
apiResponseError = authLibraryError;
}
callback(apiResponseError, ...params);
});
}
};
if (reqConfig.customEndpoint) {
// Using a custom API override. Do not use `google-auth-library` for
// authentication. (ex: connecting to a local Datastore server)
onAuthenticated(null, reqOpts);
}
else {
authClient.authorizeRequest(reqOpts).then(res => {
const opts = extend(true, {}, reqOpts, res);
onAuthenticated(null, opts);
}, err => {
onAuthenticated(err);
});
}
if (stream) {
return stream;
}
return {
abort() {
setImmediate(() => {
if (activeRequest_) {
activeRequest_.abort();
activeRequest_ = null;
}
});
},
};
}
const mar = makeAuthenticatedRequest;
mar.getCredentials = authClient.getCredentials.bind(authClient);
mar.authClient = authClient;
return mar;
}
/**
* Make a request through the `retryRequest` module with built-in error
* handling and exponential back off.
*
* @param {object} reqOpts - Request options in the format `request` expects.
* @param {object=} config - Configuration object.
* @param {boolean=} config.autoRetry - Automatically retry requests if the
* response is related to rate limits or certain intermittent server
* errors. We will exponentially backoff subsequent requests by default.
* (default: true)
* @param {number=} config.maxRetries - Maximum number of automatic retries
* attempted before returning the error. (default: 3)
* @param {object=} config.request - HTTP module for request calls.
* @param {function} callback - The callback function.
*/
makeRequest(reqOpts, config, callback) {
const options = {
request: teeny_request_1.teenyRequest.defaults(requestDefaults),
retries: config.autoRetry !== false ? config.maxRetries || 3 : 0,
shouldRetryFn(httpRespMessage) {
const err = util.parseHttpRespMessage(httpRespMessage).err;
return err && util.shouldRetryRequest(err);
},
};
if (typeof reqOpts.maxRetries === 'number') {
options.retries = reqOpts.maxRetries;
}
if (!config.stream) {
return retryRequest(reqOpts, options, (err, response, body) => {
util.handleResp(err, response, body, callback);
});
}
const dup = config.stream;
// tslint:disable-next-line:no-any
let requestStream;
const isGetRequest = (reqOpts.method || 'GET').toUpperCase() === 'GET';
if (isGetRequest) {
requestStream = retryRequest(reqOpts, options);
dup.setReadable(requestStream);
}
else {
// Streaming writable HTTP requests cannot be retried.
requestStream = options.request(reqOpts);
dup.setWritable(requestStream);
}
// Replay the Request events back to the stream.
requestStream
.on('error', dup.destroy.bind(dup))
.on('response', dup.emit.bind(dup, 'response'))
.on('complete', dup.emit.bind(dup, 'complete'));
dup.abort = requestStream.abort;
return dup;
}
/**
* Decorate the options about to be made in a request.
*
* @param {object} reqOpts - The options to be passed to `request`.
* @param {string} projectId - The project ID.
* @return {object} reqOpts - The decorated reqOpts.
*/
decorateRequest(reqOpts, projectId) {
delete reqOpts.autoPaginate;
delete reqOpts.autoPaginateVal;
delete reqOpts.objectMode;
if (reqOpts.qs !== null && typeof reqOpts.qs === 'object') {
delete reqOpts.qs.autoPaginate;
delete reqOpts.qs.autoPaginateVal;
reqOpts.qs = projectify_1.replaceProjectIdToken(reqOpts.qs, projectId);
}
if (Array.isArray(reqOpts.multipart)) {
reqOpts.multipart = reqOpts.multipart.map(part => {
return projectify_1.replaceProjectIdToken(part, projectId);
});
}
if (reqOpts.json !== null && typeof reqOpts.json === 'object') {
delete reqOpts.json.autoPaginate;
delete reqOpts.json.autoPaginateVal;
reqOpts.json = projectify_1.replaceProjectIdToken(reqOpts.json, projectId);
}
reqOpts.uri = projectify_1.replaceProjectIdToken(reqOpts.uri, projectId);
return reqOpts;
}
// tslint:disable-next-line:no-any
isCustomType(unknown, module) {
function getConstructorName(obj) {
return obj.constructor && obj.constructor.name.toLowerCase();
}
const moduleNameParts = module.split('/');
const parentModuleName = moduleNameParts[0] && moduleNameParts[0].toLowerCase();
const subModuleName = moduleNameParts[1] && moduleNameParts[1].toLowerCase();
if (subModuleName && getConstructorName(unknown) !== subModuleName) {
return false;
}
let walkingModule = unknown;
while (true) {
if (getConstructorName(walkingModule) === parentModuleName) {
return true;
}
walkingModule = walkingModule.parent;
if (!walkingModule) {
return false;
}
}
}
/**
* Create a properly-formatted User-Agent string from a package.json file.
*
* @param {object} packageJson - A module's package.json file.
* @return {string} userAgent - The formatted User-Agent string.
*/
getUserAgentFromPackageJson(packageJson) {
const hyphenatedPackageName = packageJson.name
.replace('@google-cloud', 'gcloud-node') // For legacy purposes.
.replace('/', '-'); // For UA spec-compliance purposes.
return hyphenatedPackageName + '/' + packageJson.version;
}
/**
* Given two parameters, figure out if this is either:
* - Just a callback function
* - An options object, and then a callback function
* @param optionsOrCallback An options object or callback.
* @param cb A potentially undefined callback.
*/
maybeOptionsOrCallback(optionsOrCallback, cb) {
return typeof optionsOrCallback === 'function'
? [{}, optionsOrCallback]
: [optionsOrCallback, cb];
}
}
exports.Util = Util;
const util = new Util();
exports.util = util;
//# sourceMappingURL=util.js.map