Initial commit

This commit is contained in:
pasketti
2026-04-05 16:14:49 -04:00
commit ebee3a5534
14059 changed files with 2588797 additions and 0 deletions

25
node_modules/google-gax/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,25 @@
Copyright 2016, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

70
node_modules/google-gax/index.js generated vendored Normal file
View File

@@ -0,0 +1,70 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var bundling = require('./lib/bundling');
var gax = require('./lib/gax');
var grpc = require('./lib/grpc');
var extend = require('extend');
var streaming = require('./lib/streaming');
var operationsClient = require('./lib/operations_client');
var longrunning = require('./lib/longrunning');
var routingHeader = require('./lib/routing_header');
function lro(options) {
options = extend(
{
scopes: lro.ALL_SCOPES,
},
options
);
var gaxGrpc = grpc(options);
return operationsClient(gaxGrpc);
}
lro.SERVICE_ADDRESS = operationsClient.SERVICE_ADDRESS;
lro.ALL_SCOPES = operationsClient.ALL_SCOPES;
exports.lro = lro;
exports.createApiCall = require('./lib/api_callable').createApiCall;
exports.grpc = grpc;
exports.createByteLengthFunction = grpc.createByteLengthFunction;
exports.PathTemplate = require('./lib/path_template').PathTemplate;
exports.PageDescriptor = require('./lib/paged_iteration').PageDescriptor;
exports.BundleDescriptor = bundling.BundleDescriptor;
exports.StreamType = streaming.StreamType;
exports.StreamDescriptor = streaming.StreamDescriptor;
exports.constructSettings = gax.constructSettings;
exports.BundleExecutor = bundling.BundleExecutor;
exports.LongrunningDescriptor = longrunning.LongrunningDescriptor;
exports.operation = longrunning.operation;
exports.routingHeader = routingHeader;
exports.version = require('./package').version;

6
node_modules/google-gax/lib/.eslintrc.yml generated vendored Normal file
View File

@@ -0,0 +1,6 @@
---
env:
mocha: true
rules:
no-warning-comments: off
no-console: off

391
node_modules/google-gax/lib/api_callable.js generated vendored Normal file
View File

@@ -0,0 +1,391 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Provides function wrappers that implement page streaming and retrying.
*/
'use strict';
var setTimeout = require('timers').setTimeout;
var util = require('util');
/**
* @callback APICallback
* @param {?Error} error
* @param {?Object} response
*/
/**
* @callback APIFunc
* @param {Object} argument
* @param {grpc.Metadata} metadata
* @param {Object} options
* @param {APICallback} callback
*/
/**
* @callback APICall
* @param {Object} argument
* @param {CallOptions} callOptions
* @param {APICallback} callback
* @return {Promise|Stream|undefined}
*/
/**
* Canceller manages callback, API calls, and cancellation
* of the API calls.
* @param {APICallback=} callback
* The callback to be called asynchronously when the API call
* finishes.
* @constructor
* @property {APICallback} callback
* The callback function to be called.
* @private
*/
function Canceller(callback) {
this.callback = callback;
this.cancelFunc = null;
this.completed = false;
}
/**
* Cancels the ongoing promise.
*/
Canceller.prototype.cancel = function() {
if (this.completed) {
return;
}
this.completed = true;
if (this.cancelFunc) {
this.cancelFunc();
} else {
this.callback(new Error('cancelled'));
}
};
/**
* Call calls the specified function. Result will be used to fulfill
* the promise.
*
* @param {function(Object, APICallback=)} aFunc
* A function for an API call.
* @param {Object} argument
* A request object.
*/
Canceller.prototype.call = function(aFunc, argument) {
if (this.completed) {
return;
}
var self = this;
var canceller = aFunc(argument, function() {
self.completed = true;
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(self.callback);
setImmediate.apply(null, args);
});
this.cancelFunc = function() {
canceller.cancel();
};
};
/**
* PromiseCanceller is Canceller, but it holds a promise when
* the API call finishes.
* @param {Function} PromiseCtor - A constructor for a promise that implements
* the ES6 specification of promise.
* @constructor
* @private
*/
function PromiseCanceller(PromiseCtor) {
var self = this;
this.promise = new PromiseCtor(function(resolve, reject) {
Canceller.call(self, function(err) {
if (err) {
reject(err);
} else {
resolve(Array.prototype.slice.call(arguments, 1));
}
});
});
this.promise.cancel = function() {
self.cancel();
};
}
util.inherits(PromiseCanceller, Canceller);
/**
* Updates aFunc so that it gets called with the timeout as its final arg.
*
* This converts a function, aFunc, into another function with updated deadline.
*
* @private
*
* @param {APIFunc} aFunc - a function to be updated.
* @param {number} timeout - to be added to the original function as it final
* positional arg.
* @param {Object} otherArgs - the additional arguments to be passed to aFunc.
* @param {Object=} abTests - the A/B testing key/value pairs.
* @return {function(Object, APICallback)}
* the function with other arguments and the timeout.
*/
function addTimeoutArg(aFunc, timeout, otherArgs, abTests) {
// TODO: this assumes the other arguments consist of metadata and options,
// which is specific to gRPC calls. Remove the hidden dependency on gRPC.
return function timeoutFunc(argument, callback) {
var now = new Date();
var options = otherArgs.options || {};
options.deadline = new Date(now.getTime() + timeout);
var metadata = otherArgs.metadataBuilder
? otherArgs.metadataBuilder(abTests, otherArgs.headers || {})
: null;
return aFunc(argument, metadata, options, callback);
};
}
/**
* Creates a function equivalent to aFunc, but that retries on certain
* exceptions.
*
* @private
*
* @param {APIFunc} aFunc - A function.
* @param {RetryOptions} retry - Configures the exceptions upon which the
* function eshould retry, and the parameters to the exponential backoff retry
* algorithm.
* @param {Object} otherArgs - the additional arguments to be passed to aFunc.
* @return {function(Object, APICallback)} A function that will retry.
*/
function retryable(aFunc, retry, otherArgs) {
var delayMult = retry.backoffSettings.retryDelayMultiplier;
var maxDelay = retry.backoffSettings.maxRetryDelayMillis;
var timeoutMult = retry.backoffSettings.rpcTimeoutMultiplier;
var maxTimeout = retry.backoffSettings.maxRpcTimeoutMillis;
var delay = retry.backoffSettings.initialRetryDelayMillis;
var timeout = retry.backoffSettings.initialRpcTimeoutMillis;
/**
* Equivalent to ``aFunc``, but retries upon transient failure.
*
* Retrying is done through an exponential backoff algorithm configured
* by the options in ``retry``.
* @param {Object} argument The request object.
* @param {APICallback} callback The callback.
* @return {function()} cancel function.
*/
return function retryingFunc(argument, callback) {
var canceller;
var timeoutId;
var now = new Date();
var deadline;
if (retry.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + retry.backoffSettings.totalTimeoutMillis;
}
var retries = 0;
var maxRetries = retry.backoffSettings.maxRetries;
// TODO: define A/B testing values for retry behaviors.
/** Repeat the API call as long as necessary. */
function repeat() {
timeoutId = null;
if (deadline && now.getTime() >= deadline) {
callback(
new Error(
'Retry total timeout exceeded before any' + 'response was received'
)
);
return;
}
if (retries && retries >= maxRetries) {
callback(
new Error(
'Exceeded maximum number of retries before any ' +
'response was received'
)
);
return;
}
retries++;
var toCall = addTimeoutArg(aFunc, timeout, otherArgs);
canceller = toCall(argument, function(err) {
if (!err) {
var args = Array.prototype.slice.call(arguments, 1);
args.unshift(null);
callback.apply(null, args);
return;
}
canceller = null;
if (retry.retryCodes.indexOf(err.code) < 0) {
err.note =
'Exception occurred in retry method that was ' +
'not classified as transient';
callback(err);
} else {
var toSleep = Math.random() * delay;
timeoutId = setTimeout(function() {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
timeout = Math.min(
timeout * timeoutMult,
maxTimeout,
deadline - now.getTime()
);
repeat();
}, toSleep);
}
});
}
if (maxRetries && deadline) {
callback(
new Error(
'Cannot set both totalTimeoutMillis and maxRetries ' +
'in backoffSettings.'
)
);
} else {
repeat();
}
return {
cancel: function() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (canceller) {
canceller.cancel();
} else {
callback(new Error('cancelled'));
}
},
};
};
}
/**
* Creates an API caller for normal methods.
*
* @private
* @constructor
*/
function NormalApiCaller() {}
NormalApiCaller.prototype.init = function(settings, callback) {
if (callback) {
return new Canceller(callback);
}
return new PromiseCanceller(settings.promise);
};
NormalApiCaller.prototype.wrap = function(func) {
return func;
};
NormalApiCaller.prototype.call = function(
apiCall,
argument,
settings,
canceller
) {
canceller.call(apiCall, argument);
};
NormalApiCaller.prototype.fail = function(canceller, err) {
canceller.callback(err);
};
NormalApiCaller.prototype.result = function(canceller) {
if (canceller.promise) {
return canceller.promise;
}
};
exports.NormalApiCaller = NormalApiCaller;
/**
* Converts an rpc call into an API call governed by the settings.
*
* In typical usage, `func` will be a promsie to a callable used to make an rpc
* request. This will mostly likely be a bound method from a request stub used
* to make an rpc call. It is not a direct function but a Promise instance,
* because of its asynchronism (typically, obtaining the auth information).
*
* The result is a function which manages the API call with the given settings
* and the options on the invocation.
*
* @param {Promise.<APIFunc>} funcWithAuth - is a promise to be used to make
* a bare rpc call. This is a Promise instead of a bare function because
* the rpc call will be involeved with asynchronous authentications.
* @param {CallSettings} settings - provides the settings for this call
* @param {Object=} optDescriptor - optionally specify the descriptor for
* the method call.
* @return {APICall} func - a bound method on a request stub used
* to make an rpc call.
*/
exports.createApiCall = function createApiCall(
funcWithAuth,
settings,
optDescriptor
) {
var apiCaller = optDescriptor
? optDescriptor.apiCaller(settings)
: new NormalApiCaller();
return function apiCallInner(request, callOptions, callback) {
var thisSettings = settings.merge(callOptions);
var status = apiCaller.init(thisSettings, callback);
funcWithAuth
.then(function(func) {
func = apiCaller.wrap(func);
var retry = thisSettings.retry;
if (retry && retry.retryCodes && retry.retryCodes.length > 0) {
return retryable(func, thisSettings.retry, thisSettings.otherArgs);
}
return addTimeoutArg(
func,
thisSettings.timeout,
thisSettings.otherArgs
);
})
.then(function(apiCall) {
apiCaller.call(apiCall, request, thisSettings, status);
})
.catch(function(err) {
apiCaller.fail(status, err);
});
return apiCaller.result(status);
};
};

68
node_modules/google-gax/lib/auth.js generated vendored Normal file
View File

@@ -0,0 +1,68 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
/**
* @callback GetCredentialsFunc
*
* To authorize requests through gRPC, we must get the raw google-auth-library
* auth client object.
*
* @param {function()} callback - The callback function.
* @param {Object} opts - options values for configuring auth
* @param {(String|String[])} opts.scopes - the scope or scopes to use when
* obtaining the credentials.
* @param {Object} opts.sslCreds - when specified, this is used instead
* of default credentials.
*/
/**
* Creates a promise which resolves a auth credential.
*
* @param {GetCredentialsFunc} getCredentials - the callback used to
* obtain the credentials.
* @param {Object} opts - the optional arguments to be passed to
* getCredentials.
* @return {Promise} A promise which resolves to the credential.
*/
exports.createCredPromise = function createCredPromise(getCredentials, opts) {
return new Promise(function(resolve, reject) {
getCredentials(function(err, credentials) {
if (err) {
reject(err);
} else {
resolve(credentials);
}
}, opts);
});
};

565
node_modules/google-gax/lib/bundling.js generated vendored Normal file
View File

@@ -0,0 +1,565 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Provides behavior that supports request bundling.
*/
'use strict';
var _ = require('lodash');
var util = require('util');
var NormalApiCaller = require('./api_callable').NormalApiCaller;
/**
* A function which does nothing. Used for an empty cancellation funciton.
* @private
*/
function noop() {}
/**
* Compute the identifier of the `obj`. The objects of the same ID
* will be bundled together.
*
* @param {Object} obj - The request object.
* @param {String[]} discriminatorFields - The array of field names.
* A field name may include '.' as a separator, which is used to
* indicate object traversal.
* @return {String|undefined} - the identifier string, or undefined if any
* discriminator.
* fields do not exist.
*/
function computeBundleId(obj, discriminatorFields) {
var ids = [];
var hasIds = false;
for (var i = 0; i < discriminatorFields.length; ++i) {
var id = _.at(obj, discriminatorFields[i])[0];
if (id === undefined) {
ids.push(null);
} else {
hasIds = true;
ids.push(id);
}
}
if (!hasIds) {
return undefined;
}
return JSON.stringify(ids);
}
exports.computeBundleId = computeBundleId;
/**
* Creates a deep copy of the object with the consideration of subresponse
* fields for bundling.
*
* @param {Object} obj - The source object.
* @param {Object?} subresponseInfo - The information to copy the subset of
* the field for the response. Do nothing if it's null.
* @param {String} subresponseInfo.field - The field name.
* @param {number} subresponseInfo.start - The offset where the copying
* element should starts with.
* @param {number} subresponseInfo.end - The ending index where the copying
* region of the elements ends.
* @return {Object} The copied object.
* @private
*/
function deepCopyForResponse(obj, subresponseInfo) {
var result;
if (obj === null) {
return null;
}
if (obj === undefined) {
return undefined;
}
if (Array.isArray(obj)) {
result = [];
obj.forEach(function(element) {
result.push(deepCopyForResponse(element, null));
});
return result;
}
// Some objects (such as ByteBuffer) have copy method.
if (obj.copy !== undefined) {
return obj.copy();
}
// ArrayBuffer should be copied through slice().
if (obj instanceof ArrayBuffer) {
return obj.slice();
}
if (typeof obj === 'object') {
result = {};
Object.keys(obj).forEach(function(key) {
if (
subresponseInfo &&
key === subresponseInfo.field &&
Array.isArray(obj[key])
) {
// Note that subresponses are not deep-copied. This is safe because
// those subresponses are not shared among callbacks.
result[key] = obj[key].slice(
subresponseInfo.start,
subresponseInfo.end
);
} else {
result[key] = deepCopyForResponse(obj[key], null);
}
});
return result;
}
return obj;
}
exports.deepCopyForResponse = deepCopyForResponse;
/**
* A task coordinates the execution of a single bundle.
*
* @param {function} apiCall - The function to conduct calling API.
* @param {Object} bundlingRequest - The base request object to be used
* for the actual API call.
* @param {string} bundledField - The name of the field in bundlingRequest
* to be bundled.
* @param {string=} subresponseField - The name of the field in the response
* to be passed to the callback.
* @constructor
* @private
*/
function Task(apiCall, bundlingRequest, bundledField, subresponseField) {
this._apiCall = apiCall;
this._request = bundlingRequest;
this._bundledField = bundledField;
this._subresponseField = subresponseField;
this._data = [];
}
exports.Task = Task;
/**
* Returns the number of elements in a task.
* @return {number} The number of elements.
*/
Task.prototype.getElementCount = function() {
var count = 0;
for (var i = 0; i < this._data.length; ++i) {
count += this._data[i].elements.length;
}
return count;
};
/**
* Returns the total byte size of the elements in a task.
* @return {number} The byte size.
*/
Task.prototype.getRequestByteSize = function() {
var size = 0;
for (var i = 0; i < this._data.length; ++i) {
size += this._data[i].bytes;
}
return size;
};
/**
* Invokes the actual API call with current elements.
* @return {string[]} - the list of ids for invocations to be run.
*/
Task.prototype.run = function() {
if (this._data.length === 0) {
return [];
}
var request = this._request;
var elements = [];
var ids = [];
for (var i = 0; i < this._data.length; ++i) {
elements.push.apply(elements, this._data[i].elements);
ids.push(this._data[i].callback.id);
}
request[this._bundledField] = elements;
var self = this;
this.callCanceller = this._apiCall(request, function(err, response) {
var responses = [];
if (err) {
self._data.forEach(function() {
responses.push(null);
});
} else {
var subresponseInfo = null;
if (self._subresponseField) {
subresponseInfo = {
field: self._subresponseField,
start: 0,
};
}
self._data.forEach(function(data) {
if (subresponseInfo) {
subresponseInfo.end = subresponseInfo.start + data.elements.length;
}
responses.push(deepCopyForResponse(response, subresponseInfo));
if (subresponseInfo) {
subresponseInfo.start = subresponseInfo.end;
}
});
}
for (var i = 0; i < self._data.length; ++i) {
if (self._data[i].cancelled) {
self._data[i].callback(new Error('cancelled'));
} else {
self._data[i].callback(err, responses[i]);
}
}
});
return ids;
};
/**
* Appends the list of elements into the task.
* @param {Object[]} elements - the new list of elements.
* @param {number} bytes - the byte size required to encode elements in the API.
* @param {APICallback} callback - the callback of the method call.
*/
Task.prototype.extend = function(elements, bytes, callback) {
this._data.push({
elements: elements,
bytes: bytes,
callback: callback,
});
};
/**
* Cancels a part of elements.
* @param {string} id - The identifier of the part of elements.
* @return {boolean} Whether the entire task will be canceled or not.
*/
Task.prototype.cancel = function(id) {
if (this.callCanceller) {
var allCancelled = true;
this._data.forEach(function(d) {
if (d.callback.id === id) {
d.cancelled = true;
}
if (!d.cancelled) {
allCancelled = false;
}
});
if (allCancelled) {
this.callCanceller.cancel();
}
return allCancelled;
}
for (var i = 0; i < this._data.length; ++i) {
if (this._data[i].callback.id === id) {
this._data[i].callback(new Error('cancelled'));
this._data.splice(i, 1);
break;
}
}
return this._data.length === 0;
};
/**
* Organizes requests for an api service that requires to bundle them.
*
* @param {BundleOptions} bundleOptions - configures strategy this instance
* uses when executing bundled functions.
* @param {BundleDescriptor} bundleDescriptor - the description of the bundling.
* @constructor
*/
function BundleExecutor(bundleOptions, bundleDescriptor) {
this._options = bundleOptions;
this._descriptor = bundleDescriptor;
this._tasks = {};
this._timers = {};
this._invocations = {};
this._invocationId = 0;
}
exports.BundleExecutor = BundleExecutor;
/**
* Schedule a method call.
*
* @param {function} apiCall - the function for an API call.
* @param {Object} request - the request object to be bundled with others.
* @param {APICallback} callback - the callback to be called when the method finished.
* @return {function()} - the function to cancel the scheduled invocation.
*/
BundleExecutor.prototype.schedule = function(apiCall, request, callback) {
var bundleId = computeBundleId(
request,
this._descriptor.requestDiscriminatorFields
);
if (!callback) {
callback = noop;
}
if (bundleId === undefined) {
console.warn(
'The request does not have enough information for request bundling. ' +
'Invoking immediately. Request: ' +
JSON.stringify(request) +
' discriminator fields: ' +
this._descriptor.requestDiscriminatorFields
);
return apiCall(request, callback);
}
if (!(bundleId in this._tasks)) {
this._tasks[bundleId] = new Task(
apiCall,
request,
this._descriptor.bundledField,
this._descriptor.subresponseField
);
}
var task = this._tasks[bundleId];
callback.id = String(this._invocationId++);
this._invocations[callback.id] = bundleId;
var bundledField = request[this._descriptor.bundledField];
var elementCount = bundledField.length;
var requestBytes = 0;
var self = this;
bundledField.forEach(function(obj) {
requestBytes += self._descriptor.byteLengthFunction(obj);
});
var countLimit = this._options.elementCountLimit || 0;
var byteLimit = this._options.requestByteLimit || 0;
if (
(countLimit > 0 && elementCount >= countLimit) ||
(byteLimit > 0 && requestBytes >= byteLimit)
) {
var message;
if (countLimit > 0 && elementCount >= countLimit) {
message =
'The number of elements ' +
elementCount +
' exceeds the limit ' +
this._options.elementCountLimit;
} else {
message =
'The required bytes ' +
requestBytes +
' exceeds the limit ' +
this._options.requestByteLimit;
}
callback(new Error(message));
return {
cancel: noop,
};
}
var existingCount = task.getElementCount();
var existingBytes = task.getRequestByteSize();
if (
(countLimit > 0 && elementCount + existingCount >= countLimit) ||
(byteLimit > 0 && requestBytes + existingBytes >= byteLimit)
) {
this._runNow(bundleId);
this._tasks[bundleId] = new Task(
apiCall,
request,
this._descriptor.bundledField,
this._descriptor.subresponseField
);
task = this._tasks[bundleId];
}
task.extend(bundledField, requestBytes, callback);
var ret = {
cancel: function() {
self._cancel(callback.id);
},
};
var countThreshold = this._options.elementCountThreshold || 0;
var sizeThreshold = this._options.requestByteThreshold || 0;
if (
(countThreshold > 0 && task.getElementCount() >= countThreshold) ||
(sizeThreshold > 0 && task.getRequestByteSize() >= sizeThreshold)
) {
this._runNow(bundleId);
return ret;
}
if (!(bundleId in this._timers) && this._options.delayThreshold > 0) {
this._timers[bundleId] = setTimeout(function() {
delete self._timers[bundleId];
self._runNow(bundleId);
}, self._options.delayThreshold);
}
return ret;
};
/**
* Clears scheduled timeout if it exists.
*
* @param {String} bundleId - the id for the task whose timeout needs to be
* cleared.
* @private
*/
BundleExecutor.prototype._maybeClearTimeout = function(bundleId) {
if (bundleId in this._timers) {
var timerId = this._timers[bundleId];
delete this._timers[bundleId];
clearTimeout(timerId);
}
};
/**
* Cancels an event.
*
* @param {String} id - The id for the event in the task.
* @private
*/
BundleExecutor.prototype._cancel = function(id) {
if (!(id in this._invocations)) {
return;
}
var bundleId = this._invocations[id];
if (!(bundleId in this._tasks)) {
return;
}
var task = this._tasks[bundleId];
delete this._invocations[id];
if (task.cancel(id)) {
this._maybeClearTimeout(bundleId);
delete this._tasks[bundleId];
}
};
/**
* Invokes a task.
*
* @param {String} bundleId - The id for the task.
* @private
*/
BundleExecutor.prototype._runNow = function(bundleId) {
if (!(bundleId in this._tasks)) {
console.warn('no such bundleid: ' + bundleId);
return;
}
this._maybeClearTimeout(bundleId);
var task = this._tasks[bundleId];
delete this._tasks[bundleId];
var self = this;
task.run().forEach(function(id) {
delete self._invocations[id];
});
};
/**
* Creates an API caller that bundles requests.
*
* @private
* @constructor
* @param {BundleExecutor} bundler - bundles API calls.
*/
function Bundleable(bundler) {
this.bundler = bundler;
NormalApiCaller.call(this);
}
util.inherits(Bundleable, NormalApiCaller);
Bundleable.prototype.call = function(apiCall, argument, settings, status) {
if (settings.isBundling) {
var self = this;
status.call(function(argument, callback) {
self.bundler.schedule(apiCall, argument, callback);
}, argument);
} else {
NormalApiCaller.prototype.call.call(
this,
apiCall,
argument,
settings,
status
);
}
};
/**
* Describes the structure of bundled call.
*
* requestDiscriminatorFields may include '.' as a separator, which is used to
* indicate object traversal. This allows fields in nested objects to be used
* to determine what request to bundle.
*
* @property {String} bundledField
* @property {String} requestDiscriminatorFields
* @property {String} subresponseField
* @property {Function} byteLengthFunction
*
* @param {String} bundledField - the repeated field in the request message
* that will have its elements aggregated by bundling.
* @param {String} requestDiscriminatorFields - a list of fields in the
* target request message class that are used to detemrine which request
* messages should be bundled together.
* @param {String} subresponseField - an optional field, when present it
* indicates the field in the response message that should be used to
* demultiplex the response into multiple response messages.
* @param {Function} byteLengthFunction - a function to obtain the byte
* length to be consumed for the bundled field messages. Because Node.JS
* protobuf.js/gRPC uses builtin Objects for the user-visible data and
* internally they are encoded/decoded in protobuf manner, this function
* is actually necessary to calculate the byte length.
* @constructor
*/
function BundleDescriptor(
bundledField,
requestDiscriminatorFields,
subresponseField,
byteLengthFunction
) {
if (!byteLengthFunction && typeof subresponseField === 'function') {
byteLengthFunction = subresponseField;
subresponseField = null;
}
this.bundledField = bundledField;
this.requestDiscriminatorFields = requestDiscriminatorFields;
this.subresponseField = subresponseField;
this.byteLengthFunction = byteLengthFunction;
}
exports.BundleDescriptor = BundleDescriptor;
/**
* Returns a new API caller.
* @private
* @param {CallSettings} settings - the current settings.
* @return {Bundleable} - the new bundling API caller.
*/
BundleDescriptor.prototype.apiCaller = function(settings) {
return new Bundleable(new BundleExecutor(settings.bundleOptions, this));
};

623
node_modules/google-gax/lib/gax.js generated vendored Normal file
View File

@@ -0,0 +1,623 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Google API Extensions
*/
'use strict';
/**
* Encapsulates the overridable settings for a particular API call.
*
* ``CallOptions`` is an optional arg for all GAX API calls. It is used to
* configure the settings of a specific API call.
*
* When provided, its values override the GAX service defaults for that
* particular call.
*
* Typically the API clients will accept this as the second to the last
* argument. See the examples below.
* @typedef {Object} CallOptions
* @property {number=} timeout - The client-side timeout for API calls.
* @property {RetryOptions=} retry - determines whether and how to retry
* on transient errors. When set to null, the call will not retry.
* @property {boolean=} autoPaginate - If set to false and the call is
* configured for paged iteration, page unrolling is not performed, instead
* the callback will be called with the response object.
* @property {Object=} pageToken - If set and the call is configured for
* paged iteration, paged iteration is not performed and requested with this
* pageToken.
* @property {number} maxResults - If set and the call is configured for
* paged iteration, the call will stop when the number of response elements
* reaches to the specified size. By default, it will unroll the page to
* the end of the list.
* @property {boolean=} isBundling - If set to false and the call is configured
* for bundling, bundling is not performed.
* @property {BackoffSettings=} longrunning - BackoffSettings used for polling.
* @property {Function=} promise - A constructor for a promise that implements the ES6
* specification of promise which will be used to create promises. If not
* provided, native promises will be used.
* @example
* // suppress bundling for bundled method.
* api.bundlingMethod(
* param, {optParam: aValue, isBundling: false}, function(err, response) {
* // handle response.
* });
* @example
* // suppress streaming for page-streaming method.
* api.pageStreamingMethod(
* param, {optParam: aValue, autoPaginate: false}, function(err, page) {
* // not returning a stream, but callback is called with the paged response.
* });
*/
/**
* Per-call configurable settings for retrying upon transient failure.
* @typedef {Object} RetryOptions
* @property {String[]} retryCodes
* @property {BackoffSettings} backoffSettings
*/
/**
* Parameters to the exponential backoff algorithm for retrying.
* @typedef {Object} BackoffSettings
* @property {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @property {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @property {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @property {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @propetry {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @property {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @property {number} totalTimeoutMillis - the total time, in milliseconds,
* starting from when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
*/
/**
* Parameter to configure bundling behavior.
* @typedef {Object} BundleOptions
* @property {number} elementCountThreshold -
* the bundled request will be sent once the count of outstanding elements
* in the repeated field reaches this value.
* @property {number} elementCountLimit -
* represents a hard limit on the number of elements in the repeated field
* of the bundle; if adding a request to a bundle would exceed this value,
* the bundle is sent and the new request is added to a fresh bundle. It is
* invalid for a single request to exceed this limit.
* @property {number} requestByteThreshold -
* the bundled request will be sent once the count of bytes in the request
* reaches this value. Note that this value is pessimistically approximated
* by summing the bytesizes of the elements in the repeated field, and
* therefore may be an under-approximation.
* @property {number} requestByteLimit -
* represents a hard limit on the size of the bundled request; if adding
* a request to a bundle would exceed this value, the bundle is sent and
* the new request is added to a fresh bundle. It is invalid for a single
* request to exceed this limit. Note that this value is pessimistically
* approximated by summing the bytesizes of the elements in the repeated
* field, with a buffer applied to correspond to the resulting
* under-approximation.
* @property {number} delayThreshold -
* the bundled request will be sent this amount of time after the first
* element in the bundle was added to it.
*/
/**
* @param {Object} settings - An object containing parameters of this settings.
* @param {number} settings.timeout - The client-side timeout for API calls.
* This parameter is ignored for retrying calls.
* @param {RetryOptions} settings.retry - The configuration for retrying upon
* transient error. If set to null, this call will not retry.
* @param {boolean} settings.autoPaginate - If there is no `pageDescriptor`,
* this attrbute has no meaning. Otherwise, determines whether a page streamed
* response should make the page structure transparent to the user by
* flattening the repeated field in the returned generator.
* @param {number} settings.pageToken - If there is no `pageDescriptor`,
* this attribute has no meaning. Otherwise, determines the page token used in
* the page streaming request.
* @param {Object} settings.otherArgs - Additional arguments to be passed to
* the API calls.
* @param {Function=} settings.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native promises
* will be used.
*
* @constructor
*/
function CallSettings(settings) {
settings = settings || {};
this.timeout = settings.timeout || 30 * 1000;
this.retry = settings.retry;
this.autoPaginate = 'autoPaginate' in settings ? settings.autoPaginate : true;
this.pageToken = settings.pageToken;
this.maxResults = settings.maxResults;
this.otherArgs = settings.otherArgs || {};
this.bundleOptions = settings.bundleOptions;
this.isBundling = 'isBundling' in settings ? settings.isBundling : true;
this.longrunning = 'longrunning' in settings ? settings.longrunning : null;
this.promise = 'promise' in settings ? settings.promise : Promise;
}
exports.CallSettings = CallSettings;
/**
* Returns a new CallSettings merged from this and a CallOptions object.
*
* @param {CallOptions} options - an instance whose values override
* those in this object. If null, ``merge`` returns a copy of this
* object
* @return {CallSettings} The merged CallSettings instance.
*/
CallSettings.prototype.merge = function merge(options) {
if (!options) {
return new CallSettings(this);
}
var timeout = this.timeout;
var retry = this.retry;
var autoPaginate = this.autoPaginate;
var pageToken = this.pageToken;
var maxResults = this.maxResults;
var otherArgs = this.otherArgs;
var isBundling = this.isBundling;
var longrunning = this.longrunning;
var promise = this.promise;
if ('timeout' in options) {
timeout = options.timeout;
}
if ('retry' in options) {
retry = options.retry;
}
if ('autoPaginate' in options && !options.autoPaginate) {
autoPaginate = false;
}
if ('pageToken' in options) {
autoPaginate = false;
pageToken = options.pageToken;
}
if ('maxResults' in options) {
maxResults = options.maxResults;
}
if ('otherArgs' in options) {
otherArgs = {};
for (var key in this.otherArgs) {
otherArgs[key] = this.otherArgs[key];
}
for (var optionsKey in options.otherArgs) {
otherArgs[optionsKey] = options.otherArgs[optionsKey];
}
}
if ('isBundling' in options) {
isBundling = options.isBundling;
}
if ('maxRetries' in options) {
retry.backoffSettings.maxRetries = options.maxRetries;
delete retry.backoffSettings.totalTimeoutMillis;
}
if ('longrunning' in options) {
longrunning = options.longrunning;
}
if ('promise' in options) {
promise = options.promise;
}
return new CallSettings({
timeout: timeout,
retry: retry,
bundleOptions: this.bundleOptions,
longrunning: longrunning,
autoPaginate: autoPaginate,
pageToken: pageToken,
maxResults: maxResults,
otherArgs: otherArgs,
isBundling: isBundling,
promise: promise,
});
};
/**
* Per-call configurable settings for retrying upon transient failure.
*
* @param {String[]} retryCodes - a list of Google API canonical error codes
* upon which a retry should be attempted.
* @param {BackoffSettings} backoffSettings - configures the retry
* exponential backoff algorithm.
* @return {RetryOptions} A new RetryOptions object.
*
*/
function createRetryOptions(retryCodes, backoffSettings) {
return {
retryCodes: retryCodes,
backoffSettings: backoffSettings,
};
}
exports.createRetryOptions = createRetryOptions;
/**
* Parameters to the exponential backoff algorithm for retrying.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} totalTimeoutMillis - the total time, in milliseconds,
* starting from when the initial request is sent, after which an error will
* be returned, regardless of the retrying attempts made meanwhile.
* @return {BackoffSettings} a new settings.
*
*/
function createBackoffSettings(
initialRetryDelayMillis,
retryDelayMultiplier,
maxRetryDelayMillis,
initialRpcTimeoutMillis,
rpcTimeoutMultiplier,
maxRpcTimeoutMillis,
totalTimeoutMillis
) {
return {
initialRetryDelayMillis: initialRetryDelayMillis,
retryDelayMultiplier: retryDelayMultiplier,
maxRetryDelayMillis: maxRetryDelayMillis,
initialRpcTimeoutMillis: initialRpcTimeoutMillis,
rpcTimeoutMultiplier: rpcTimeoutMultiplier,
maxRpcTimeoutMillis: maxRpcTimeoutMillis,
totalTimeoutMillis: totalTimeoutMillis,
};
}
exports.createBackoffSettings = createBackoffSettings;
/**
* Parameters to the exponential backoff algorithm for retrying.
* This function is unsupported, and intended for internal use only.
*
* @param {number} initialRetryDelayMillis - the initial delay time,
* in milliseconds, between the completion of the first failed request and the
* initiation of the first retrying request.
* @param {number} retryDelayMultiplier - the multiplier by which to
* increase the delay time between the completion of failed requests, and the
* initiation of the subsequent retrying request.
* @param {number} maxRetryDelayMillis - the maximum delay time, in
* milliseconds, between requests. When this value is reached,
* ``retryDelayMultiplier`` will no longer be used to increase delay time.
* @param {number} initialRpcTimeoutMillis - the initial timeout parameter
* to the request.
* @param {number} rpcTimeoutMultiplier - the multiplier by which to
* increase the timeout parameter between failed requests.
* @param {number} maxRpcTimeoutMillis - the maximum timeout parameter, in
* milliseconds, for a request. When this value is reached,
* ``rpcTimeoutMultiplier`` will no longer be used to increase the timeout.
* @param {number} maxRetries - the maximum number of retrying attempts that
* will be made. If reached, an error will be returned.
* @return {BackoffSettings} a new settings.
*
*/
function createMaxRetriesBackoffSettings(
initialRetryDelayMillis,
retryDelayMultiplier,
maxRetryDelayMillis,
initialRpcTimeoutMillis,
rpcTimeoutMultiplier,
maxRpcTimeoutMillis,
maxRetries
) {
return {
initialRetryDelayMillis: initialRetryDelayMillis,
retryDelayMultiplier: retryDelayMultiplier,
maxRetryDelayMillis: maxRetryDelayMillis,
initialRpcTimeoutMillis: initialRpcTimeoutMillis,
rpcTimeoutMultiplier: rpcTimeoutMultiplier,
maxRpcTimeoutMillis: maxRpcTimeoutMillis,
maxRetries: maxRetries,
};
}
exports.createMaxRetriesBackoffSettings = createMaxRetriesBackoffSettings;
/**
* Creates a new {@link BundleOptions}.
*
* @private
* @param {Object} options - An object to hold optional parameters. See
* properties for the content of options.
* @return {BundleOptions} - A new options.
*/
function createBundleOptions(options) {
var params = [
'element_count_threshold',
'element_count_limit',
'request_byte_threshold',
'request_byte_limit',
'delay_threshold_millis',
];
params.forEach(function(param) {
if (param in options && typeof options[param] !== 'number') {
throw new Error(param + ' should be a number');
}
});
var elementCountThreshold = options.element_count_threshold || 0;
var elementCountLimit = options.element_count_limit || 0;
var requestByteThreshold = options.request_byte_threshold || 0;
var requestByteLimit = options.request_byte_limit || 0;
var delayThreshold = options.delay_threshold_millis || 0;
if (
elementCountThreshold === 0 &&
requestByteThreshold === 0 &&
delayThreshold === 0
) {
throw new Error('one threshold should be > 0');
}
return {
elementCountThreshold: elementCountThreshold,
elementCountLimit: elementCountLimit,
requestByteThreshold: requestByteThreshold,
requestByteLimit: requestByteLimit,
delayThreshold: delayThreshold,
};
}
exports.createBundleOptions = createBundleOptions;
/**
* Helper for {@link constructSettings}
*
* @private
*
* @param {Object} methodConfig - A dictionary representing a single
* `methods` entry of the standard API client config file. (See
* {@link constructSettings} for information on this yaml.)
* @param {?Object} retryCodes - A dictionary parsed from the
* `retry_codes_def` entry of the standard API client config
* file. (See {@link constructSettings} for information on this yaml.)
* @param {Object} retryParams - A dictionary parsed from the
* `retry_params` entry of the standard API client config
* file. (See {@link constructSettings} for information on this yaml.)
* @param {Object} retryNames - A dictionary mapping the string names
* used in the standard API client config file to API response
* status codes.
* @return {?RetryOptions} The new retry options.
*/
function constructRetry(methodConfig, retryCodes, retryParams, retryNames) {
if (!methodConfig) {
return null;
}
var codes = null;
if (retryCodes && 'retry_codes_name' in methodConfig) {
var retryCodesName = methodConfig.retry_codes_name;
codes = (retryCodes[retryCodesName] || []).map(function(name) {
return retryNames[name];
});
}
var backoffSettings = null;
if (retryParams && 'retry_params_name' in methodConfig) {
var params = retryParams[methodConfig.retry_params_name];
backoffSettings = createBackoffSettings(
params.initial_retry_delay_millis,
params.retry_delay_multiplier,
params.max_retry_delay_millis,
params.initial_rpc_timeout_millis,
params.rpc_timeout_multiplier,
params.max_rpc_timeout_millis,
params.total_timeout_millis
);
}
return createRetryOptions(codes, backoffSettings);
}
/**
* Helper for {@link constructSettings}
*
* Takes two retry options, and merges them into a single RetryOption instance.
*
* @private
*
* @param {RetryOptions} retry - The base RetryOptions.
* @param {RetryOptions} overrides - The RetryOptions used for overriding
* `retry`. Use the values if it is not null. If entire `overrides` is null,
* ignore the base retry and return null.
* @return {?RetryOptions} The merged RetryOptions.
*/
function mergeRetryOptions(retry, overrides) {
if (!overrides) {
return null;
}
if (!overrides.retryCodes && !overrides.backoffSettings) {
return retry;
}
var codes = retry.retryCodes;
if (overrides.retryCodes) {
codes = overrides.retryCodes;
}
var backoffSettings = retry.backoffSettings;
if (overrides.backoffSettings) {
backoffSettings = overrides.backoffSettings;
}
return createRetryOptions(codes, backoffSettings);
}
/**
* Constructs a dictionary mapping method names to {@link CallSettings}.
*
* The `clientConfig` parameter is parsed from a client configuration JSON
* file of the form:
*
* {
* "interfaces": {
* "google.fake.v1.ServiceName": {
* "retry_codes": {
* "idempotent": ["UNAVAILABLE", "DEADLINE_EXCEEDED"],
* "non_idempotent": []
* },
* "retry_params": {
* "default": {
* "initial_retry_delay_millis": 100,
* "retry_delay_multiplier": 1.2,
* "max_retry_delay_millis": 1000,
* "initial_rpc_timeout_millis": 2000,
* "rpc_timeout_multiplier": 1.5,
* "max_rpc_timeout_millis": 30000,
* "total_timeout_millis": 45000
* }
* },
* "methods": {
* "CreateFoo": {
* "retry_codes_name": "idempotent",
* "retry_params_name": "default"
* },
* "Publish": {
* "retry_codes_name": "non_idempotent",
* "retry_params_name": "default",
* "bundling": {
* "element_count_threshold": 40,
* "element_count_limit": 200,
* "request_byte_threshold": 90000,
* "request_byte_limit": 100000,
* "delay_threshold_millis": 100
* }
* }
* }
* }
* }
* }
*
* @param {String} serviceName - The fully-qualified name of this
* service, used as a key into the client config file (in the
* example above, this value should be 'google.fake.v1.ServiceName').
* @param {Object} clientConfig - A dictionary parsed from the
* standard API client config file.
* @param {Object} configOverrides - A dictionary in the same structure of
* client_config to override the settings.
* @param {Object.<string, string[]>} retryNames - A dictionary mapping the strings
* referring to response status codes to objects representing
* those codes.
* @param {Object} otherArgs - the non-request arguments to be passed to the API
* calls.
* @param {Function=} promise - A constructor for a promise that implements the
* ES6 specification of promise. If not provided, native promises will be used.
* @return {Object} A mapping from method name to CallSettings, or null if the
* service is not found in the config.
*/
exports.constructSettings = function constructSettings(
serviceName,
clientConfig,
configOverrides,
retryNames,
otherArgs,
promise
) {
otherArgs = otherArgs || {};
var defaults = {};
var serviceConfig = (clientConfig.interfaces || {})[serviceName];
if (!serviceConfig) {
return null;
}
var overrides = (configOverrides.interfaces || {})[serviceName] || {};
var methods = serviceConfig.methods;
var overridingMethods = overrides.methods || {};
for (var methodName in methods) {
var methodConfig = methods[methodName];
var jsName = methodName[0].toLowerCase() + methodName.slice(1);
var retry = constructRetry(
methodConfig,
serviceConfig.retry_codes,
serviceConfig.retry_params,
retryNames
);
var bundlingConfig = methodConfig.bundling;
var timeout = methodConfig.timeout_millis;
if (methodName in overridingMethods) {
var overridingMethod = overridingMethods[methodName];
if (overridingMethod) {
if ('bundling' in overridingMethod) {
bundlingConfig = overridingMethod.bundling;
}
if ('timeout_millis' in overridingMethod) {
timeout = overridingMethod.timeout_millis;
}
}
retry = mergeRetryOptions(
retry,
constructRetry(
overridingMethod,
overrides.retry_codes,
overrides.retry_params,
retryNames
)
);
}
defaults[jsName] = new CallSettings({
timeout: timeout,
retry: retry,
bundleOptions: bundlingConfig
? createBundleOptions(bundlingConfig)
: null,
otherArgs: otherArgs,
promise: promise || Promise,
});
}
return defaults;
};

315
node_modules/google-gax/lib/grpc.js generated vendored Normal file
View File

@@ -0,0 +1,315 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
var autoAuth = require('google-auto-auth');
var fs = require('fs');
var gax = require('./gax');
var globby = require('globby');
var googleProtoFilesDir = require('google-proto-files')('..');
var path = require('path');
var protobuf = require('protobufjs');
var util = require('util');
googleProtoFilesDir = path.normalize(googleProtoFilesDir);
var COMMON_PROTO_DIRS = [
// This list of directories is defined here:
// https://github.com/googleapis/googleapis/blob/master/gapic/packaging/common_protos.yaml
'api',
path.join('iam', 'v1'),
path.join('logging', 'type'),
'longrunning',
'protobuf', // This is an additional path that the common protos depend on.
'rpc',
'type',
];
var COMMON_PROTO_GLOB_PATTERNS = COMMON_PROTO_DIRS.map(function(dir) {
return path.join(googleProtoFilesDir, 'google', dir, '**', '*.proto');
});
var COMMON_PROTO_FILES = globby
.sync(COMMON_PROTO_GLOB_PATTERNS)
.map(function(filename) {
return path.normalize(filename);
})
.map(function(filename) {
return filename.substring(googleProtoFilesDir.length + 1);
});
/**
* A class which keeps the context of gRPC and auth for the gRPC.
*
* @param {Object=} options - The optional parameters. It will be directly
* passed to google-auto-auth library, so parameters like keyFile or
* credentials will be valid.
* @param {Object=} options.auth - An instance of google-auto-auth.
* When specified, this auth instance will be used instead of creating
* a new one.
* @param {Object=} options.grpc - When specified, this will be used
* for the 'grpc' module in this context. By default, it will load the grpc
* module in the standard way.
* @param {Function=} options.promise - A constructor for a promise that
* implements the ES6 specification of promise. If not provided, native promises
* will be used.
* @constructor
*/
function GrpcClient(options) {
if (!(this instanceof GrpcClient)) {
return new GrpcClient(options);
}
options = options || {};
this.auth = options.auth || autoAuth(options);
this.promise = options.promise || Promise;
if ('grpc' in options) {
this.grpc = options.grpc;
this.grpcVersion = '';
} else {
this.grpc = require('grpc');
this.grpcVersion = require('grpc/package.json').version;
}
}
module.exports = GrpcClient;
/**
* Creates a gRPC credentials. It asks the auth data if necessary.
* @private
* @param {Object} opts - options values for configuring credentials.
* @param {Object=} opts.sslCreds - when specified, this is used instead
* of default channel credentials.
* @return {Promise} The promise which will be resolved to the gRPC credential.
*/
GrpcClient.prototype._getCredentials = function _getCredentials(opts) {
var PromiseCtor = this.promise;
if (opts.sslCreds) {
return PromiseCtor.resolve(opts.sslCreds);
}
var grpc = this.grpc;
var getAuthClient = this.auth.getAuthClient.bind(this.auth);
var sslCreds = grpc.credentials.createSsl();
return new PromiseCtor(function(resolve, reject) {
getAuthClient(function(err, auth) {
if (err) {
reject(err);
} else {
var credentials = grpc.credentials.combineChannelCredentials(
sslCreds,
grpc.credentials.createFromGoogleCredential(auth)
);
resolve(credentials);
}
});
});
};
/**
* Load grpc proto services with the specific arguments.
* @param {Array=} args - The argument list to be passed to grpc.load().
* @return {Object} The gRPC loaded result (the toplevel namespace object).
*/
GrpcClient.prototype.load = function(args) {
if (!args) {
args = [];
} else if (!Array.isArray(args)) {
args = [args];
}
if (args.length === 1) {
args.push('proto', {convertFieldsToCamelCase: true});
}
return this.grpc.load.apply(this.grpc, args);
};
/**
* Load grpc proto service from a filename hooking in googleapis common protos
* when necessary.
* @param {String} protoPath - The directory to search for the protofile.
* @param {String} filename - The filename of the proto to be loaded.
* @return {Object<string, *>} The gRPC loaded result (the toplevel namespace
* object).
*/
GrpcClient.prototype.loadProto = function(protoPath, filename) {
var resolvedPath = GrpcClient._resolveFile(protoPath, filename);
return this.grpc.loadObject(
protobuf.loadSync(resolvedPath, new GoogleProtoFilesRoot())
);
};
GrpcClient._resolveFile = function(protoPath, filename) {
if (fs.existsSync(path.join(protoPath, filename))) {
return path.join(protoPath, filename);
} else if (COMMON_PROTO_FILES.indexOf(filename) > -1) {
return path.join(googleProtoFilesDir, filename);
}
throw new Error(filename + ' could not be found in ' + protoPath);
};
GrpcClient.prototype.metadataBuilder = function(headers) {
var Metadata = this.grpc.Metadata;
var baseMetadata = new Metadata();
for (var key in headers) {
baseMetadata.set(key, headers[key]);
}
return function buildMetadata(abTests, moreHeaders) {
// TODO: bring the A/B testing info into the metadata.
var copied = false;
var metadata = baseMetadata;
for (var key in moreHeaders) {
if (
key.toLowerCase() !== 'x-goog-api-client' &&
moreHeaders.hasOwnProperty(key)
) {
if (!copied) {
copied = true;
metadata = metadata.clone();
}
metadata.set(key, moreHeaders[key]);
}
}
return metadata;
};
};
/**
* A wrapper of {@link constructSettings} function with under the gRPC context.
*
* Most of parameters are common among constructSettings, please take a look.
* @param {string} serviceName - The fullly-qualified name of the service.
* @param {Object} clientConfig - A dictionary of the client config.
* @param {Object} configOverrides - A dictionary of overriding configs.
* @param {Object} headers - A dictionary of additional HTTP header name to
* its value.
* @return {Object} A mapping of method names to CallSettings.
*/
GrpcClient.prototype.constructSettings = function constructSettings(
serviceName,
clientConfig,
configOverrides,
headers
) {
return gax.constructSettings(
serviceName,
clientConfig,
configOverrides,
this.grpc.status,
{metadataBuilder: this.metadataBuilder(headers)},
this.promise
);
};
/**
* Creates a gRPC stub with current gRPC and auth.
* @param {function} CreateStub - The constructor function of the stub.
* @param {Object} options - The optional arguments to customize
* gRPC connection. This options will be passed to the constructor of
* gRPC client too.
* @param {string} options.servicePath - The name of the server of the service.
* @param {number} options.port - The port of the service.
* @param {grpc.ClientCredentials=} options.sslCreds - The credentials to be used
* to set up gRPC connection.
* @return {Promise} A promse which resolves to a gRPC stub instance.
*/
GrpcClient.prototype.createStub = function(CreateStub, options) {
var serviceAddress = options.servicePath + ':' + options.port;
return this._getCredentials(options).then(function(credentials) {
var grpcOptions = {};
Object.keys(options).forEach(function(key) {
if (key.indexOf('grpc.') === 0) {
grpcOptions[key] = options[key];
}
});
return new CreateStub(serviceAddress, credentials, grpcOptions);
});
};
/**
* Creates a 'bytelength' function for a given proto message class.
*
* See {@link BundleDescriptor} about the meaning of the return value.
*
* @param {function} message - a constructor function that is generated by
* protobuf.js. Assumes 'encoder' field in the message.
* @return {function(Object):number} - a function to compute the byte length
* for an object.
*/
GrpcClient.createByteLengthFunction = function createByteLengthFunction(
message
) {
return function getByteLength(obj) {
return message.encode(obj).finish().length;
};
};
function GoogleProtoFilesRoot() {
protobuf.Root.call(this, [].slice.apply(arguments));
}
util.inherits(GoogleProtoFilesRoot, protobuf.Root);
module.exports.GoogleProtoFilesRoot = GoogleProtoFilesRoot;
// Causes the loading of an included proto to check if it is a common
// proto. If it is a common proto, use the google-proto-files proto.
GoogleProtoFilesRoot.prototype.resolvePath = function(originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
// Fully qualified paths don't need to be resolved.
if (path.isAbsolute(includePath)) {
if (!fs.existsSync(includePath)) {
throw new Error('The include `' + includePath + '` was not found.');
}
return includePath;
}
if (COMMON_PROTO_FILES.indexOf(includePath) > -1) {
return path.join(googleProtoFilesDir, includePath);
}
return GoogleProtoFilesRoot._findIncludePath(originPath, includePath);
};
GoogleProtoFilesRoot._findIncludePath = function(originPath, includePath) {
originPath = path.normalize(originPath);
includePath = path.normalize(includePath);
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
};

428
node_modules/google-gax/lib/longrunning.js generated vendored Normal file
View File

@@ -0,0 +1,428 @@
/*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var createBackoffSettings = require('./gax').createBackoffSettings;
var NormalApiCaller = require('./api_callable').NormalApiCaller;
var events = require('events');
var util = require('util');
/**
* A callback to upack a google.protobuf.Any message.
* @callback anyDecoder
* @param {google.protobuf.Any} message - The message to unpacked.
* @return {Object} - The unpacked message.
*/
/**
* Describes the structure of a page-streaming call.
*
* @property {OperationsClient} operationsClient
* @property {anyDecoder} responseDecoder
* @property {anyDecoder} metadataDecoder
*
* @param {OperationsClient} operationsClient - The client used to poll or
* cancel an operation.
* @param {anyDecoder=} responseDecoder - The decoder to unpack
* the response message.
* @param {anyDecoder=} metadataDecoder - The decoder to unpack
* the metadata message.
*
* @constructor
*/
function LongrunningDescriptor(
operationsClient,
responseDecoder,
metadataDecoder
) {
this.operationsClient = operationsClient;
this.responseDecoder = responseDecoder;
this.metadataDecoder = metadataDecoder;
}
LongrunningDescriptor.prototype.apiCaller = function() {
return new LongrunningApiCaller(this);
};
exports.LongrunningDescriptor = LongrunningDescriptor;
/**
* Creates an API caller that performs polling on a long running operation.
*
* @private
* @constructor
* @param {LongrunningDescriptor} longrunningDescriptor - Holds the
* decoders used for unpacking responses and the operationsClient
* used for polling the operation.
*/
function LongrunningApiCaller(longrunningDescriptor) {
NormalApiCaller.call(this);
this.longrunningDescriptor = longrunningDescriptor;
}
util.inherits(LongrunningApiCaller, NormalApiCaller);
LongrunningApiCaller.prototype.call = function(
apiCall,
argument,
settings,
canceller
) {
var self = this;
canceller.call(function(argument, callback) {
self._wrapOperation(apiCall, settings, argument, callback);
}, argument);
};
LongrunningApiCaller.prototype._wrapOperation = function(
apiCall,
settings,
argument,
callback
) {
var backoffSettings = settings.longrunning;
if (!backoffSettings) {
backoffSettings = createBackoffSettings(
100,
1.3,
60000,
null,
null,
null,
null
);
}
var longrunningDescriptor = this.longrunningDescriptor;
return apiCall(argument, function(err, rawResponse) {
if (err) {
callback(err, null, rawResponse);
return;
}
var operation = new Operation(
rawResponse,
longrunningDescriptor,
backoffSettings,
settings
);
callback(null, operation, rawResponse);
});
};
/**
* Wrapper for a google.longrunnung.Operation.
*
* @constructor
*
* @param {google.longrunning.Operation} grpcOp - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
function Operation(
grpcOp,
longrunningDescriptor,
backoffSettings,
callOptions
) {
events.EventEmitter.call(this);
this.completeListeners = 0;
this.hasActiveListeners = false;
this.latestResponse = grpcOp;
this.longrunningDescriptor = longrunningDescriptor;
this.result = null;
this.metadata = null;
this.backoffSettings = backoffSettings;
this._unpackResponse(grpcOp);
this._listenForEvents();
this._callOptions = callOptions;
}
util.inherits(Operation, events.EventEmitter);
/**
* 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
*/
Operation.prototype._listenForEvents = function() {
var self = this;
this.on('newListener', function(event) {
if (event === 'complete') {
self.completeListeners++;
if (!self.hasActiveListeners) {
self.hasActiveListeners = true;
self.startPolling_();
}
}
});
this.on('removeListener', function(event) {
if (event === 'complete' && --self.completeListeners === 0) {
self.hasActiveListeners = false;
}
});
};
/**
* Cancels current polling api call and cancels the operation.
*
* @return {Promise} the promise of the OperationsClient#cancelOperation api
* request.
*/
Operation.prototype.cancel = function() {
if (this.currentCallPromise_) {
this.currentCallPromise_.cancel();
}
var operationsClient = this.longrunningDescriptor.operationsClient;
return operationsClient.cancelOperation({name: this.latestResponse.name});
};
/**
* @callback GetOperationCallback
* @param {?Error} error
* @param {?Object} result
* @param {?Object} metadata
* @param {?google.longrunning.Operation} rawResponse
*/
/**
* Get the updated status of the operation. If the Operation has previously
* completed, this will use the status of the cached completed operation.
*
* - callback(err): Operation failed
* - callback(null, result, metadata, rawResponse): Operation complete
* - callback(null, null, metadata, rawResponse): Operation incomplete
*
* @param {getOperationCallback} callback - Callback to handle the polled
* operation result and metadata.
* @return {Promise|undefined} - This returns a promise if a callback is not specified.
* The promise resolves to an array where the first element is the unpacked
* result, the second element is the metadata, and the third element is the raw
* response of the api call. The promise rejects if the operation returns an
* error.
*/
Operation.prototype.getOperation = function(callback) {
var self = this;
var operationsClient = this.longrunningDescriptor.operationsClient;
function promisifyResponse() {
if (!callback) {
var PromiseCtor = self._callOptions.promise;
return new PromiseCtor(function(resolve, reject) {
if (self.latestResponse.error) {
var error = new Error(self.latestReponse.error.message);
error.code = self.latestReponse.error.code;
reject(error);
} else {
resolve([self.result, self.metadata, self.latestResponse]);
}
});
}
return;
}
if (this.latestResponse.done) {
this._unpackResponse(this.latestResponse, callback);
return promisifyResponse();
}
this.currentCallPromise_ = operationsClient.getOperation(
{name: this.latestResponse.name},
this._callOptions
);
var noCallbackPromise = this.currentCallPromise_.then(function(responses) {
self.latestResponse = responses[0];
self._unpackResponse(responses[0], callback);
return promisifyResponse();
});
if (!callback) {
return noCallbackPromise;
}
};
Operation.prototype._unpackResponse = function(op, callback) {
var responseDecoder = this.longrunningDescriptor.responseDecoder;
var metadataDecoder = this.longrunningDescriptor.metadataDecoder;
var response;
var metadata;
if (op.done) {
if (op.result === 'error') {
var error = new Error(op.error.message);
error.code = op.error.code;
if (callback) {
callback(error);
}
return;
}
if (responseDecoder && op.response) {
response = responseDecoder(op.response.value);
this.result = response;
}
}
if (metadataDecoder && op.metadata) {
metadata = metadataDecoder(op.metadata.value);
this.metadata = metadata;
}
if (callback) {
callback(null, response, metadata, op);
}
};
/**
* Poll `getOperation` to check the operation's status. This runs a loop to ping
* using the backoff strategy specified at initialization.
*
* Note: This method is automatically called once a "complete" event handler is
* registered on the operation.
*
* @private
*/
Operation.prototype.startPolling_ = function() {
var self = this;
var now = new Date();
var delayMult = this.backoffSettings.retryDelayMultiplier;
var maxDelay = this.backoffSettings.maxRetryDelayMillis;
var delay = this.backoffSettings.initialRetryDelayMillis;
var deadline = Infinity;
if (this.backoffSettings.totalTimeoutMillis) {
deadline = now.getTime() + this.backoffSettings.totalTimeoutMillis;
}
var previousMetadataBytes;
if (this.latestResponse.metadata) {
previousMetadataBytes = this.latestResponse.metadata.value;
}
function emit() {
self.emit.apply(self, Array.prototype.slice.call(arguments, 0));
}
function retry() {
if (!self.hasActiveListeners) {
return;
}
if (now.getTime() >= deadline) {
setImmediate(
emit,
'error',
new Error(
'Total timeout exceeded before ' + 'any response was received'
)
);
return;
}
self.getOperation(function(err, result, metadata, rawResponse) {
if (err) {
setImmediate(emit, 'error', err);
return;
}
if (!result) {
if (
rawResponse.metadata &&
(!previousMetadataBytes ||
!rawResponse.metadata.value.equals(previousMetadataBytes))
) {
setImmediate(emit, 'progress', metadata, rawResponse);
previousMetadataBytes = rawResponse.metadata.value;
}
setTimeout(function() {
now = new Date();
delay = Math.min(delay * delayMult, maxDelay);
retry();
}, delay);
return;
}
setImmediate(emit, 'complete', result, metadata, rawResponse);
});
}
retry();
};
/**
* Wraps the `complete` and `error` events in a Promise.
*
* @return {promise} - Promise that resolves on operation completion and rejects
* on operation error.
*/
Operation.prototype.promise = function() {
var self = this;
var PromiseCtor = this._callOptions.promise;
return new PromiseCtor(function(resolve, reject) {
self
.on('error', reject)
.on('complete', function(result, metadata, rawResponse) {
resolve([result, metadata, rawResponse]);
});
});
};
/**
* Method used to create Operation objects.
*
* @constructor
*
* @param {google.longrunning.Operation} op - The operation to be wrapped.
* @param {LongrunningDescriptor} longrunningDescriptor - This defines the
* operations service client and unpacking mechanisms for the operation.
* @param {BackoffSettings} backoffSettings - The backoff settings used in
* in polling the operation.
* @param {CallOptions=} callOptions - CallOptions used in making get operation
* requests.
*/
exports.operation = function(
op,
longrunningDescriptor,
backoffSettings,
callOptions
) {
return new Operation(op, longrunningDescriptor, backoffSettings, callOptions);
};

464
node_modules/google-gax/lib/operations_client.js generated vendored Normal file
View File

@@ -0,0 +1,464 @@
/*
* 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.
*
* EDITING INSTRUCTIONS
* This file was generated from the file
* https://github.com/googleapis/googleapis/blob/master/google/longrunning/operations.proto,
* and updates to that file get reflected here through a refresh process.
* For the short term, the refresh process will only be runnable by Google
* engineers.
*
* The only allowed edits are to method and file documentation. A 3-way
* merge preserves those additions if the generated source changes.
*/
/* TODO: introduce line-wrapping so that it never exceeds the limit. */
/* jscs: disable maximumLineLength */
'use strict';
var configData = require('./operations_client_config');
var extend = require('extend');
var gax = require('./gax');
extend(gax, require('./api_callable'));
extend(gax, require('./path_template'));
extend(gax, require('./paged_iteration'));
var SERVICE_ADDRESS = 'longrunning.googleapis.com';
var DEFAULT_SERVICE_PORT = 443;
var CODE_GEN_NAME_VERSION = 'gapic/0.7.1';
var PAGE_DESCRIPTORS = {
listOperations: new gax.PageDescriptor(
'pageToken',
'nextPageToken',
'operations'
),
};
/**
* The scopes needed to make gRPC calls to all of the methods defined in
* this service.
*/
var ALL_SCOPES = [];
/**
* Manages long-running operations with an API service.
*
* When an API method normally takes long time to complete, it can be designed
* to return {@link Operation} to the client, and the client can use this
* interface to receive the real response asynchronously by polling the
* operation resource, or pass the operation resource to another API (such as
* Google Cloud Pub/Sub API) to receive the response. Any API service that
* returns long-running operations should implement the `Operations` interface
* so developers can have a consistent client experience.
*
* This will be created through a builder function which can be obtained by the module.
* See the following example of how to initialize the module and how to access to the builder.
* @see {@link operationsClient}
*
* @class
*/
function OperationsClient(gaxGrpc, grpcClients, opts) {
opts = extend(
{
servicePath: SERVICE_ADDRESS,
port: DEFAULT_SERVICE_PORT,
clientConfig: {},
},
opts
);
var googleApiClient = ['gl-node/' + process.versions.node];
if (opts.libName && opts.libVersion) {
googleApiClient.push(opts.libName + '/' + opts.libVersion);
}
googleApiClient.push(
CODE_GEN_NAME_VERSION,
'gax/' + gax.version,
'grpc/' + gaxGrpc.grpcVersion
);
var defaults = gaxGrpc.constructSettings(
'google.longrunning.Operations',
configData,
opts.clientConfig,
{'x-goog-api-client': googleApiClient.join(' ')}
);
var self = this;
this.auth = gaxGrpc.auth;
var operationsStub = gaxGrpc.createStub(
grpcClients.google.longrunning.Operations,
opts
);
var operationsStubMethods = [
'getOperation',
'listOperations',
'cancelOperation',
'deleteOperation',
];
operationsStubMethods.forEach(function(methodName) {
self['_' + methodName] = gax.createApiCall(
operationsStub.then(function(operationsStub) {
return function() {
var args = Array.prototype.slice.call(arguments, 0);
return operationsStub[methodName].apply(operationsStub, args);
};
}),
defaults[methodName],
PAGE_DESCRIPTORS[methodName]
);
});
}
/**
* Get the project ID used by this class.
* @aram {function(Error, string)} callback - the callback to be called with
* the current project Id.
*/
OperationsClient.prototype.getProjectId = function(callback) {
return this.auth.getProjectId(callback);
};
// Service calls
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"}.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.getOperation({name: name}).then(function(responses) {
* var response = responses[0];
* // doThingsWith(response)
* }).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.getOperation = function(request, options, callback) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this._getOperation(request, options, callback);
};
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns `UNIMPLEMENTED`.
*
* NOTE: the `name` binding below allows API services to override the binding
* to use different resource name schemes.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error, ?Array, ?Object, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The second parameter to the callback is Array of [google.longrunning.Operation]{@link external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, it contains the result
* in a single response. If the response indicates the next page exists, the third
* parameter is set to be used for the next request object. The fourth parameter keeps
* the raw response object of an object representing [google.longrunning.ListOperationsResponse]{@link external:"google.longrunning.ListOperationsResponse"}.
* @return {Promise} - The promise which resolves to an array.
* The first element of the array is Array of [google.longrunning.Operation]{@link external:"google.longrunning.Operation"}.
*
* When autoPaginate: false is specified through options, the array has three elements.
* The first element is Array of [google.longrunning.Operation]{@link external:"google.longrunning.Operation"} in a single response.
* The second element is the next request object if the response
* indicates the next page exists, or null. The third element is
* an object representing [google.longrunning.ListOperationsResponse]{@link external:"google.longrunning.ListOperationsResponse"}.
*
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* // Iterate over all elements.
* client.listOperations(request).then(function(responses) {
* var resources = responses[0];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i])
* }
* }).catch(function(err) {
* console.error(err);
* });
*
* // Or obtain the paged response.
* var options = {autoPaginate: false};
* function callback(responses) {
* // The actual resources in a response.
* var resources = responses[0];
* // The next request if the response shows there's more responses.
* var nextRequest = responses[1];
* // The actual response object, if necessary.
* // var rawResponse = responses[2];
* for (var i = 0; i < resources.length; ++i) {
* // doThingsWith(resources[i]);
* }
* if (nextRequest) {
* // Fetch the next page.
* return client.listOperations(nextRequest, options).then(callback);
* }
* }
* client.listOperations(request, options)
* .then(callback)
* .catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.listOperations = function(
request,
options,
callback
) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this._listOperations(request, options, callback);
};
/**
* Equivalent to {@link listOperations}, but returns a NodeJS Stream object.
*
* This fetches the paged responses for {@link listOperations} continuously
* and invokes the callback registered for 'data' event for each element in the
* responses.
*
* The returned object has 'end' method when no more elements are required.
*
* autoPaginate option will be ignored.
*
* @see {@link https://nodejs.org/api/stream.html}
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation collection.
* @param {string} request.filter
* The standard list filter.
* @param {number=} request.pageSize
* The maximum number of resources contained in the underlying API
* response. If page streaming is performed per-resource, this
* parameter does not affect the return value. If page streaming is
* performed per-page, this determines the maximum number of
* resources in a page.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @return {Stream}
* An object stream which emits an object representing [google.longrunning.Operation]{@link external:"google.longrunning.Operation"} on 'data' event.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* var filter = '';
* var request = {
* name: name,
* filter: filter
* };
* client.listOperationsStream(request).on('data', function(element) {
* // doThingsWith(element)
* }).on('error', function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.listOperationsStream = function(request, options) {
if (options === undefined) {
options = {};
}
return PAGE_DESCRIPTORS.listOperations.createStream(
this._listOperations,
request,
options
);
};
/**
* Starts asynchronous cancellation on a long-running operation. The server
* makes a best effort to cancel the operation, but success is not
* guaranteed. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`. Clients can use
* {@link Operations.GetOperation} or
* other methods to check whether the cancellation succeeded or whether the
* operation completed despite cancellation. On successful cancellation,
* the operation is not deleted; instead, it becomes an operation with
* an {@link Operation.error} value with a {@link google.rpc.Status.code} of 1,
* corresponding to `Code.CANCELLED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be cancelled.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.cancelOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.cancelOperation = function(
request,
options,
callback
) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this._cancelOperation(request, options, callback);
};
/**
* Deletes a long-running operation. This method indicates that the client is
* no longer interested in the operation result. It does not cancel the
* operation. If the server doesn't support this method, it returns
* `google.rpc.Code.UNIMPLEMENTED`.
*
* @param {Object} request
* The request object that will be sent.
* @param {string} request.name
* The name of the operation resource to be deleted.
* @param {Object=} options
* Optional parameters. You can override the default settings for this call, e.g, timeout,
* retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details.
* @param {function(?Error)=} callback
* The function which will be called with the result of the API call.
* @return {Promise} - The promise which resolves when API call finishes.
* The promise has a method named "cancel" which cancels the ongoing API call.
*
* @example
*
* var client = longrunning.operationsClient();
* var name = '';
* client.deleteOperation({name: name}).catch(function(err) {
* console.error(err);
* });
*/
OperationsClient.prototype.deleteOperation = function(
request,
options,
callback
) {
if (options instanceof Function && callback === undefined) {
callback = options;
options = {};
}
if (options === undefined) {
options = {};
}
return this._deleteOperation(request, options, callback);
};
function OperationsClientBuilder(gaxGrpc) {
if (!(this instanceof OperationsClientBuilder)) {
return new OperationsClientBuilder(gaxGrpc);
}
var operationsClient = gaxGrpc.load([
{
root: require('google-proto-files')('..'),
file: 'google/longrunning/operations.proto',
},
]);
extend(this, operationsClient.google.longrunning);
/**
* Build a new instance of {@link OperationsClient}.
*
* @param {Object=} opts - The optional parameters.
* @param {String=} opts.servicePath
* The domain name of the API remote host.
* @param {number=} opts.port
* The port on which to connect to the remote host.
* @param {grpc.ClientCredentials=} opts.sslCreds
* A ClientCredentials for use with an SSL-enabled channel.
* @param {Object=} opts.clientConfig
* The customized config to build the call settings. See
* {@link gax.constructSettings} for the format.
*/
this.operationsClient = function(opts) {
return new OperationsClient(gaxGrpc, operationsClient, opts);
};
extend(this.operationsClient, OperationsClient);
}
module.exports = OperationsClientBuilder;
module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS;
module.exports.ALL_SCOPES = ALL_SCOPES;

View File

@@ -0,0 +1,46 @@
{
"interfaces": {
"google.longrunning.Operations": {
"retry_codes": {
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"non_idempotent": []
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 90000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 90000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListOperations": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CancelOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"DeleteOperation": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}

230
node_modules/google-gax/lib/paged_iteration.js generated vendored Normal file
View File

@@ -0,0 +1,230 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
var extend = require('extend');
var util = require('util');
var NormalApiCaller = require('./api_callable').NormalApiCaller;
var through2 = require('through2');
var ended = require('is-stream-ended');
/**
* Creates an API caller that returns a stream to performs page-streaming.
*
* @private
* @constructor
* @param {PageDescriptor} pageDescriptor - indicates the structure
* of page streaming to be performed.
*/
function PagedIteration(pageDescriptor) {
NormalApiCaller.call(this);
this.pageDescriptor = pageDescriptor;
}
util.inherits(PagedIteration, NormalApiCaller);
PagedIteration.prototype.createActualCallback = function(request, callback) {
var self = this;
return function fetchNextPageToken(err, response) {
if (err) {
callback(err);
return;
}
var resources = response[self.pageDescriptor.resourceField];
var pageToken = response[self.pageDescriptor.responsePageTokenField];
if (pageToken) {
request[self.pageDescriptor.requestPageTokenField] = pageToken;
callback(err, resources, request, response);
} else {
callback(err, resources, null, response);
}
};
};
PagedIteration.prototype.wrap = function(func) {
var self = this;
return function wrappedCall(argument, metadata, options, callback) {
return func(
argument,
metadata,
options,
self.createActualCallback(argument, callback)
);
};
};
PagedIteration.prototype.init = function(settings, callback) {
return NormalApiCaller.prototype.init.call(this, settings, callback);
};
PagedIteration.prototype.call = function(
apiCall,
argument,
settings,
canceller
) {
argument = extend({}, argument);
if (settings.pageToken) {
argument[this.pageDescriptor.requestPageTokenField] = settings.pageToken;
}
if (settings.pageSize) {
argument[this.pageDescriptor.requestPageSizeField] = settings.pageSize;
}
if (!settings.autoPaginate) {
NormalApiCaller.prototype.call.call(
this,
apiCall,
argument,
settings,
canceller
);
return;
}
var maxResults = settings.maxResults || -1;
var allResources = [];
function pushResources(err, resources, next) {
if (err) {
canceller.callback(err);
return;
}
for (var i = 0; i < resources.length; ++i) {
allResources.push(resources[i]);
if (allResources.length === maxResults) {
next = null;
break;
}
}
if (!next) {
canceller.callback(null, allResources);
return;
}
setImmediate(apiCall, next, pushResources);
}
setImmediate(apiCall, argument, pushResources);
};
/**
* Describes the structure of a page-streaming call.
*
* @property {String} requestPageTokenField
* @property {String} responsePageTokenField
* @property {String} resourceField
*
* @param {String} requestPageTokenField - The field name of the page token in
* the request.
* @param {String} responsePageTokenField - The field name of the page token in
* the response.
* @param {String} resourceField - The resource field name.
*
* @constructor
*/
function PageDescriptor(
requestPageTokenField,
responsePageTokenField,
resourceField
) {
this.requestPageTokenField = requestPageTokenField;
this.responsePageTokenField = responsePageTokenField;
this.resourceField = resourceField;
}
exports.PageDescriptor = PageDescriptor;
/**
* Creates a new object Stream which emits the resource on 'data' event.
* @private
* @param {ApiCall} apiCall - the callable object.
* @param {Object} request - the request object.
* @param {CallOptions=} options - the call options to customize the api call.
* @return {Stream} - a new object Stream.
*/
PageDescriptor.prototype.createStream = function(apiCall, request, options) {
var stream = through2.obj();
options = extend({}, options, {autoPaginate: false});
var maxResults = 'maxResults' in options ? options.maxResults : -1;
var pushCount = 0;
var started = false;
function callback(err, resources, next) {
if (err) {
stream.emit('error', err);
return;
}
for (var i = 0; i < resources.length; ++i) {
if (ended(stream)) {
return;
}
if (resources[i] === null) {
continue;
}
stream.push(resources[i]);
pushCount++;
if (pushCount === maxResults) {
stream.end();
}
}
if (ended(stream)) {
return;
}
if (!next) {
stream.end();
return;
}
// When pageToken is specified in the original options, it will overwrite
// the page token field in the next request. Therefore it must be cleared.
if ('pageToken' in options) {
delete options.pageToken;
}
if (stream.isPaused()) {
request = next;
started = false;
} else {
setImmediate(apiCall, next, options, callback);
}
}
stream.on('resume', function() {
if (!started) {
started = true;
apiCall(request, options, callback);
}
});
return stream;
};
/**
* Returns a new API caller.
* @private
* @return {PageStreamable} - the page streaming caller.
*/
PageDescriptor.prototype.apiCaller = function() {
return new PagedIteration(this);
};

120
node_modules/google-gax/lib/parser_extras.js generated vendored Normal file
View File

@@ -0,0 +1,120 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
var util = require('util');
var _ = require('lodash');
/* constants used in the pegjs parser */
var BINDING = (exports.BINDING = 1);
exports.END_BINDING = 2;
var TERMINAL = (exports.TERMINAL = 3);
/**
* Checks that segments only has one terminal segment that is a path wildcard.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @throws {TypeError} if there are too many
*/
function allowOnePathWildcard(segments) {
var hasPathWildcard = false;
for (var i = 0; i < segments.length; i++) {
var s = segments[i];
if (s.kind !== TERMINAL || s.literal !== '**') {
continue;
}
if (hasPathWildcard) {
var tooManyWildcards = 'cannot contain more than one path wildcard';
throw new TypeError(tooManyWildcards);
}
hasPathWildcard = true;
}
}
/**
* Counts the number of terminal segments.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @return {number} the number of terminal segments in the template
*/
function countTerminals(segments) {
var terms = _.filter(segments, function(x) {
return x.kind === TERMINAL;
});
return terms.length;
}
/**
* Updates missing literals of each of the binding segments.
*
* @private
*
* @param {Segments[]} segments the parsed segments
*/
function updateBindingLiterals(segments) {
var bindingIndex = 0;
segments.forEach(function(s) {
if (s.kind === BINDING && !s.literal) {
s.literal = util.format('$%d', bindingIndex);
bindingIndex += 1;
}
});
}
/**
* Completes the parsing of the segments
*
* Validates them, and transforms them into the object used by the
* PathTemplate class.
*
* @private
*
* @param {Segments[]} segments the parsed segments
* @param {Object} initializes the attributes of a PathTemplate
* @return {Object} Returns segments and size
* @throws {TypeError} if multiple path wildcards exist
*/
function finishParse(segments) {
allowOnePathWildcard(segments);
updateBindingLiterals(segments);
return {
segments: segments,
size: countTerminals(segments),
};
}
exports.finishParse = finishParse;

191
node_modules/google-gax/lib/path_template.js generated vendored Normal file
View File

@@ -0,0 +1,191 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
'use strict';
/*
* Path template utility.
*/
var _ = require('lodash');
var extras = require('./parser_extras');
var util = require('util');
exports.PathTemplate = PathTemplate;
/**
* @param {String} data the of the template
*
* @constructor
*/
function PathTemplate(data) {
var parser = require('./path_template_parser');
var parseResult = extras.finishParse(parser.parse(data));
Object.defineProperty(this, 'size', {
get: function() {
return parseResult.size;
},
});
Object.defineProperty(this, 'segments', {
get: function() {
return parseResult.segments;
},
});
}
/**
* Matches a fully-qualified path template string.
*
* @param {String} path a fully-qualified path template string
* @return {Object} contains var names matched to binding values
* @throws {TypeError} if path can't be matched to this template
*/
PathTemplate.prototype.match = function match(path) {
var pathSegments = path.split('/');
var bindings = {};
var segmentCount = this.size;
var current = null;
var index = 0;
this.segments.forEach(function(segment) {
if (index > pathSegments.length) {
return;
}
if (segment.kind === extras.BINDING) {
current = segment.literal;
} else if (segment.kind === extras.TERMINAL) {
if (segment.literal === '*') {
bindings[current] = pathSegments[index];
index += 1;
} else if (segment.literal === '**') {
var size = pathSegments.length - segmentCount + 1;
segmentCount += size - 1;
bindings[current] = pathSegments.slice(index, index + size).join('/');
index += size;
} else if (segment.literal === pathSegments[index]) {
index += 1;
} else {
var msg = util.format(
"mismatched literal (index=%d): '%s' != '%s'",
index,
segment.literal,
pathSegments[index]
);
throw new TypeError(msg);
}
}
});
if (index !== pathSegments.length || index !== segmentCount) {
var msg = util.format(
'match error: could not instantiate a path template from %s',
path
);
throw new TypeError(msg);
}
return bindings;
};
/**
* Renders a path template using the provided bindings.
*
* @param {Object} bindings a mapping of var names to binding strings
* @return {String} a rendered representation of the path template
* @throws {TypeError} if a key is missing, or if a sub-template cannot be
* parsed
*/
PathTemplate.prototype.render = function render(bindings) {
var out = [];
var inABinding = false;
this.segments.forEach(function(segment) {
if (segment.kind === extras.BINDING) {
if (!_.has(bindings, segment.literal)) {
var msg = util.format(
'Value for key %s is not provided in %s',
segment.literal,
bindings
);
throw new TypeError(msg);
}
var tmp = new PathTemplate(bindings[segment.literal]);
Array.prototype.push.apply(out, tmp.segments);
inABinding = true;
} else if (segment.kind === extras.END_BINDING) {
inABinding = false;
} else if (inABinding) {
return;
} else {
out.push(segment);
}
});
var result = formatSegments(out);
this.match(result);
return result;
};
/**
* Renders the path template.
*
* @return {string} contains var names matched to binding values
*/
PathTemplate.prototype.inspect = function inspect() {
return formatSegments(this.segments);
};
/**
* Creates the string representattion for the segments.
* @param {Object[]} segments - The array of segments.
* @return {string} - A string representing segments in the path template
* format.
*/
function formatSegments(segments) {
var out = '';
var slash = true;
segments.forEach(function(segment) {
if (segment.kind === extras.TERMINAL) {
if (slash) {
out += '/';
}
out += segment.literal;
return;
}
slash = true;
if (segment.kind === extras.BINDING) {
out += '/{' + segment.literal + '=';
slash = false;
} else {
out += segment.literal + '}';
}
});
return out.substring(1);
}

664
node_modules/google-gax/lib/path_template_parser.js generated vendored Normal file
View File

@@ -0,0 +1,664 @@
/* eslint-disable */
module.exports = (function() {
'use strict';
/*
* Generated by PEG.js 0.9.0.
*
* http://pegjs.org/
*/
function peg$subclass(child, parent) {
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = 'SyntaxError';
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
function peg$parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
parser = this,
peg$FAILED = {},
peg$startRuleFunctions = {template: peg$parsetemplate},
peg$startRuleFunction = peg$parsetemplate,
peg$c0 = '/',
peg$c1 = {type: 'literal', value: '/', description: '"/"'},
peg$c2 = function(segments) {
return segments;
},
peg$c3 = function(s, segments) {
return s.concat(segments);
},
peg$c4 = function(s) {
return s;
},
peg$c5 = '{',
peg$c6 = {type: 'literal', value: '{', description: '"{"'},
peg$c7 = '=',
peg$c8 = {type: 'literal', value: '=', description: '"="'},
peg$c9 = '}',
peg$c10 = {type: 'literal', value: '}', description: '"}"'},
peg$c11 = function(l, segments) {
return _.flatten([
{kind: extras.BINDING, literal: l},
segments,
{kind: extras.END_BINDING, literal: ''},
]);
},
peg$c12 = function(l) {
return [
{kind: extras.BINDING, literal: l},
{kind: extras.TERMINAL, literal: '*'},
{kind: extras.END_BINDING, literal: ''},
];
},
peg$c13 = function(t, segments) {
return t.concat(segments);
},
peg$c14 = function(t) {
if (t[0].literal === '*' || t[0].literal === '**') {
return [
{
kind: extras.BINDING,
},
t[0],
{kind: extras.END_BINDING, literal: ''},
];
} else {
return t;
}
},
peg$c15 = '**',
peg$c16 = {type: 'literal', value: '**', description: '"**"'},
peg$c17 = '*',
peg$c18 = {type: 'literal', value: '*', description: '"*"'},
peg$c19 = function(l) {
return [{kind: extras.TERMINAL, literal: l}];
},
peg$c20 = /^[^*=}{\/]/,
peg$c21 = {type: 'class', value: '[^*=}{/]', description: '[^*=}{/]'},
peg$c22 = function(cs) {
return cs.join('');
},
peg$currPos = 0,
peg$savedPos = 0,
peg$posDetailsCache = [{line: 1, column: 1, seenCR: false}],
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ('startRule' in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error(
'Can\'t start parsing from rule "' + options.startRule + '".'
);
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$savedPos, peg$currPos);
}
function location() {
return peg$computeLocation(peg$savedPos, peg$currPos);
}
function expected(description) {
throw peg$buildException(
null,
[{type: 'other', description: description}],
input.substring(peg$savedPos, peg$currPos),
peg$computeLocation(peg$savedPos, peg$currPos)
);
}
function error(message) {
throw peg$buildException(
message,
null,
input.substring(peg$savedPos, peg$currPos),
peg$computeLocation(peg$savedPos, peg$currPos)
);
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos],
p,
ch;
if (details) {
return details;
} else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column,
seenCR: details.seenCR,
};
while (p < pos) {
ch = input.charAt(p);
if (ch === '\n') {
if (!details.seenCR) {
details.line++;
}
details.column = 1;
details.seenCR = false;
} else if (ch === '\r' || ch === '\u2028' || ch === '\u2029') {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos),
endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column,
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column,
},
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) {
return;
}
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, found, location) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) {
return ch
.charCodeAt(0)
.toString(16)
.toUpperCase();
}
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) {
return '\\x0' + hex(ch);
})
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) {
return '\\x' + hex(ch);
})
.replace(/[\u0100-\u0FFF]/g, function(ch) {
return '\\u0' + hex(ch);
})
.replace(/[\u1000-\uFFFF]/g, function(ch) {
return '\\u' + hex(ch);
});
}
var expectedDescs = new Array(expected.length),
expectedDesc,
foundDesc,
i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc =
expected.length > 1
? expectedDescs.slice(0, -1).join(', ') +
' or ' +
expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? '"' + stringEscape(found) + '"' : 'end of input';
return 'Expected ' + expectedDesc + ' but ' + foundDesc + ' found.';
}
if (expected !== null) {
cleanupExpected(expected);
}
return new peg$SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
location
);
}
function peg$parsetemplate() {
var s0, s1, s2;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 47) {
s1 = peg$c0;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parsebound_segments();
if (s2 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c2(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsebound_segments();
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c2(s1);
}
s0 = s1;
}
return s0;
}
function peg$parsebound_segments() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parsebound_segment();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s2 = peg$c0;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsebound_segments();
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c3(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$parsebound_segment();
}
return s0;
}
function peg$parsebound_segment() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parsebound_terminal();
if (s1 === peg$FAILED) {
s1 = peg$parsevariable();
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c4(s1);
}
s0 = s1;
return s0;
}
function peg$parsevariable() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c5;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c6);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseliteral();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c7;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c8);
}
}
if (s3 !== peg$FAILED) {
s4 = peg$parseunbound_segments();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s5 = peg$c9;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s5 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c11(s2, s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c5;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c6);
}
}
if (s1 !== peg$FAILED) {
s2 = peg$parseliteral();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c10);
}
}
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c12(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
}
return s0;
}
function peg$parseunbound_segments() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$parseunbound_terminal();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s2 = peg$c0;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c1);
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parseunbound_segments();
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c13(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
if (s0 === peg$FAILED) {
s0 = peg$parseunbound_terminal();
}
return s0;
}
function peg$parsebound_terminal() {
var s0, s1;
s0 = peg$currPos;
s1 = peg$parseunbound_terminal();
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c14(s1);
}
s0 = s1;
return s0;
}
function peg$parseunbound_terminal() {
var s0, s1;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c15) {
s1 = peg$c15;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c16);
}
}
if (s1 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 42) {
s1 = peg$c17;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c18);
}
}
if (s1 === peg$FAILED) {
s1 = peg$parseliteral();
}
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c19(s1);
}
s0 = s1;
return s0;
}
function peg$parseliteral() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c20.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c21);
}
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c20.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) {
peg$fail(peg$c21);
}
}
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
return s0;
}
var _ = require('lodash');
var util = require('util');
var extras = require('./parser_extras');
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({type: 'end', description: 'end of input'});
}
throw peg$buildException(
null,
peg$maxFailExpected,
peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
peg$maxFailPos < input.length
? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)
: peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
);
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse,
};
})();

105
node_modules/google-gax/lib/path_template_parser.pegjs generated vendored Normal file
View File

@@ -0,0 +1,105 @@
/*
*
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
{
var _ = require('lodash');
var util = require('util');
var extras = require('./parser_extras');
}
template
= '/' segments:bound_segments { return segments; }
/ segments:bound_segments { return segments; }
bound_segments
= s:bound_segment '/' segments:bound_segments {
return s.concat(segments);
}
/ bound_segment
bound_segment
= s:( bound_terminal / variable ) { return s; }
variable
= '{' l:literal '=' segments:unbound_segments '}' {
return _.flatten([
{ kind: extras.BINDING, literal: l },
segments,
{ kind: extras.END_BINDING, literal: '' }
]);
}
/ '{' l:literal '}' {
return [
{ kind: extras.BINDING, literal: l },
{ kind: extras.TERMINAL, literal: '*' },
{ kind: extras.END_BINDING, literal: '' }
];
}
unbound_segments
= t:unbound_terminal '/' segments:unbound_segments {
return t.concat(segments);
}
/ unbound_terminal
bound_terminal
= t:unbound_terminal {
if (t[0].literal === '*' || t[0].literal === '**') {
return [
{
kind: extras.BINDING,
},
t[0],
{ kind: extras.END_BINDING, literal: '' }
];
} else {
return t;
}
}
unbound_terminal
= l:( '**' / '*' / literal ) {
return [
{ kind: extras.TERMINAL, literal: l }
];
}
literal
= cs:[^*=}{/]+ { return cs.join('') }

57
node_modules/google-gax/lib/routing_header.js generated vendored Normal file
View File

@@ -0,0 +1,57 @@
/*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Helpers for constructing routing headers.
*
* These headers are used by Google infrastructure to determine how to route
* requests, especially for services that are regional.
*
* Generally, these headers are specified as gRPC metadata.
*/
'use strict';
/**
* Constructs the routing header from the given params
*
* @param {Object} params - the request header parameters.
* @return {string} the routing header value.
*/
function fromParams(params) {
return Object.keys(params)
.map(function(key) {
return key + '=' + params[key];
})
.join('&');
}
exports.fromParams = fromParams;

190
node_modules/google-gax/lib/streaming.js generated vendored Normal file
View File

@@ -0,0 +1,190 @@
/**
* Copyright 2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
/* This file describes the gRPC-streaming. */
var util = require('util');
var Duplexify = require('duplexify');
/**
* The type of gRPC streaming.
* @enum {number}
*/
var StreamType = {
/** Client sends a single request, server streams responses. */
SERVER_STREAMING: 1,
/** Client streams requests, server returns a single response. */
CLIENT_STREAMING: 2,
/** Both client and server stream objects. */
BIDI_STREAMING: 3,
};
exports.StreamType = StreamType;
/**
* StreamProxy is a proxy to gRPC-streaming method.
*
* @private
* @constructor
* @param {StreamType} type - the type of gRPC stream.
* @param {ApiCallback} callback - the callback for further API call.
*/
function StreamProxy(type, callback) {
Duplexify.call(this, null, null, {
objectMode: true,
readable: type !== StreamType.CLIENT_STREAMING,
writable: type !== StreamType.SERVER_STREAMING,
});
this.type = type;
this._callback = callback;
this._isCancelCalled = false;
}
util.inherits(StreamProxy, Duplexify);
StreamProxy.prototype.cancel = function() {
if (this.stream) {
this.stream.cancel();
} else {
this._isCancelCalled = true;
}
};
/**
* Specifies the target stream.
* @param {ApiCall} apiCall - the API function to be called.
* @param {Object} argument - the argument to be passed to the apiCall.
*/
StreamProxy.prototype.setStream = function(apiCall, argument) {
var stream = apiCall(argument, this._callback);
this.stream = stream;
var self = this;
['metadata', 'status'].forEach(function(event) {
stream.on(event, function() {
var args = Array.prototype.slice.call(arguments, 0);
args.unshift(event);
self.emit.apply(self, args);
});
});
// We also want to supply the status data as 'response' event to support
// the behavior of google-cloud-node expects.
// see: https://github.com/GoogleCloudPlatform/google-cloud-node/pull/1775#issuecomment-259141029
// https://github.com/GoogleCloudPlatform/google-cloud-node/blob/116436fa789d8b0f7fc5100b19b424e3ec63e6bf/packages/common/src/grpc-service.js#L355
stream.on('metadata', function(metadata) {
// Create a response object with succeeds.
// TODO: unify this logic with the decoration of gRPC response when it's added.
// see: https://github.com/googleapis/gax-nodejs/issues/65
self.emit('response', {
code: 200,
details: '',
message: 'OK',
metadata: metadata,
});
});
if (this.type !== StreamType.CLIENT_STREAMING) {
this.setReadable(stream);
}
if (this.type !== StreamType.SERVER_STREAMING) {
this.setWritable(stream);
}
if (this._isCancelCalled) {
stream.cancel();
}
};
/**
* An API caller for methods of gRPC streaming.
* @private
* @constructor
* @param {StreamDescriptor} descriptor - the descriptor of the method structure.
*/
function GrpcStreamable(descriptor) {
this.descriptor = descriptor;
}
GrpcStreamable.prototype.init = function(settings, callback) {
return new StreamProxy(this.descriptor.type, callback);
};
GrpcStreamable.prototype.wrap = function(func) {
switch (this.descriptor.type) {
case StreamType.SERVER_STREAMING:
return function(argument, metadata, options) {
return func(argument, metadata, options);
};
case StreamType.CLIENT_STREAMING:
return function(argument, metadata, options, callback) {
return func(metadata, options, callback);
};
case StreamType.BIDI_STREAMING:
return function(argument, metadata, options) {
return func(metadata, options);
};
default:
console.error('Unknown stream type', this.descriptor.type);
}
return func;
};
GrpcStreamable.prototype.call = function(apiCall, argument, settings, stream) {
stream.setStream(apiCall, argument);
};
GrpcStreamable.prototype.fail = function(stream, err) {
stream.emit('error', err);
};
GrpcStreamable.prototype.result = function(stream) {
return stream;
};
/**
* Describes the structure of gRPC streaming call.
* @constructor
* @param {StreamType} streamType - the type of streaming.
*/
function StreamDescriptor(streamType) {
this.type = streamType;
}
StreamDescriptor.prototype.apiCaller = function(settings) {
// Right now retrying does not work with gRPC-streaming, because retryable
// assumes an API call returns an event emitter while gRPC-streaming methods
// return Stream.
// TODO: support retrying.
settings.retry = null;
return new GrpcStreamable(this);
};
exports.StreamDescriptor = StreamDescriptor;

46
node_modules/google-gax/package.json generated vendored Normal file
View File

@@ -0,0 +1,46 @@
{
"name": "google-gax",
"version": "0.16.1",
"description": "Google API Extensions",
"main": "index.js",
"files": [
"lib"
],
"dependencies": {
"duplexify": "^3.5.4",
"extend": "^3.0.0",
"globby": "^8.0.0",
"google-auto-auth": "^0.10.0",
"google-proto-files": "^0.15.0",
"grpc": "^1.10.0",
"is-stream-ended": "^0.1.0",
"lodash": "^4.17.2",
"protobufjs": "^6.8.0",
"through2": "^2.0.3"
},
"devDependencies": {
"chai": "*",
"codecov": "~3.0.0",
"eslint": "^4.10.0",
"eslint-config-prettier": "^2.7.0",
"eslint-plugin-node": "^6.0.0",
"eslint-plugin-prettier": "^2.3.1",
"ink-docstrap": "^1.3.2",
"istanbul": "~0.4.5",
"jsdoc": "^3.5.5",
"mocha": "~5.0.0",
"pegjs": "~0.10.0",
"prettier": "^1.9.2",
"proxyquire": "^2.0.0",
"pumpify": "^1.3.5",
"sinon": "~4.4.0",
"stream-events": "^1.0.1"
},
"repository": "googleapis/gax-nodejs",
"author": "Google API Authors",
"license": "BSD-3-Clause",
"homepage": "https://github.com/googleapis/gax-nodejs#readme",
"engines": {
"node": ">=0.12.0"
}
}