1
0
mirror of https://github.com/musix-org/musix-oss synced 2025-07-03 00:34:28 +00:00
This commit is contained in:
MatteZ02
2019-10-10 16:43:04 +03:00
parent 6f6ac8a6fa
commit 50b9bed483
9432 changed files with 1988816 additions and 167 deletions

View File

@ -0,0 +1,189 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const logger_1 = require("./logger");
/*
* @module firestore/backoff
* @private
*
* Contains backoff logic to facilitate RPC error handling. This class derives
* its implementation from the Firestore Mobile Web Client.
*
* @see https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore/src/remote/backoff.ts
*/
/*!
* The default initial backoff time in milliseconds after an error.
* Set to 1s according to https://cloud.google.com/apis/design/errors.
*/
const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;
/*!
* The default maximum backoff time in milliseconds.
*/
const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;
/*!
* The default factor to increase the backup by after each failed attempt.
*/
const DEFAULT_BACKOFF_FACTOR = 1.5;
/*!
* The default jitter to distribute the backoff attempts by (0 means no
* randomization, 1.0 means +/-50% randomization).
*/
const DEFAULT_JITTER_FACTOR = 1.0;
/*!
* The maximum number of retries that will be attempted by backoff
* before stopping all retry attempts.
*/
exports.MAX_RETRY_ATTEMPTS = 10;
/*!
* The timeout handler used by `ExponentialBackoff`.
*/
let delayExecution = setTimeout;
/**
* Allows overriding of the timeout handler used by the exponential backoff
* implementation. If not invoked, we default to `setTimeout()`.
*
* Used only in testing.
*
* @private
* @param {function} handler A handler than matches the API of `setTimeout()`.
*/
function setTimeoutHandler(handler) {
delayExecution = handler;
}
exports.setTimeoutHandler = setTimeoutHandler;
/**
* A helper for running delayed tasks following an exponential backoff curve
* between attempts.
*
* Each delay is made up of a "base" delay which follows the exponential
* backoff curve, and a "jitter" (+/- 50% by default) that is calculated and
* added to the base delay. This prevents clients from accidentally
* synchronizing their delays causing spikes of load to the backend.
*
* @private
*/
class ExponentialBackoff {
constructor(options = {}) {
/**
* The number of retries that has been attempted.
*
* @private
*/
this._retryCount = 0;
/**
* The backoff delay of the current attempt.
*
* @private
*/
this.currentBaseMs = 0;
/**
* Whether we are currently waiting for backoff to complete.
*
* @private
*/
this.awaitingBackoffCompletion = false;
this.initialDelayMs =
options.initialDelayMs !== undefined
? options.initialDelayMs
: DEFAULT_BACKOFF_INITIAL_DELAY_MS;
this.backoffFactor =
options.backoffFactor !== undefined
? options.backoffFactor
: DEFAULT_BACKOFF_FACTOR;
this.maxDelayMs =
options.maxDelayMs !== undefined
? options.maxDelayMs
: DEFAULT_BACKOFF_MAX_DELAY_MS;
this.jitterFactor =
options.jitterFactor !== undefined
? options.jitterFactor
: DEFAULT_JITTER_FACTOR;
}
/**
* Resets the backoff delay and retry count.
*
* The very next backoffAndWait() will have no delay. If it is called again
* (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
* subsequent ones will increase according to the backoffFactor.
*
* @private
*/
reset() {
this._retryCount = 0;
this.currentBaseMs = 0;
}
/**
* Resets the backoff delay to the maximum delay (e.g. for use after a
* RESOURCE_EXHAUSTED error).
*
* @private
*/
resetToMax() {
this.currentBaseMs = this.maxDelayMs;
}
/**
* Returns a promise that resolves after currentDelayMs, and increases the
* delay for any subsequent attempts.
*
* @return A Promise that resolves when the current delay elapsed.
* @private
*/
backoffAndWait() {
if (this.awaitingBackoffCompletion) {
return Promise.reject(new Error('A backoff operation is already in progress.'));
}
if (this.retryCount > exports.MAX_RETRY_ATTEMPTS) {
return Promise.reject(new Error('Exceeded maximum number of retries allowed.'));
}
// First schedule using the current base (which may be 0 and should be
// honored as such).
const delayWithJitterMs = this.currentBaseMs + this.jitterDelayMs();
if (this.currentBaseMs > 0) {
logger_1.logger('ExponentialBackoff.backoffAndWait', null, `Backing off for ${delayWithJitterMs} ms ` +
`(base delay: ${this.currentBaseMs} ms)`);
}
// Apply backoff factor to determine next delay and ensure it is within
// bounds.
this.currentBaseMs *= this.backoffFactor;
this.currentBaseMs = Math.max(this.currentBaseMs, this.initialDelayMs);
this.currentBaseMs = Math.min(this.currentBaseMs, this.maxDelayMs);
this._retryCount += 1;
return new Promise(resolve => {
this.awaitingBackoffCompletion = true;
delayExecution(() => {
this.awaitingBackoffCompletion = false;
resolve();
}, delayWithJitterMs);
});
}
// Visible for testing.
get retryCount() {
return this._retryCount;
}
/**
* Returns a randomized "jitter" delay based on the current base and jitter
* factor.
*
* @returns {number} The jitter to apply based on the current delay.
* @private
*/
jitterDelayMs() {
return (Math.random() - 0.5) * this.jitterFactor * this.currentBaseMs;
}
}
exports.ExponentialBackoff = ExponentialBackoff;
//# sourceMappingURL=backoff.js.map

View File

@ -0,0 +1,212 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/*!
* @module firestore/convert
* @private
*
* This module contains utility functions to convert
* `firestore.v1.Documents` from Proto3 JSON to their equivalent
* representation in Protobuf JS. Protobuf JS is the only encoding supported by
* this client, and dependencies that use Proto3 JSON (such as the Google Cloud
* Functions SDK) are supported through this conversion and its usage in
* {@see Firestore#snapshot_}.
*/
/**
* Converts an ISO 8601 or google.protobuf.Timestamp proto into Protobuf JS.
*
* @private
* @param timestampValue The value to convert.
* @param argumentName The argument name to use in the error message if the
* conversion fails. If omitted, 'timestampValue' is used.
* @return The value as expected by Protobuf JS or undefined if no input was
* provided.
*/
function timestampFromJson(timestampValue, argumentName) {
let timestampProto;
if (typeof timestampValue === 'string') {
const date = new Date(timestampValue);
const seconds = Math.floor(date.getTime() / 1000);
let nanos = 0;
if (timestampValue.length > 20) {
const nanoString = timestampValue.substring(20, timestampValue.length - 1);
const trailingZeroes = 9 - nanoString.length;
nanos = Number(nanoString) * Math.pow(10, trailingZeroes);
}
if (isNaN(seconds) || isNaN(nanos)) {
argumentName = argumentName || 'timestampValue';
throw new Error(`Specify a valid ISO 8601 timestamp for "${argumentName}".`);
}
timestampProto = {
seconds: seconds || undefined,
nanos: nanos || undefined,
};
}
else if (timestampValue !== undefined) {
validate_1.validateObject('timestampValue', timestampValue);
timestampProto = {
seconds: timestampValue.seconds || undefined,
nanos: timestampValue.nanos || undefined,
};
}
return timestampProto;
}
exports.timestampFromJson = timestampFromJson;
/**
* Converts a Proto3 JSON 'bytesValue' field into Protobuf JS.
*
* @private
* @param bytesValue The value to convert.
* @return The value as expected by Protobuf JS.
*/
function bytesFromJson(bytesValue) {
if (typeof bytesValue === 'string') {
return Buffer.from(bytesValue, 'base64');
}
else {
return bytesValue;
}
}
/**
* Detects 'valueType' from a Proto3 JSON `firestore.v1.Value` proto.
*
* @private
* @param proto The `firestore.v1.Value` proto.
* @return The string value for 'valueType'.
*/
function detectValueType(proto) {
if (proto.valueType) {
return proto.valueType;
}
const detectedValues = [];
if (proto.stringValue !== undefined) {
detectedValues.push('stringValue');
}
if (proto.booleanValue !== undefined) {
detectedValues.push('booleanValue');
}
if (proto.integerValue !== undefined) {
detectedValues.push('integerValue');
}
if (proto.doubleValue !== undefined) {
detectedValues.push('doubleValue');
}
if (proto.timestampValue !== undefined) {
detectedValues.push('timestampValue');
}
if (proto.referenceValue !== undefined) {
detectedValues.push('referenceValue');
}
if (proto.arrayValue !== undefined) {
detectedValues.push('arrayValue');
}
if (proto.nullValue !== undefined) {
detectedValues.push('nullValue');
}
if (proto.mapValue !== undefined) {
detectedValues.push('mapValue');
}
if (proto.geoPointValue !== undefined) {
detectedValues.push('geoPointValue');
}
if (proto.bytesValue !== undefined) {
detectedValues.push('bytesValue');
}
if (detectedValues.length !== 1) {
throw new Error(`Unable to infer type value fom '${JSON.stringify(proto)}'.`);
}
return detectedValues[0];
}
exports.detectValueType = detectValueType;
/**
* Converts a `firestore.v1.Value` in Proto3 JSON encoding into the
* Protobuf JS format expected by this client.
*
* @private
* @param fieldValue The `firestore.v1.Value` in Proto3 JSON format.
* @return The `firestore.v1.Value` in Protobuf JS format.
*/
function valueFromJson(fieldValue) {
const valueType = detectValueType(fieldValue);
switch (valueType) {
case 'timestampValue':
return {
timestampValue: timestampFromJson(fieldValue.timestampValue),
};
case 'bytesValue':
return {
bytesValue: bytesFromJson(fieldValue.bytesValue),
};
case 'integerValue':
return {
integerValue: Number(fieldValue.integerValue),
};
case 'doubleValue':
return {
doubleValue: Number(fieldValue.doubleValue),
};
case 'arrayValue': {
const arrayValue = [];
if (Array.isArray(fieldValue.arrayValue.values)) {
for (const value of fieldValue.arrayValue.values) {
arrayValue.push(valueFromJson(value));
}
}
return {
arrayValue: {
values: arrayValue,
},
};
}
case 'mapValue': {
const mapValue = {};
const fields = fieldValue.mapValue.fields;
if (fields) {
for (const prop of Object.keys(fields)) {
mapValue[prop] = valueFromJson(fieldValue.mapValue.fields[prop]);
}
}
return {
mapValue: {
fields: mapValue,
},
};
}
default:
return fieldValue;
}
}
exports.valueFromJson = valueFromJson;
/**
* Converts a map of IValues in Proto3 JSON encoding into the Protobuf JS format
* expected by this client. This conversion creates a copy of the underlying
* fields.
*
* @private
* @param document An object with IValues in Proto3 JSON format.
* @return The object in Protobuf JS format.
*/
function fieldsFromJson(document) {
const result = {};
for (const prop of Object.keys(document)) {
result[prop] = valueFromJson(document[prop]);
}
return result;
}
exports.fieldsFromJson = fieldsFromJson;
//# sourceMappingURL=convert.js.map

View File

@ -0,0 +1,166 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A DocumentChange represents a change to the documents matching a query.
* It contains the document affected and the type of change that occurred.
*
* @class
*/
class DocumentChange {
/**
* @hideconstructor
*
* @param {string} type 'added' | 'removed' | 'modified'.
* @param {QueryDocumentSnapshot} document The document.
* @param {number} oldIndex The index in the documents array prior to this
* change.
* @param {number} newIndex The index in the documents array after this
* change.
*/
constructor(type, document, oldIndex, newIndex) {
this._type = type;
this._document = document;
this._oldIndex = oldIndex;
this._newIndex = newIndex;
}
/**
* The type of change ('added', 'modified', or 'removed').
*
* @type {string}
* @name DocumentChange#type
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(`Type of change is ${change.type}`);
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get type() {
return this._type;
}
/**
* The document affected by this change.
*
* @type {QueryDocumentSnapshot}
* @name DocumentChange#doc
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* console.log(change.doc.data());
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get doc() {
return this._document;
}
/**
* The index of the changed document in the result set immediately prior to
* this DocumentChange (i.e. supposing that all prior DocumentChange objects
* have been applied). Is -1 for 'added' events.
*
* @type {number}
* @name DocumentChange#oldIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get oldIndex() {
return this._oldIndex;
}
/**
* The index of the changed document in the result set immediately after
* this DocumentChange (i.e. supposing that all prior DocumentChange
* objects and the current DocumentChange object have been applied).
* Is -1 for 'removed' events.
*
* @type {number}
* @name DocumentChange#newIndex
* @readonly
*
* @example
* let query = firestore.collection('col').where('foo', '==', 'bar');
* let docsArray = [];
*
* let unsubscribe = query.onSnapshot(querySnapshot => {
* for (let change of querySnapshot.docChanges) {
* if (change.oldIndex !== -1) {
* docsArray.splice(change.oldIndex, 1);
* }
* if (change.newIndex !== -1) {
* docsArray.splice(change.newIndex, 0, change.doc);
* }
* }
* });
*
* // Remove this listener.
* unsubscribe();
*/
get newIndex() {
return this._newIndex;
}
/**
* Returns true if the data in this `DocumentChange` is equal to the provided
* value.
*
* @param {*} other The value to compare against.
* @return true if this `DocumentChange` is equal to the provided value.
*/
isEqual(other) {
if (this === other) {
return true;
}
return (other instanceof DocumentChange &&
this._type === other._type &&
this._oldIndex === other._oldIndex &&
this._newIndex === other._newIndex &&
this._document.isEqual(other._document));
}
}
exports.DocumentChange = DocumentChange;
//# sourceMappingURL=document-change.js.map

View File

@ -0,0 +1,884 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const deepEqual = require('deep-equal');
const assert = require("assert");
const field_value_1 = require("./field-value");
const path_1 = require("./path");
const serializer_1 = require("./serializer");
const util_1 = require("./util");
/**
* Returns a builder for DocumentSnapshot and QueryDocumentSnapshot instances.
* Invoke `.build()' to assemble the final snapshot.
*
* @private
*/
class DocumentSnapshotBuilder {
/**
* Builds the DocumentSnapshot.
*
* @private
* @returns Returns either a QueryDocumentSnapshot (if `fieldsProto` was
* provided) or a DocumentSnapshot.
*/
build() {
assert((this.fieldsProto !== undefined) === (this.createTime !== undefined), 'Create time should be set iff document exists.');
assert((this.fieldsProto !== undefined) === (this.updateTime !== undefined), 'Update time should be set iff document exists.');
return this.fieldsProto
? new QueryDocumentSnapshot(this.ref, this.fieldsProto, this.readTime, this.createTime, this.updateTime)
: new DocumentSnapshot(this.ref, undefined, this.readTime);
}
}
exports.DocumentSnapshotBuilder = DocumentSnapshotBuilder;
/**
* A DocumentSnapshot is an immutable representation for a document in a
* Firestore database. The data can be extracted with
* [data()]{@link DocumentSnapshot#data} or
* [get(fieldPath)]{@link DocumentSnapshot#get} to get a
* specific field.
*
* <p>For a DocumentSnapshot that points to a non-existing document, any data
* access will return 'undefined'. You can use the
* [exists]{@link DocumentSnapshot#exists} property to explicitly verify a
* document's existence.
*
* @class
*/
class DocumentSnapshot {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document (or undefined if the document does not exist).
* @param readTime The time when this snapshot was read (or undefined if
* the document exists only locally).
* @param createTime The time when the document was created (or undefined if
* the document does not exist).
* @param updateTime The time when the document was last updated (or undefined
* if the document does not exist).
*/
constructor(ref, fieldsProto, readTime, createTime, updateTime) {
this._ref = ref;
this._fieldsProto = fieldsProto;
this._serializer = ref.firestore._serializer;
this._readTime = readTime;
this._createTime = createTime;
this._updateTime = updateTime;
}
/**
* Creates a DocumentSnapshot from an object.
*
* @private
* @param ref The reference to the document.
* @param obj The object to store in the DocumentSnapshot.
* @return The created DocumentSnapshot.
*/
static fromObject(ref, obj) {
const serializer = ref.firestore._serializer;
return new DocumentSnapshot(ref, serializer.encodeFields(obj));
}
/**
* Creates a DocumentSnapshot from an UpdateMap.
*
* This methods expands the top-level field paths in a JavaScript map and
* turns { foo.bar : foobar } into { foo { bar : foobar }}
*
* @private
* @param ref The reference to the document.
* @param data The field/value map to expand.
* @return The created DocumentSnapshot.
*/
static fromUpdateMap(ref, data) {
const serializer = ref.firestore._serializer;
/**
* Merges 'value' at the field path specified by the path array into
* 'target'.
*/
function merge(target, value, path, pos) {
const key = path[pos];
const isLast = pos === path.length - 1;
if (target[key] === undefined) {
if (isLast) {
if (value instanceof field_value_1.FieldTransform) {
// If there is already data at this path, we need to retain it.
// Otherwise, we don't include it in the DocumentSnapshot.
return !util_1.isEmpty(target) ? target : null;
}
// The merge is done.
const leafNode = serializer.encodeValue(value);
if (leafNode) {
target[key] = leafNode;
}
return target;
}
else {
// We need to expand the target object.
const childNode = {
mapValue: {
fields: {},
},
};
const nestedValue = merge(childNode.mapValue.fields, value, path, pos + 1);
if (nestedValue) {
childNode.mapValue.fields = nestedValue;
target[key] = childNode;
return target;
}
else {
return !util_1.isEmpty(target) ? target : null;
}
}
}
else {
assert(!isLast, "Can't merge current value into a nested object");
target[key].mapValue.fields = merge(target[key].mapValue.fields, value, path, pos + 1);
return target;
}
}
const res = {};
for (const [key, value] of data) {
const path = key.toArray();
merge(res, value, path, 0);
}
return new DocumentSnapshot(ref, res);
}
/**
* True if the document exists.
*
* @type {boolean}
* @name DocumentSnapshot#exists
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Data: ${JSON.stringify(documentSnapshot.data())}`);
* }
* });
*/
get exists() {
return this._fieldsProto !== undefined;
}
/**
* A [DocumentReference]{@link DocumentReference} for the document
* stored in this snapshot.
*
* @type {DocumentReference}
* @name DocumentSnapshot#ref
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Found document at '${documentSnapshot.ref.path}'`);
* }
* });
*/
get ref() {
return this._ref;
}
/**
* The ID of the document for which this DocumentSnapshot contains data.
*
* @type {string}
* @name DocumentSnapshot#id
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then((documentSnapshot) => {
* if (documentSnapshot.exists) {
* console.log(`Document found with name '${documentSnapshot.id}'`);
* }
* });
*/
get id() {
return this._ref.id;
}
/**
* The time the document was created. Undefined for documents that don't
* exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#createTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let createTime = documentSnapshot.createTime;
* console.log(`Document created at '${createTime.toDate()}'`);
* }
* });
*/
get createTime() {
return this._createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated). Undefined for documents that don't exist.
*
* @type {Timestamp|undefined}
* @name DocumentSnapshot#updateTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* if (documentSnapshot.exists) {
* let updateTime = documentSnapshot.updateTime;
* console.log(`Document updated at '${updateTime.toDate()}'`);
* }
* });
*/
get updateTime() {
return this._updateTime;
}
/**
* The time this snapshot was read.
*
* @type {Timestamp}
* @name DocumentSnapshot#readTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let readTime = documentSnapshot.readTime;
* console.log(`Document read at '${readTime.toDate()}'`);
* });
*/
get readTime() {
if (this._readTime === undefined) {
throw new Error(`Called 'readTime' on a local document`);
}
return this._readTime;
}
/**
* Retrieves all fields in the document as an object. Returns 'undefined' if
* the document doesn't exist.
*
* @returns {DocumentData|undefined} An object containing all fields in the
* document or 'undefined' if the document doesn't exist.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// tslint:disable-next-line no-any
data() {
// tslint:disable-line no-any
const fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const obj = {};
for (const prop of Object.keys(fields)) {
obj[prop] = this._serializer.decodeValue(fields[prop]);
}
return obj;
}
/**
* Retrieves the field specified by `field`.
*
* @param {string|FieldPath} field The field path
* (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns {*} The data at the specified field location or undefined if no
* such field exists.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ a: { b: 'c' }}).then(() => {
* return documentRef.get();
* }).then(documentSnapshot => {
* let field = documentSnapshot.get('a.b');
* console.log(`Retrieved field value: ${field}`);
* });
*/
// We deliberately use `any` in the external API to not impose type-checking
// on end users.
// tslint:disable-next-line no-any
get(field) {
// tslint:disable-line no-any
path_1.validateFieldPath('field', field);
const protoField = this.protoField(field);
if (protoField === undefined) {
return undefined;
}
return this._serializer.decodeValue(protoField);
}
/**
* Retrieves the field specified by 'fieldPath' in its Protobuf JS
* representation.
*
* @private
* @param field The path (e.g. 'foo' or 'foo.bar') to a specific field.
* @returns The Protobuf-encoded data at the specified field location or
* undefined if no such field exists.
*/
protoField(field) {
let fields = this._fieldsProto;
if (fields === undefined) {
return undefined;
}
const components = path_1.FieldPath.fromArgument(field).toArray();
while (components.length > 1) {
fields = fields[components.shift()];
if (!fields || !fields.mapValue) {
return undefined;
}
fields = fields.mapValue.fields;
}
return fields[components[0]];
}
/**
* Checks whether this DocumentSnapshot contains any fields.
*
* @private
* @return {boolean}
*/
get isEmpty() {
return this._fieldsProto === undefined || util_1.isEmpty(this._fieldsProto);
}
/**
* Convert a document snapshot to the Firestore 'Document' Protobuf.
*
* @private
* @returns The document in the format the API expects.
*/
toProto() {
return {
update: {
name: this._ref.formattedName,
fields: this._fieldsProto,
},
};
}
/**
* Returns true if the document's data and path in this `DocumentSnapshot` is
* equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `DocumentSnapshot` is equal to the provided
* value.
*/
isEqual(other) {
// Since the read time is different on every document read, we explicitly
// ignore all document metadata in this comparison.
return (this === other ||
(other instanceof DocumentSnapshot &&
this._ref.isEqual(other._ref) &&
deepEqual(this._fieldsProto, other._fieldsProto, { strict: true })));
}
}
exports.DocumentSnapshot = DocumentSnapshot;
/**
* A QueryDocumentSnapshot contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with [data()]{@link QueryDocumentSnapshot#data}
* or [get()]{@link DocumentSnapshot#get} to get a specific field.
*
* A QueryDocumentSnapshot offers the same API surface as a
* {@link DocumentSnapshot}. Since query results contain only existing
* documents, the [exists]{@link DocumentSnapshot#exists} property will
* always be true and [data()]{@link QueryDocumentSnapshot#data} will never
* return 'undefined'.
*
* @class
* @extends DocumentSnapshot
*/
class QueryDocumentSnapshot extends DocumentSnapshot {
/**
* @hideconstructor
*
* @param ref The reference to the document.
* @param fieldsProto The fields of the Firestore `Document` Protobuf backing
* this document.
* @param readTime The time when this snapshot was read.
* @param createTime The time when the document was created.
* @param updateTime The time when the document was last updated.
*/
constructor(ref, fieldsProto, readTime, createTime, updateTime) {
super(ref, fieldsProto, readTime, createTime, updateTime);
}
/**
* The time the document was created.
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#createTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document created at '${snapshot.createTime.toDate()}'`);
* });
*/
get createTime() {
return super.createTime;
}
/**
* The time the document was last updated (at the time the snapshot was
* generated).
*
* @type {Timestamp}
* @name QueryDocumentSnapshot#updateTime
* @readonly
* @override
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(snapshot => {
* console.log(`Document updated at '${snapshot.updateTime.toDate()}'`);
* });
*/
get updateTime() {
return super.updateTime;
}
/**
* Retrieves all fields in the document as an object.
*
* @override
*
* @returns {DocumentData} An object containing all fields in the document.
*
* @example
* let query = firestore.collection('col');
*
* query.get().forEach(documentSnapshot => {
* let data = documentSnapshot.data();
* console.log(`Retrieved data: ${JSON.stringify(data)}`);
* });
*/
data() {
const data = super.data();
if (!data) {
throw new Error('The data in a QueryDocumentSnapshot should always exist.');
}
return data;
}
}
exports.QueryDocumentSnapshot = QueryDocumentSnapshot;
/**
* A Firestore Document Mask contains the field paths affected by an update.
*
* @class
* @private
*/
class DocumentMask {
/**
* @private
* @hideconstructor
*
* @param fieldPaths The field paths in this mask.
*/
constructor(fieldPaths) {
this._sortedPaths = fieldPaths;
this._sortedPaths.sort((a, b) => a.compareTo(b));
}
/**
* Creates a document mask with the field paths of a document.
*
* @private
* @param data A map with fields to modify. Only the keys are used to extract
* the document mask.
*/
static fromUpdateMap(data) {
const fieldPaths = [];
data.forEach((value, key) => {
if (!(value instanceof field_value_1.FieldTransform) || value.includeInDocumentMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(key));
}
});
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask from an array of field paths.
*
* @private
* @param fieldMask A list of field paths.
*/
static fromFieldMask(fieldMask) {
const fieldPaths = [];
for (const fieldPath of fieldMask) {
fieldPaths.push(path_1.FieldPath.fromArgument(fieldPath));
}
return new DocumentMask(fieldPaths);
}
/**
* Creates a document mask with the field names of a document.
*
* @private
* @param data An object with fields to modify. Only the keys are used to
* extract the document mask.
*/
static fromObject(data) {
const fieldPaths = [];
function extractFieldPaths(currentData, currentPath) {
let isEmpty = true;
for (const key of Object.keys(currentData)) {
isEmpty = false;
// We don't split on dots since fromObject is called with
// DocumentData.
const childSegment = new path_1.FieldPath(key);
const childPath = currentPath
? currentPath.append(childSegment)
: childSegment;
const value = currentData[key];
if (value instanceof field_value_1.FieldTransform) {
if (value.includeInDocumentMask) {
fieldPaths.push(childPath);
}
}
else if (serializer_1.isPlainObject(value)) {
extractFieldPaths(value, childPath);
}
else {
fieldPaths.push(childPath);
}
}
// Add a field path for an explicitly updated empty map.
if (currentPath && isEmpty) {
fieldPaths.push(currentPath);
}
}
extractFieldPaths(data);
return new DocumentMask(fieldPaths);
}
/**
* Returns true if this document mask contains no fields.
*
* @private
* @return {boolean} Whether this document mask is empty.
*/
get isEmpty() {
return this._sortedPaths.length === 0;
}
/**
* Removes the specified values from a sorted field path array.
*
* @private
* @param input A sorted array of FieldPaths.
* @param values An array of FieldPaths to remove.
*/
static removeFromSortedArray(input, values) {
for (let i = 0; i < input.length;) {
let removed = false;
for (const fieldPath of values) {
if (input[i].isEqual(fieldPath)) {
input.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
++i;
}
}
}
/**
* Removes the field path specified in 'fieldPaths' from this document mask.
*
* @private
* @param fieldPaths An array of FieldPaths.
*/
removeFields(fieldPaths) {
DocumentMask.removeFromSortedArray(this._sortedPaths, fieldPaths);
}
/**
* Returns whether this document mask contains 'fieldPath'.
*
* @private
* @param fieldPath The field path to test.
* @return Whether this document mask contains 'fieldPath'.
*/
contains(fieldPath) {
for (const sortedPath of this._sortedPaths) {
const cmp = sortedPath.compareTo(fieldPath);
if (cmp === 0) {
return true;
}
else if (cmp > 0) {
return false;
}
}
return false;
}
/**
* Removes all properties from 'data' that are not contained in this document
* mask.
*
* @private
* @param data An object to filter.
* @return A shallow copy of the object filtered by this document mask.
*/
applyTo(data) {
/*!
* Applies this DocumentMask to 'data' and computes the list of field paths
* that were specified in the mask but are not present in 'data'.
*/
const applyDocumentMask = (data) => {
const remainingPaths = this._sortedPaths.slice(0);
const processObject = (currentData, currentPath) => {
let result = null;
Object.keys(currentData).forEach(key => {
const childPath = currentPath
? currentPath.append(key)
: new path_1.FieldPath(key);
if (this.contains(childPath)) {
DocumentMask.removeFromSortedArray(remainingPaths, [childPath]);
result = result || {};
result[key] = currentData[key];
}
else if (util_1.isObject(currentData[key])) {
const childObject = processObject(currentData[key], childPath);
if (childObject) {
result = result || {};
result[key] = childObject;
}
}
});
return result;
};
// processObject() returns 'null' if the DocumentMask is empty.
const filteredData = processObject(data) || {};
return {
filteredData,
remainingPaths,
};
};
const result = applyDocumentMask(data);
if (result.remainingPaths.length !== 0) {
throw new Error(`Input data is missing for field "${result.remainingPaths[0]}".`);
}
return result.filteredData;
}
/**
* Converts a document mask to the Firestore 'DocumentMask' Proto.
*
* @private
* @returns A Firestore 'DocumentMask' Proto.
*/
toProto() {
if (this.isEmpty) {
return {};
}
const encodedPaths = [];
for (const fieldPath of this._sortedPaths) {
encodedPaths.push(fieldPath.formattedName);
}
return {
fieldPaths: encodedPaths,
};
}
}
exports.DocumentMask = DocumentMask;
/**
* A Firestore Document Transform.
*
* A DocumentTransform contains pending server-side transforms and their
* corresponding field paths.
*
* @private
* @class
*/
class DocumentTransform {
/**
* @private
* @hideconstructor
*
* @param ref The DocumentReference for this transform.
* @param transforms A Map of FieldPaths to FieldTransforms.
*/
constructor(ref, transforms) {
this.ref = ref;
this.transforms = transforms;
}
/**
* Generates a DocumentTransform from a JavaScript object.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param obj The object to extract the transformations from.
* @returns The Document Transform.
*/
static fromObject(ref, obj) {
const updateMap = new Map();
for (const prop of Object.keys(obj)) {
updateMap.set(new path_1.FieldPath(prop), obj[prop]);
}
return DocumentTransform.fromUpdateMap(ref, updateMap);
}
/**
* Generates a DocumentTransform from an Update Map.
*
* @private
* @param ref The `DocumentReference` to use for the DocumentTransform.
* @param data The update data to extract the transformations from.
* @returns The Document Transform.
*/
static fromUpdateMap(ref, data) {
const transforms = new Map();
function encode_(val, path, allowTransforms) {
if (val instanceof field_value_1.FieldTransform && val.includeInDocumentTransform) {
if (allowTransforms) {
transforms.set(path, val);
}
else {
throw new Error(`${val.methodName}() is not supported inside of array values.`);
}
}
else if (Array.isArray(val)) {
for (let i = 0; i < val.length; ++i) {
// We need to verify that no array value contains a document transform
encode_(val[i], path.append(String(i)), false);
}
}
else if (serializer_1.isPlainObject(val)) {
for (const prop of Object.keys(val)) {
encode_(val[prop], path.append(new path_1.FieldPath(prop)), allowTransforms);
}
}
}
data.forEach((value, key) => {
encode_(value, path_1.FieldPath.fromArgument(key), true);
});
return new DocumentTransform(ref, transforms);
}
/**
* Whether this DocumentTransform contains any actionable transformations.
*
* @private
*/
get isEmpty() {
return this.transforms.size === 0;
}
/**
* Returns the array of fields in this DocumentTransform.
*
* @private
*/
get fields() {
return Array.from(this.transforms.keys());
}
/**
* Validates the user provided field values in this document transform.
* @private
*/
validate() {
this.transforms.forEach(transform => transform.validate());
}
/**
* Converts a document transform to the Firestore 'DocumentTransform' Proto.
*
* @private
* @param serializer The Firestore serializer
* @returns A Firestore 'DocumentTransform' Proto or 'null' if this transform
* is empty.
*/
toProto(serializer) {
if (this.isEmpty) {
return null;
}
const fieldTransforms = [];
for (const [path, transform] of this.transforms) {
fieldTransforms.push(transform.toProto(serializer, path));
}
return {
transform: {
document: this.ref.formattedName,
fieldTransforms,
},
};
}
}
exports.DocumentTransform = DocumentTransform;
/**
* A Firestore Precondition encapsulates options for database writes.
*
* @private
* @class
*/
class Precondition {
/**
* @private
* @hideconstructor
*
* @param options.exists - Whether the referenced document should exist in
* Firestore,
* @param options.lastUpdateTime - The last update time of the referenced
* document in Firestore.
* @param options
*/
constructor(options) {
if (options !== undefined) {
this._exists = options.exists;
this._lastUpdateTime = options.lastUpdateTime;
}
}
/**
* Generates the Protobuf `Preconditon` object for this precondition.
*
* @private
* @returns The `Preconditon` Protobuf object or 'null' if there are no
* preconditions.
*/
toProto() {
if (this.isEmpty) {
return null;
}
const proto = {};
if (this._lastUpdateTime !== undefined) {
const valueProto = this._lastUpdateTime.toProto();
proto.updateTime = valueProto.timestampValue;
}
else {
proto.exists = this._exists;
}
return proto;
}
/**
* Whether this DocumentTransform contains any enforcement.
*
* @private
*/
get isEmpty() {
return this._exists === undefined && !this._lastUpdateTime;
}
}
exports.Precondition = Precondition;
//# sourceMappingURL=document.js.map

View File

@ -0,0 +1,429 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const deepEqual = require('deep-equal');
const serializer_1 = require("./serializer");
const validate_1 = require("./validate");
/**
* Sentinel values that can be used when writing documents with set(), create()
* or update().
*
* @class
*/
class FieldValue {
/**
* @hideconstructor
*/
constructor() { }
/**
* Returns a sentinel for use with update() or set() with {merge:true} to mark
* a field for deletion.
*
* @returns {FieldValue} The sentinel value to use in your objects.
*
* @example
* let documentRef = firestore.doc('col/doc');
* let data = { a: 'b', c: 'd' };
*
* documentRef.set(data).then(() => {
* return documentRef.update({a: Firestore.FieldValue.delete()});
* }).then(() => {
* // Document now only contains { c: 'd' }
* });
*/
static delete() {
return DeleteTransform.DELETE_SENTINEL;
}
/**
* Returns a sentinel used with set(), create() or update() to include a
* server-generated timestamp in the written data.
*
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({
* time: Firestore.FieldValue.serverTimestamp()
* }).then(() => {
* return documentRef.get();
* }).then(doc => {
* console.log(`Server time set to ${doc.get('time')}`);
* });
*/
static serverTimestamp() {
return ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL;
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to increment the the field's current value by the
* given value.
*
* If either current field value or the operand uses floating point
* precision, both values will be interpreted as floating point numbers and
* all arithmetic will follow IEEE 754 semantics. Otherwise, integer
* precision is kept and the result is capped between -2^63 and 2^63-1.
*
* If the current field value is not of type 'number', or if the field does
* not yet exist, the transformation will set the field to the given value.
*
* @param {number} n The value to increment by.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'counter', Firestore.FieldValue.increment(1)
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('counter') was incremented
* });
*/
static increment(n) {
validate_1.validateMinNumberOfArguments('FieldValue.increment', arguments, 1);
return new NumericIncrementTransform(n);
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to union the given elements with any array value that
* already exists on the server. Each specified element that doesn't already
* exist in the array will be added to the end. If the field being modified is
* not already an array it will be overwritten with an array containing
* exactly the specified elements.
*
* @param {...*} elements The elements to union into the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayUnion('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') contains field 'foo'
* });
*/
static arrayUnion(...elements) {
validate_1.validateMinNumberOfArguments('FieldValue.arrayUnion', arguments, 1);
return new ArrayUnionTransform(elements);
}
/**
* Returns a special value that can be used with set(), create() or update()
* that tells the server to remove the given elements from any array value
* that already exists on the server. All instances of each element specified
* will be removed from the array. If the field being modified is not already
* an array it will be overwritten with an empty array.
*
* @param {...*} elements The elements to remove from the array.
* @return {FieldValue} The FieldValue sentinel for use in a call to set(),
* create() or update().
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.update(
* 'array', Firestore.FieldValue.arrayRemove('foo')
* ).then(() => {
* return documentRef.get();
* }).then(doc => {
* // doc.get('array') no longer contains field 'foo'
* });
*/
static arrayRemove(...elements) {
validate_1.validateMinNumberOfArguments('FieldValue.arrayRemove', arguments, 1);
return new ArrayRemoveTransform(elements);
}
/**
* Returns true if this `FieldValue` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldValue` is equal to the provided value.
*
* @example
* let fieldValues = [
* Firestore.FieldValue.increment(-1.0),
* Firestore.FieldValue.increment(-1),
* Firestore.FieldValue.increment(-0.0),
* Firestore.FieldValue.increment(-0),
* Firestore.FieldValue.increment(0),
* Firestore.FieldValue.increment(0.0),
* Firestore.FieldValue.increment(1),
* Firestore.FieldValue.increment(1.0)
* ];
*
* let equal = 0;
* for (let i = 0; i < fieldValues.length; ++i) {
* for (let j = i + 1; j < fieldValues.length; ++j) {
* if (fieldValues[i].isEqual(fieldValues[j])) {
* ++equal;
* }
* }
* }
* console.log(`Found ${equal} equalities.`);
*/
isEqual(other) {
return this === other;
}
}
exports.FieldValue = FieldValue;
/**
* An internal interface shared by all field transforms.
*
* A 'FieldTransform` subclass should implement '.includeInDocumentMask',
* '.includeInDocumentTransform' and 'toProto' (if '.includeInDocumentTransform'
* is 'true').
*
* @private
* @abstract
*/
class FieldTransform extends FieldValue {
}
exports.FieldTransform = FieldTransform;
/**
* A transform that deletes a field from a Firestore document.
*
* @private
*/
class DeleteTransform extends FieldTransform {
constructor() {
super();
}
/**
* Deletes are included in document masks.
* @private
*/
get includeInDocumentMask() {
return true;
}
/**
* Deletes are are omitted from document transforms.
* @private
*/
get includeInDocumentTransform() {
return false;
}
get methodName() {
return 'FieldValue.delete';
}
validate() { }
toProto(serializer, fieldPath) {
throw new Error('FieldValue.delete() should not be included in a FieldTransform');
}
}
exports.DeleteTransform = DeleteTransform;
/**
* Sentinel value for a field delete.
* @private
*/
DeleteTransform.DELETE_SENTINEL = new DeleteTransform();
/**
* A transform that sets a field to the Firestore server time.
*
* @private
*/
class ServerTimestampTransform extends FieldTransform {
constructor() {
super();
}
/**
* Server timestamps are omitted from document masks.
*
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Server timestamps are included in document transforms.
*
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.serverTimestamp';
}
validate() { }
toProto(serializer, fieldPath) {
return {
fieldPath: fieldPath.formattedName,
setToServerValue: 'REQUEST_TIME',
};
}
}
/**
* Sentinel value for a server timestamp.
*
* @private
*/
ServerTimestampTransform.SERVER_TIMESTAMP_SENTINEL = new ServerTimestampTransform();
/**
* Increments a field value on the backend.
*
* @private
*/
class NumericIncrementTransform extends FieldTransform {
constructor(operand) {
super();
this.operand = operand;
}
/**
* Numeric transforms are omitted from document masks.
*
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Numeric transforms are included in document transforms.
*
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.increment';
}
validate() {
validate_1.validateNumber('FieldValue.increment()', this.operand);
}
toProto(serializer, fieldPath) {
const encodedOperand = serializer.encodeValue(this.operand);
return { fieldPath: fieldPath.formattedName, increment: encodedOperand };
}
isEqual(other) {
return (this === other ||
(other instanceof NumericIncrementTransform &&
this.operand === other.operand));
}
}
/**
* Transforms an array value via a union operation.
*
* @private
*/
class ArrayUnionTransform extends FieldTransform {
constructor(elements) {
super();
this.elements = elements;
}
/**
* Array transforms are omitted from document masks.
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Array transforms are included in document transforms.
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.arrayUnion';
}
validate() {
for (let i = 0; i < this.elements.length; ++i) {
validateArrayElement(i, this.elements[i]);
}
}
toProto(serializer, fieldPath) {
const encodedElements = serializer.encodeValue(this.elements).arrayValue;
return {
fieldPath: fieldPath.formattedName,
appendMissingElements: encodedElements,
};
}
isEqual(other) {
return (this === other ||
(other instanceof ArrayUnionTransform &&
deepEqual(this.elements, other.elements, { strict: true })));
}
}
/**
* Transforms an array value via a remove operation.
*
* @private
*/
class ArrayRemoveTransform extends FieldTransform {
constructor(elements) {
super();
this.elements = elements;
}
/**
* Array transforms are omitted from document masks.
* @private
*/
get includeInDocumentMask() {
return false;
}
/**
* Array transforms are included in document transforms.
* @private
*/
get includeInDocumentTransform() {
return true;
}
get methodName() {
return 'FieldValue.arrayRemove';
}
validate() {
for (let i = 0; i < this.elements.length; ++i) {
validateArrayElement(i, this.elements[i]);
}
}
toProto(serializer, fieldPath) {
const encodedElements = serializer.encodeValue(this.elements).arrayValue;
return {
fieldPath: fieldPath.formattedName,
removeAllFromArray: encodedElements,
};
}
isEqual(other) {
return (this === other ||
(other instanceof ArrayRemoveTransform &&
deepEqual(this.elements, other.elements, { strict: true })));
}
}
/**
* Validates that `value` can be used as an element inside of an array. Certain
* field values (such as ServerTimestamps) are rejected.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The value to validate.
*/
function validateArrayElement(arg, value) {
serializer_1.validateUserInput(arg, value, 'array element',
/*path=*/ { allowDeletes: 'none', allowTransforms: false },
/*path=*/ undefined,
/*level=*/ 0,
/*inArray=*/ true);
}
//# sourceMappingURL=field-value.js.map

View File

@ -0,0 +1,101 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/**
* An immutable object representing a geographic location in Firestore. The
* location is represented as a latitude/longitude pair.
*
* @class
*/
class GeoPoint {
/**
* Creates a [GeoPoint]{@link GeoPoint}.
*
* @param {number} latitude The latitude as a number between -90 and 90.
* @param {number} longitude The longitude as a number between -180 and 180.
*
* @example
* let data = {
* google: new Firestore.GeoPoint(37.422, 122.084)
* };
*
* firestore.doc('col/doc').set(data).then(() => {
* console.log(`Location is ${data.google.latitude}, ` +
* `${data.google.longitude}`);
* });
*/
constructor(latitude, longitude) {
validate_1.validateNumber('latitude', latitude, { minValue: -90, maxValue: 90 });
validate_1.validateNumber('longitude', longitude, { minValue: -180, maxValue: 180 });
this._latitude = latitude;
this._longitude = longitude;
}
/**
* The latitude as a number between -90 and 90.
*
* @type {number}
* @name GeoPoint#latitude
* @readonly
*/
get latitude() {
return this._latitude;
}
/**
* The longitude as a number between -180 and 180.
*
* @type {number}
* @name GeoPoint#longitude
* @readonly
*/
get longitude() {
return this._longitude;
}
/**
* Returns true if this `GeoPoint` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `GeoPoint` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof GeoPoint &&
this.latitude === other.latitude &&
this.longitude === other.longitude));
}
/**
* Converts the GeoPoint to a google.type.LatLng proto.
* @private
*/
toProto() {
return {
geoPointValue: {
latitude: this.latitude,
longitude: this.longitude,
},
};
}
/**
* Converts a google.type.LatLng proto to its GeoPoint representation.
* @private
*/
static fromProto(proto) {
return new GeoPoint(proto.latitude || 0, proto.longitude || 0);
}
}
exports.GeoPoint = GeoPoint;
//# sourceMappingURL=geo-point.js.map

1159
node_modules/@google-cloud/firestore/build/src/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,55 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const util = require("util");
const validate_1 = require("./validate");
/*! The Firestore library version */
let libVersion;
/*! The external function used to emit logs. */
let logFunction = (msg) => { };
/**
* Log function to use for debug output. By default, we don't perform any
* logging.
*
* @private
*/
function logger(methodName, requestTag, logMessage, ...additionalArgs) {
requestTag = requestTag || '#####';
const formattedMessage = util.format(logMessage, ...additionalArgs);
const time = new Date().toISOString();
logFunction(`Firestore (${libVersion}) ${time} ${requestTag} [${methodName}]: ` +
formattedMessage);
}
exports.logger = logger;
/**
* Sets the log function for all active Firestore instances.
*/
function setLogFunction(logger) {
validate_1.validateFunction('logger', logger);
logFunction = logger;
}
exports.setLogFunction = setLogFunction;
/**
* Sets the log function for all active Firestore instances.
*
* @private
*/
function setLibVersion(version) {
libVersion = version;
}
exports.setLibVersion = setLibVersion;
//# sourceMappingURL=logger.js.map

230
node_modules/@google-cloud/firestore/build/src/order.js generated vendored Normal file
View File

@ -0,0 +1,230 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const convert_1 = require("./convert");
const path_1 = require("./path");
/*!
* The type order as defined by the backend.
*/
var TypeOrder;
(function (TypeOrder) {
TypeOrder[TypeOrder["NULL"] = 0] = "NULL";
TypeOrder[TypeOrder["BOOLEAN"] = 1] = "BOOLEAN";
TypeOrder[TypeOrder["NUMBER"] = 2] = "NUMBER";
TypeOrder[TypeOrder["TIMESTAMP"] = 3] = "TIMESTAMP";
TypeOrder[TypeOrder["STRING"] = 4] = "STRING";
TypeOrder[TypeOrder["BLOB"] = 5] = "BLOB";
TypeOrder[TypeOrder["REF"] = 6] = "REF";
TypeOrder[TypeOrder["GEO_POINT"] = 7] = "GEO_POINT";
TypeOrder[TypeOrder["ARRAY"] = 8] = "ARRAY";
TypeOrder[TypeOrder["OBJECT"] = 9] = "OBJECT";
})(TypeOrder || (TypeOrder = {}));
/*!
* @private
*/
function typeOrder(val) {
const valueType = convert_1.detectValueType(val);
switch (valueType) {
case 'nullValue':
return TypeOrder.NULL;
case 'integerValue':
return TypeOrder.NUMBER;
case 'doubleValue':
return TypeOrder.NUMBER;
case 'stringValue':
return TypeOrder.STRING;
case 'booleanValue':
return TypeOrder.BOOLEAN;
case 'arrayValue':
return TypeOrder.ARRAY;
case 'timestampValue':
return TypeOrder.TIMESTAMP;
case 'geoPointValue':
return TypeOrder.GEO_POINT;
case 'bytesValue':
return TypeOrder.BLOB;
case 'referenceValue':
return TypeOrder.REF;
case 'mapValue':
return TypeOrder.OBJECT;
default:
throw new Error('Unexpected value type: ' + valueType);
}
}
/*!
* @private
*/
function primitiveComparator(left, right) {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
return 0;
}
exports.primitiveComparator = primitiveComparator;
/*!
* Utility function to compare doubles (using Firestore semantics for NaN).
* @private
*/
function compareNumbers(left, right) {
if (left < right) {
return -1;
}
if (left > right) {
return 1;
}
if (left === right) {
return 0;
}
// one or both are NaN.
if (isNaN(left)) {
return isNaN(right) ? 0 : -1;
}
return 1;
}
/*!
* @private
*/
function compareNumberProtos(left, right) {
let leftValue, rightValue;
if (left.integerValue !== undefined) {
leftValue = Number(left.integerValue);
}
else {
leftValue = Number(left.doubleValue);
}
if (right.integerValue !== undefined) {
rightValue = Number(right.integerValue);
}
else {
rightValue = Number(right.doubleValue);
}
return compareNumbers(leftValue, rightValue);
}
/*!
* @private
*/
function compareTimestamps(left, right) {
const seconds = primitiveComparator(left.seconds || 0, right.seconds || 0);
if (seconds !== 0) {
return seconds;
}
return primitiveComparator(left.nanos || 0, right.nanos || 0);
}
/*!
* @private
*/
function compareBlobs(left, right) {
if (!(left instanceof Buffer) || !(right instanceof Buffer)) {
throw new Error('Blobs can only be compared if they are Buffers.');
}
return Buffer.compare(left, right);
}
/*!
* @private
*/
function compareReferenceProtos(left, right) {
const leftPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(left.referenceValue);
const rightPath = path_1.QualifiedResourcePath.fromSlashSeparatedString(right.referenceValue);
return leftPath.compareTo(rightPath);
}
/*!
* @private
*/
function compareGeoPoints(left, right) {
return (primitiveComparator(left.latitude || 0, right.latitude || 0) ||
primitiveComparator(left.longitude || 0, right.longitude || 0));
}
/*!
* @private
*/
function compareArrays(left, right) {
for (let i = 0; i < left.length && i < right.length; i++) {
const valueComparison = compare(left[i], right[i]);
if (valueComparison !== 0) {
return valueComparison;
}
}
// If all the values matched so far, just check the length.
return primitiveComparator(left.length, right.length);
}
/*!
* @private
*/
function compareObjects(left, right) {
// This requires iterating over the keys in the object in order and doing a
// deep comparison.
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
leftKeys.sort();
rightKeys.sort();
for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {
const keyComparison = primitiveComparator(leftKeys[i], rightKeys[i]);
if (keyComparison !== 0) {
return keyComparison;
}
const key = leftKeys[i];
const valueComparison = compare(left[key], right[key]);
if (valueComparison !== 0) {
return valueComparison;
}
}
// If all the keys matched so far, just check the length.
return primitiveComparator(leftKeys.length, rightKeys.length);
}
/*!
* @private
*/
function compare(left, right) {
// First compare the types.
const leftType = typeOrder(left);
const rightType = typeOrder(right);
const typeComparison = primitiveComparator(leftType, rightType);
if (typeComparison !== 0) {
return typeComparison;
}
// So they are the same type.
switch (leftType) {
case TypeOrder.NULL:
// Nulls are all equal.
return 0;
case TypeOrder.BOOLEAN:
return primitiveComparator(left.booleanValue, right.booleanValue);
case TypeOrder.STRING:
return primitiveComparator(left.stringValue, right.stringValue);
case TypeOrder.NUMBER:
return compareNumberProtos(left, right);
case TypeOrder.TIMESTAMP:
return compareTimestamps(left.timestampValue, right.timestampValue);
case TypeOrder.BLOB:
return compareBlobs(left.bytesValue, right.bytesValue);
case TypeOrder.REF:
return compareReferenceProtos(left, right);
case TypeOrder.GEO_POINT:
return compareGeoPoints(left.geoPointValue, right.geoPointValue);
case TypeOrder.ARRAY:
return compareArrays(left.arrayValue.values || [], right.arrayValue.values || []);
case TypeOrder.OBJECT:
return compareObjects(left.mapValue.fields || {}, right.mapValue.fields || {});
default:
throw new Error(`Encountered unknown type order: ${leftType}`);
}
}
exports.compare = compare;
//# sourceMappingURL=order.js.map

573
node_modules/@google-cloud/firestore/build/src/path.js generated vendored Normal file
View File

@ -0,0 +1,573 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* The default database ID for this Firestore client. We do not yet expose the
* ability to use different databases.
*/
exports.DEFAULT_DATABASE_ID = '(default)';
/*!
* A regular expression to verify an absolute Resource Path in Firestore. It
* extracts the project ID, the database name and the relative resource path
* if available.
*
* @type {RegExp}
*/
const RESOURCE_PATH_RE =
// Note: [\s\S] matches all characters including newlines.
/^projects\/([^/]*)\/databases\/([^/]*)(?:\/documents\/)?([\s\S]*)$/;
/*!
* A regular expression to verify whether a field name can be passed to the
* backend without escaping.
*
* @type {RegExp}
*/
const UNESCAPED_FIELD_NAME_RE = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
/*!
* A regular expression to verify field paths that are passed to the API as
* strings. Field paths that do not match this expression have to be provided
* as a [FieldPath]{@link FieldPath} object.
*
* @type {RegExp}
*/
const FIELD_PATH_RE = /^[^*~/[\]]+$/;
/**
* An abstract class representing a Firestore path.
*
* Subclasses have to implement `split()` and `canonicalString()`.
*
* @private
* @class
*/
class Path {
/**
* Creates a new Path with the given segments.
*
* @private
* @hideconstructor
* @param segments Sequence of parts of a path.
*/
constructor(segments) {
this.segments = segments;
}
/**
* Returns the number of segments of this field path.
*
* @private
*/
get size() {
return this.segments.length;
}
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath) {
if (relativePath instanceof Path) {
return this.construct(this.segments.concat(relativePath.segments));
}
return this.construct(this.segments.concat(this.split(relativePath)));
}
/**
* Returns the path of the parent node.
*
* @private
* @returns The new path or null if we are already at the root.
*/
parent() {
if (this.segments.length === 0) {
return null;
}
return this.construct(this.segments.slice(0, this.segments.length - 1));
}
/**
* Checks whether the current path is a prefix of the specified path.
*
* @private
* @param other The path to check against.
* @returns 'true' iff the current path is a prefix match with 'other'.
*/
isPrefixOf(other) {
if (other.segments.length < this.segments.length) {
return false;
}
for (let i = 0; i < this.segments.length; i++) {
if (this.segments[i] !== other.segments[i]) {
return false;
}
}
return true;
}
/**
* Compare the current path against another Path object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other) {
const len = Math.min(this.segments.length, other.segments.length);
for (let i = 0; i < len; i++) {
if (this.segments[i] < other.segments[i]) {
return -1;
}
if (this.segments[i] > other.segments[i]) {
return 1;
}
}
if (this.segments.length < other.segments.length) {
return -1;
}
if (this.segments.length > other.segments.length) {
return 1;
}
return 0;
}
/**
* Returns a copy of the underlying segments.
*
* @private
* @returns A copy of the segments that make up this path.
*/
toArray() {
return this.segments.slice();
}
/**
* Returns true if this `Path` is equal to the provided value.
*
* @private
* @param other The value to compare against.
* @return true if this `Path` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof this.constructor && this.compareTo(other) === 0));
}
}
/**
* A slash-separated path for navigating resources within the current Firestore
* instance.
*
* @private
*/
class ResourcePath extends Path {
/**
* Constructs a ResourcePath.
*
* @private
* @param segments Sequence of names of the parts of the path.
*/
constructor(...segments) {
super(segments);
}
/**
* Indicates whether this path points to a document.
* @private
*/
get isDocument() {
return this.segments.length > 0 && this.segments.length % 2 === 0;
}
/**
* Indicates whether this path points to a collection.
* @private
*/
get isCollection() {
return this.segments.length % 2 === 1;
}
/**
* The last component of the path.
* @private
*/
get id() {
if (this.segments.length > 0) {
return this.segments[this.segments.length - 1];
}
return null;
}
/**
* Returns the location of this path relative to the root of the project's
* database.
* @private
*/
get relativeName() {
return this.segments.join('/');
}
/**
* Constructs a new instance of ResourcePath.
*
* @private
* @param segments Sequence of parts of the path.
* @returns The newly created ResourcePath.
*/
construct(segments) {
return new ResourcePath(...segments);
}
/**
* Splits a string into path segments, using slashes as separators.
*
* @private
* @param relativePath The path to split.
* @returns The split path segments.
*/
split(relativePath) {
// We may have an empty segment at the beginning or end if they had a
// leading or trailing slash (which we allow).
return relativePath.split('/').filter(segment => segment.length > 0);
}
/**
* Converts this path to a fully qualified ResourcePath.
*
* @private
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @return A fully-qualified resource path pointing to the same element.
*/
toQualifiedResourcePath(projectIdIfMissing) {
return new QualifiedResourcePath(projectIdIfMissing, exports.DEFAULT_DATABASE_ID, ...this.segments);
}
}
exports.ResourcePath = ResourcePath;
/**
* A default instance pointing to the root collection.
* @private
*/
ResourcePath.EMPTY = new ResourcePath();
/**
* A slash-separated path that includes a project and database ID for referring
* to resources in any Firestore project.
*
* @private
*/
class QualifiedResourcePath extends ResourcePath {
/**
* Constructs a Firestore Resource Path.
*
* @private
* @param projectId The Firestore project id.
* @param databaseId The Firestore database id.
* @param segments Sequence of names of the parts of the path.
*/
constructor(projectId, databaseId, ...segments) {
super(...segments);
this.projectId = projectId;
this.databaseId = databaseId;
}
/**
* String representation of the path relative to the database root.
* @private
*/
get relativeName() {
return this.segments.join('/');
}
/**
* Creates a resource path from an absolute Firestore path.
*
* @private
* @param absolutePath A string representation of a Resource Path.
* @returns The new ResourcePath.
*/
static fromSlashSeparatedString(absolutePath) {
const elements = RESOURCE_PATH_RE.exec(absolutePath);
if (elements) {
const project = elements[1];
const database = elements[2];
const path = elements[3];
return new QualifiedResourcePath(project, database).append(path);
}
throw new Error(`Resource name '${absolutePath}' is not valid.`);
}
/**
* Create a child path beneath the current level.
*
* @private
* @param relativePath Relative path to append to the current path.
* @returns The new path.
*/
append(relativePath) {
// `super.append()` calls `QualifiedResourcePath.construct()` when invoked
// from here and returns a QualifiedResourcePath.
return super.append(relativePath);
}
/**
* Create a child path beneath the current level.
*
* @private
* @returns The new path.
*/
parent() {
return super.parent();
}
/**
* String representation of a ResourcePath as expected by the API.
*
* @private
* @returns The representation as expected by the API.
*/
get formattedName() {
const components = [
'projects',
this.projectId,
'databases',
this.databaseId,
'documents',
...this.segments,
];
return components.join('/');
}
/**
* Constructs a new instance of ResourcePath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @param segments Sequence of names of the parts of the path.
* @returns The newly created QualifiedResourcePath.
*/
construct(segments) {
return new QualifiedResourcePath(this.projectId, this.databaseId, ...segments);
}
/**
* Convenience method to match the ResourcePath API. This method always
* returns the current instance. The arguments is ignored.
*
* @param projectIdIfMissing The project ID of the current Firestore project.
* The project ID is only used if it's not provided as part of this
* ResourcePath.
* @private
*/
toQualifiedResourcePath(projectIdIfMissing) {
return this;
}
/**
* Compare the current path against another ResourcePath object.
*
* @private
* @param other The path to compare to.
* @returns -1 if current < other, 1 if current > other, 0 if equal
*/
compareTo(other) {
if (other instanceof QualifiedResourcePath) {
if (this.projectId < other.projectId) {
return -1;
}
if (this.projectId > other.projectId) {
return 1;
}
if (this.databaseId < other.databaseId) {
return -1;
}
if (this.databaseId > other.databaseId) {
return 1;
}
}
return super.compareTo(other);
}
/**
* Converts this ResourcePath to the Firestore Proto representation.
* @private
*/
toProto() {
return {
referenceValue: this.formattedName,
};
}
}
exports.QualifiedResourcePath = QualifiedResourcePath;
/**
* Validates that the given string can be used as a relative or absolute
* resource path.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param resourcePath The path to validate.
* @throws if the string can't be used as a resource path.
*/
function validateResourcePath(arg, resourcePath) {
if (typeof resourcePath !== 'string' || resourcePath === '') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'resource path')} Path must be a non-empty string.`);
}
if (resourcePath.indexOf('//') >= 0) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'resource path')} Paths must not contain //.`);
}
}
exports.validateResourcePath = validateResourcePath;
/**
* A dot-separated path for navigating sub-objects within a document.
*
* @class
*/
class FieldPath extends Path {
/**
* Constructs a Firestore Field Path.
*
* @param {...string} segments Sequence of field names that form this path.
*
* @example
* let query = firestore.collection('col');
* let fieldPath = new FieldPath('f.o.o', 'bar');
*
* query.where(fieldPath, '==', 42).get().then(snapshot => {
* snapshot.forEach(document => {
* console.log(`Document contains {'f.o.o' : {'bar' : 42}}`);
* });
* });
*/
constructor(...segments) {
if (Array.isArray(segments[0])) {
throw new Error('The FieldPath constructor no longer supports an array as its first argument. ' +
'Please unpack your array and call FieldPath() with individual arguments.');
}
validate_1.validateMinNumberOfArguments('FieldPath', segments, 1);
for (let i = 0; i < segments.length; ++i) {
validate_1.validateString(i, segments[i]);
if (segments[i].length === 0) {
throw new Error(`Element at index ${i} should not be an empty string.`);
}
}
super(segments);
}
/**
* A special FieldPath value to refer to the ID of a document. It can be used
* in queries to sort or filter by the document ID.
*
* @returns {FieldPath}
*/
static documentId() {
return FieldPath._DOCUMENT_ID;
}
/**
* Turns a field path argument into a [FieldPath]{@link FieldPath}.
* Supports FieldPaths as input (which are passed through) and dot-separated
* strings.
*
* @private
* @param {string|FieldPath} fieldPath The FieldPath to create.
* @returns {FieldPath} A field path representation.
*/
static fromArgument(fieldPath) {
// validateFieldPath() is used in all public API entry points to validate
// that fromArgument() is only called with a Field Path or a string.
return fieldPath instanceof FieldPath
? fieldPath
: new FieldPath(...fieldPath.split('.'));
}
/**
* String representation of a FieldPath as expected by the API.
*
* @private
* @override
* @returns {string} The representation as expected by the API.
*/
get formattedName() {
return this.segments
.map(str => {
return UNESCAPED_FIELD_NAME_RE.test(str)
? str
: '`' + str.replace('\\', '\\\\').replace('`', '\\`') + '`';
})
.join('.');
}
/**
* Returns a string representation of this path.
*
* @private
* @returns A string representing this path.
*/
toString() {
return this.formattedName;
}
/**
* Splits a string into path segments, using dots as separators.
*
* @private
* @override
* @param {string} fieldPath The path to split.
* @returns {Array.<string>} - The split path segments.
*/
split(fieldPath) {
return fieldPath.split('.');
}
/**
* Constructs a new instance of FieldPath. We need this instead of using
* the normal constructor because polymorphic 'this' doesn't work on static
* methods.
*
* @private
* @override
* @param segments Sequence of field names.
* @returns The newly created FieldPath.
*/
construct(segments) {
return new FieldPath(...segments);
}
/**
* Returns true if this `FieldPath` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return {boolean} true if this `FieldPath` is equal to the provided value.
*/
isEqual(other) {
return super.isEqual(other);
}
}
exports.FieldPath = FieldPath;
/**
* A special sentinel value to refer to the ID of a document.
*
* @private
*/
FieldPath._DOCUMENT_ID = new FieldPath('__name__');
/**
* Validates that the provided value can be used as a field path argument.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param fieldPath The value to verify.
* @throws if the string can't be used as a field path.
*/
function validateFieldPath(arg, fieldPath) {
if (fieldPath instanceof FieldPath) {
return;
}
if (fieldPath === undefined) {
throw new Error(validate_1.invalidArgumentMessage(arg, 'field path') + ' The path cannot be omitted.');
}
if (util_1.isObject(fieldPath) && fieldPath.constructor.name === 'FieldPath') {
throw new Error(validate_1.customObjectMessage(arg, fieldPath));
}
if (typeof fieldPath !== 'string') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths can only be specified as strings or via a FieldPath object.`);
}
if (fieldPath.indexOf('..') >= 0) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths must not contain ".." in them.`);
}
if (fieldPath.startsWith('.') || fieldPath.endsWith('.')) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths must not start or end with ".".`);
}
if (!FIELD_PATH_RE.test(fieldPath)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'field path')} Paths can't be empty and must not contain
"*~/[]".`);
}
}
exports.validateFieldPath = validateFieldPath;
//# sourceMappingURL=path.js.map

153
node_modules/@google-cloud/firestore/build/src/pool.js generated vendored Normal file
View File

@ -0,0 +1,153 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const logger_1 = require("./logger");
/**
* An auto-resizing pool that distributes concurrent operations over multiple
* clients of type `T`.
*
* ClientPool is used within Firestore to manage a pool of GAPIC clients and
* automatically initializes multiple clients if we issue more than 100
* concurrent operations.
*
* @private
*/
class ClientPool {
/**
* @param concurrentOperationLimit The number of operations that each client
* can handle.
* @param clientFactory A factory function called as needed when new clients
* are required.
*/
constructor(concurrentOperationLimit, clientFactory) {
this.concurrentOperationLimit = concurrentOperationLimit;
this.clientFactory = clientFactory;
/**
* Stores each active clients and how many operations it has outstanding.
* @private
*/
this.activeClients = new Map();
}
/**
* Returns an already existing client if it has less than the maximum number
* of concurrent operations or initializes and returns a new client.
*
* @private
*/
acquire(requestTag) {
let selectedClient = null;
let selectedRequestCount = 0;
this.activeClients.forEach((requestCount, client) => {
if (!selectedClient && requestCount < this.concurrentOperationLimit) {
logger_1.logger('ClientPool.acquire', requestTag, 'Re-using existing client with %s remaining operations', this.concurrentOperationLimit - requestCount);
selectedClient = client;
selectedRequestCount = requestCount;
}
});
if (!selectedClient) {
logger_1.logger('ClientPool.acquire', requestTag, 'Creating a new client');
selectedClient = this.clientFactory();
assert(!this.activeClients.has(selectedClient), 'The provided client factory returned an existing instance');
}
this.activeClients.set(selectedClient, selectedRequestCount + 1);
return selectedClient;
}
/**
* Reduces the number of operations for the provided client, potentially
* removing it from the pool of active clients.
* @private
*/
release(requestTag, client) {
let requestCount = this.activeClients.get(client) || 0;
assert(requestCount > 0, 'No active request');
requestCount = requestCount - 1;
this.activeClients.set(client, requestCount);
if (requestCount === 0) {
const deletedCount = this.garbageCollect();
if (deletedCount) {
logger_1.logger('ClientPool.release', requestTag, 'Garbage collected %s clients', deletedCount);
}
}
}
/**
* The number of currently registered clients.
*
* @return Number of currently registered clients.
* @private
*/
// Visible for testing.
get size() {
return this.activeClients.size;
}
/**
* The number of currently active operations.
*
* @return Number of currently active operations.
* @private
*/
// Visible for testing.
get opCount() {
let activeOperationCount = 0;
this.activeClients.forEach(count => (activeOperationCount += count));
return activeOperationCount;
}
/**
* Runs the provided operation in this pool. This function may create an
* additional client if all existing clients already operate at the concurrent
* operation limit.
*
* @param requestTag A unique client-assigned identifier for this operation.
* @param op A callback function that returns a Promise. The client T will
* be returned to the pool when callback finishes.
* @return A Promise that resolves with the result of `op`.
* @private
*/
run(requestTag, op) {
const client = this.acquire(requestTag);
return op(client)
.catch(err => {
this.release(requestTag, client);
return Promise.reject(err);
})
.then(res => {
this.release(requestTag, client);
return res;
});
}
/**
* Deletes clients that are no longer executing operations. Keeps up to one
* idle client to reduce future initialization costs.
*
* @return Number of clients deleted.
* @private
*/
garbageCollect() {
let idleClients = 0;
this.activeClients.forEach((requestCount, client) => {
if (requestCount === 0) {
++idleClients;
if (idleClients > 1) {
this.activeClients.delete(client);
}
}
});
return idleClients - 1;
}
}
exports.ClientPool = ClientPool;
//# sourceMappingURL=pool.js.map

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,315 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const convert_1 = require("./convert");
const field_value_1 = require("./field-value");
const field_value_2 = require("./field-value");
const geo_point_1 = require("./geo-point");
const index_1 = require("./index");
const path_1 = require("./path");
const timestamp_1 = require("./timestamp");
const util_1 = require("./util");
const validate_1 = require("./validate");
/**
* The maximum depth of a Firestore object.
*
* @private
*/
const MAX_DEPTH = 20;
/**
* Serializer that is used to convert between JavaScript types and their
* Firestore Protobuf representation.
*
* @private
*/
class Serializer {
constructor(firestore) {
// Instead of storing the `firestore` object, we store just a reference to
// its `.doc()` method. This avoid a circular reference, which breaks
// JSON.stringify().
this.createReference = path => firestore.doc(path);
// tslint:disable-next-line deprecation
if (firestore._settings.timestampsInSnapshots === undefined) {
this.timestampsInSnapshots = true;
}
else {
// tslint:disable-next-line deprecation
this.timestampsInSnapshots = firestore._settings.timestampsInSnapshots;
}
}
/**
* Encodes a JavaScript object into the Firestore 'Fields' representation.
*
* @private
* @param obj The object to encode.
* @returns The Firestore 'Fields' representation
*/
encodeFields(obj) {
const fields = {};
for (const prop of Object.keys(obj)) {
const val = this.encodeValue(obj[prop]);
if (val) {
fields[prop] = val;
}
}
return fields;
}
/**
* Encodes a JavaScript value into the Firestore 'Value' representation.
*
* @private
* @param val The object to encode
* @returns The Firestore Proto or null if we are deleting a field.
*/
encodeValue(val) {
if (val instanceof field_value_1.FieldTransform) {
return null;
}
if (typeof val === 'string') {
return {
stringValue: val,
};
}
if (typeof val === 'boolean') {
return {
booleanValue: val,
};
}
if (typeof val === 'number') {
if (Number.isSafeInteger(val)) {
return {
integerValue: val,
};
}
else {
return {
doubleValue: val,
};
}
}
if (val instanceof Date) {
const timestamp = timestamp_1.Timestamp.fromDate(val);
return {
timestampValue: {
seconds: timestamp.seconds,
nanos: timestamp.nanoseconds,
},
};
}
if (val === null) {
return {
nullValue: 'NULL_VALUE',
};
}
if (val instanceof Buffer || val instanceof Uint8Array) {
return {
bytesValue: val,
};
}
if (util_1.isObject(val)) {
const toProto = val['toProto'];
if (typeof toProto === 'function') {
return toProto.bind(val)();
}
}
if (val instanceof Array) {
const array = {
arrayValue: {},
};
if (val.length > 0) {
array.arrayValue.values = [];
for (let i = 0; i < val.length; ++i) {
const enc = this.encodeValue(val[i]);
if (enc) {
array.arrayValue.values.push(enc);
}
}
}
return array;
}
if (typeof val === 'object' && isPlainObject(val)) {
const map = {
mapValue: {},
};
// If we encounter an empty object, we always need to send it to make sure
// the server creates a map entry.
if (!util_1.isEmpty(val)) {
map.mapValue.fields = this.encodeFields(val);
if (util_1.isEmpty(map.mapValue.fields)) {
return null;
}
}
return map;
}
throw new Error(`Cannot encode value: ${val}`);
}
/**
* Decodes a single Firestore 'Value' Protobuf.
*
* @private
* @param proto A Firestore 'Value' Protobuf.
* @returns The converted JS type.
*/
decodeValue(proto) {
const valueType = convert_1.detectValueType(proto);
switch (valueType) {
case 'stringValue': {
return proto.stringValue;
}
case 'booleanValue': {
return proto.booleanValue;
}
case 'integerValue': {
return Number(proto.integerValue);
}
case 'doubleValue': {
return Number(proto.doubleValue);
}
case 'timestampValue': {
const timestamp = timestamp_1.Timestamp.fromProto(proto.timestampValue);
return this.timestampsInSnapshots ? timestamp : timestamp.toDate();
}
case 'referenceValue': {
const resourcePath = path_1.QualifiedResourcePath.fromSlashSeparatedString(proto.referenceValue);
return this.createReference(resourcePath.relativeName);
}
case 'arrayValue': {
const array = [];
if (Array.isArray(proto.arrayValue.values)) {
for (const value of proto.arrayValue.values) {
array.push(this.decodeValue(value));
}
}
return array;
}
case 'nullValue': {
return null;
}
case 'mapValue': {
const obj = {};
const fields = proto.mapValue.fields;
if (fields) {
for (const prop of Object.keys(fields)) {
obj[prop] = this.decodeValue(fields[prop]);
}
}
return obj;
}
case 'geoPointValue': {
return geo_point_1.GeoPoint.fromProto(proto.geoPointValue);
}
case 'bytesValue': {
return proto.bytesValue;
}
default: {
throw new Error('Cannot decode type from Firestore Value: ' + JSON.stringify(proto));
}
}
}
}
exports.Serializer = Serializer;
/**
* Verifies that 'obj' is a plain JavaScript object that can be encoded as a
* 'Map' in Firestore.
*
* @private
* @param input The argument to verify.
* @returns 'true' if the input can be a treated as a plain object.
*/
function isPlainObject(input) {
return (util_1.isObject(input) &&
(Object.getPrototypeOf(input) === Object.prototype ||
Object.getPrototypeOf(input) === null));
}
exports.isPlainObject = isPlainObject;
/**
* Validates a JavaScript value for usage as a Firestore value.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value JavaScript value to validate.
* @param desc A description of the expected type.
* @param path The field path to validate.
* @param options Validation options
* @param level The current depth of the traversal. This is used to decide
* whether deletes are allowed in conjunction with `allowDeletes: root`.
* @param inArray Whether we are inside an array.
* @throws when the object is invalid.
*/
function validateUserInput(arg, value, desc, options, path, level, inArray) {
if (path && path.size > MAX_DEPTH) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Input object is deeper than ${MAX_DEPTH} levels or contains a cycle.`);
}
options = options || {};
level = level || 0;
inArray = inArray || false;
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (Array.isArray(value)) {
for (let i = 0; i < value.length; ++i) {
validateUserInput(arg, value[i], desc, options, path ? path.append(String(i)) : new path_1.FieldPath(String(i)), level + 1,
/* inArray= */ true);
}
}
else if (isPlainObject(value)) {
for (const prop of Object.keys(value)) {
validateUserInput(arg, value[prop], desc, options, path ? path.append(new path_1.FieldPath(prop)) : new path_1.FieldPath(prop), level + 1, inArray);
}
}
else if (value === undefined) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use "undefined" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof field_value_2.DeleteTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if ((options.allowDeletes === 'root' && level !== 0) ||
options.allowDeletes === 'none') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() must appear at the top-level and can only be used in update() or set() with {merge:true}${fieldPathMessage}.`);
}
}
else if (value instanceof field_value_1.FieldTransform) {
if (inArray) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() cannot be used inside of an array${fieldPathMessage}.`);
}
else if (!options.allowTransforms) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} ${value.methodName}() can only be used in set(), create() or update()${fieldPathMessage}.`);
}
}
else if (value instanceof path_1.FieldPath) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, desc)} Cannot use object of type "FieldPath" as a Firestore value${fieldPathMessage}.`);
}
else if (value instanceof index_1.DocumentReference) {
// Ok.
}
else if (value instanceof geo_point_1.GeoPoint) {
// Ok.
}
else if (value instanceof timestamp_1.Timestamp || value instanceof Date) {
// Ok.
}
else if (value instanceof Buffer || value instanceof Uint8Array) {
// Ok.
}
else if (value === null) {
// Ok.
}
else if (typeof value === 'object') {
throw new Error(validate_1.customObjectMessage(arg, value, path));
}
}
exports.validateUserInput = validateUserInput;
//# sourceMappingURL=serializer.js.map

View File

@ -0,0 +1,225 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const validate_1 = require("./validate");
/*!
* Number of nanoseconds in a millisecond.
*
* @type {number}
*/
const MS_TO_NANOS = 1000000;
/**
* A Timestamp represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian
* Calendar which extends the Gregorian calendar backwards to year one. It is
* encoded assuming all minutes are 60 seconds long, i.e. leap seconds are
* "smeared" so that no leap second table is needed for interpretation. Range is
* from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
*
* @see https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto
*/
class Timestamp {
/**
* Creates a new timestamp.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:new Firestore.Timestamp(42, 0) });
*
* @param {number} seconds The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param {number} nanoseconds The non-negative fractions of a second at
* nanosecond resolution. Negative second values with fractions must still
* have non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
constructor(seconds, nanoseconds) {
validate_1.validateInteger('seconds', seconds);
validate_1.validateInteger('nanoseconds', nanoseconds, {
minValue: 0,
maxValue: 999999999,
});
this._seconds = seconds;
this._nanoseconds = nanoseconds;
}
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ updateTime:Firestore.Timestamp.now() });
*
* @return {Timestamp} A new `Timestamp` representing the current date.
*/
static now() {
return Timestamp.fromMillis(Date.now());
}
/**
* Creates a new timestamp from the given date.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* let date = Date.parse('01 Jan 2000 00:00:00 GMT');
* documentRef.set({ startTime:Firestore.Timestamp.fromDate(date) });
*
* @param {Date} date The date to initialize the `Timestamp` from.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given date.
*/
static fromDate(date) {
return Timestamp.fromMillis(date.getTime());
}
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({ startTime:Firestore.Timestamp.fromMillis(42) });
*
* @param {number} milliseconds Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @return {Timestamp} A new `Timestamp` representing the same point in time
* as the given number of milliseconds.
*/
static fromMillis(milliseconds) {
const seconds = Math.floor(milliseconds / 1000);
const nanos = (milliseconds - seconds * 1000) * MS_TO_NANOS;
return new Timestamp(seconds, nanos);
}
/**
* Generates a `Timestamp` object from a Timestamp proto.
*
* @private
* @param {Object} timestamp The `Timestamp` Protobuf object.
*/
static fromProto(timestamp) {
return new Timestamp(Number(timestamp.seconds || 0), Number(timestamp.nanos || 0));
}
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
get seconds() {
return this._seconds;
}
/**
* The non-negative fractions of a second at nanosecond resolution.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let updated = snap.updateTime;
* console.log(`Updated at ${updated.seconds}s ${updated.nanoseconds}ns`);
* });
*
* @type {number}
*/
get nanoseconds() {
return this._nanoseconds;
}
/**
* Returns a new `Date` corresponding to this timestamp. This may lose
* precision.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* console.log(`Document updated at: ${snap.updateTime.toDate()}`);
* });
*
* @return {Date} JavaScript `Date` object representing the same point in time
* as this `Timestamp`, with millisecond precision.
*/
toDate() {
return new Date(this._seconds * 1000 + Math.round(this._nanoseconds / MS_TO_NANOS));
}
/**
* Returns the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* let startTime = snap.get('startTime');
* let endTime = snap.get('endTime');
* console.log(`Duration: ${endTime - startTime}`);
* });
*
* @return {number} The point in time corresponding to this timestamp,
* represented as the number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
*/
toMillis() {
return this._seconds * 1000 + Math.floor(this._nanoseconds / MS_TO_NANOS);
}
/**
* Returns 'true' if this `Timestamp` is equal to the provided one.
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.get().then(snap => {
* if (snap.createTime.isEqual(snap.updateTime)) {
* console.log('Document is in its initial state.');
* }
* });
*
* @param {any} other The `Timestamp` to compare against.
* @return {boolean} 'true' if this `Timestamp` is equal to the provided one.
*/
isEqual(other) {
return (this === other ||
(other instanceof Timestamp &&
this._seconds === other.seconds &&
this._nanoseconds === other.nanoseconds));
}
/**
* Generates the Protobuf `Timestamp` object for this timestamp.
*
* @private
* @returns {Object} The `Timestamp` Protobuf object.
*/
toProto() {
const timestamp = {};
if (this.seconds) {
timestamp.seconds = this.seconds;
}
if (this.nanoseconds) {
timestamp.nanos = this.nanoseconds;
}
return { timestampValue: timestamp };
}
}
exports.Timestamp = Timestamp;
//# sourceMappingURL=timestamp.js.map

View File

@ -0,0 +1,379 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = require("./path");
const reference_1 = require("./reference");
const serializer_1 = require("./serializer");
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* Error message for transactional reads that were executed after performing
* writes.
*/
const READ_AFTER_WRITE_ERROR_MSG = 'Firestore transactions require all reads to be executed before all writes.';
/*!
* Transactions can be retried if the initial stream opening errors out.
*/
const ALLOW_RETRIES = true;
/**
* A reference to a transaction.
*
* The Transaction object passed to a transaction's updateFunction provides
* the methods to read and write data within the transaction context. See
* [runTransaction()]{@link Firestore#runTransaction}.
*
* @class
*/
class Transaction {
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
* @param requestTag A unique client-assigned identifier for the scope of
* this transaction.
* @param previousTransaction If available, the failed transaction that is
* being retried.
*/
constructor(firestore, requestTag, previousTransaction) {
this._firestore = firestore;
this._transactionId =
previousTransaction && previousTransaction._transactionId;
this._writeBatch = firestore.batch();
this._requestTag = requestTag;
}
/**
* Retrieve a document or a query result from the database. Holds a
* pessimistic lock on all returned documents.
*
* @param {DocumentReference|Query} refOrQuery The document or query to
* return.
* @returns {Promise} A Promise that resolves with a DocumentSnapshot or
* QuerySnapshot for the returned documents.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
get(refOrQuery) {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
if (refOrQuery instanceof reference_1.DocumentReference) {
return this._firestore
.getAll_([refOrQuery],
/* fieldMask= */ null, this._requestTag, this._transactionId)
.then(res => {
return Promise.resolve(res[0]);
});
}
if (refOrQuery instanceof reference_1.Query) {
return refOrQuery._get(this._transactionId);
}
throw new Error('Value for argument "refOrQuery" must be a DocumentReference or a Query.');
}
/**
* Retrieves multiple documents from Firestore. Holds a pessimistic lock on
* all returned documents.
*
* The first argument is required and must be of type `DocumentReference`
* followed by any additional `DocumentReference` documents. If used, the
* optional `ReadOptions` must be the last argument.
*
* @param {...DocumentReference|ReadOptions} documentRefsOrReadOptions The
* `DocumentReferences` to receive, followed by an optional field mask.
* @returns {Promise<Array.<DocumentSnapshot>>} A Promise that
* contains an array with the resulting document snapshots.
*
* @example
* let firstDoc = firestore.doc('col/doc1');
* let secondDoc = firestore.doc('col/doc2');
* let resultDoc = firestore.doc('col/doc3');
*
* firestore.runTransaction(transaction => {
* return transaction.getAll(firstDoc, secondDoc).then(docs => {
* transaction.set(resultDoc, {
* sum: docs[0].get('count') + docs[1].get('count')
* });
* });
* });
*/
getAll(...documentRefsOrReadOptions) {
if (!this._writeBatch.isEmpty) {
throw new Error(READ_AFTER_WRITE_ERROR_MSG);
}
validate_1.validateMinNumberOfArguments('Transaction.getAll', arguments, 1);
const { documents, fieldMask } = parseGetAllArguments(documentRefsOrReadOptions);
return this._firestore.getAll_(documents, fieldMask, this._requestTag, this._transactionId);
}
/**
* Create the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The operation will
* fail the transaction if a document exists at the specified location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {DocumentData} data The object data to serialize as the document.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (!doc.exists) {
* transaction.create(documentRef, { foo: 'bar' });
* }
* });
* });
*/
create(documentRef, data) {
this._writeBatch.create(documentRef, data);
return this;
}
/**
* Writes to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}, the provided data can be merged into the
* existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {DocumentData} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.set(documentRef, { foo: 'bar' });
* return Promise.resolve();
* });
*/
set(documentRef, data, options) {
this._writeBatch.set(documentRef, data, options);
return this;
}
/**
* Updates fields in the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. The update will
* fail if applied to a document that does not exist.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to to enforce on this update.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* return transaction.get(documentRef).then(doc => {
* if (doc.exists) {
* transaction.update(documentRef, { count: doc.get('count') + 1 });
* } else {
* transaction.create(documentRef, { count: 1 });
* }
* });
* });
*/
update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('Transaction.update', arguments, 2);
this._writeBatch.update.apply(this._writeBatch, [
documentRef,
dataOrField,
...preconditionOrValues,
]);
return this;
}
/**
* Deletes the document referred to by the provided [DocumentReference]
* {@link DocumentReference}.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the transaction if the
* document doesn't exist or was last updated at a different time.
* @returns {Transaction} This Transaction instance. Used for
* chaining method calls.
*
* @example
* firestore.runTransaction(transaction => {
* let documentRef = firestore.doc('col/doc');
* transaction.delete(documentRef);
* return Promise.resolve();
* });
*/
delete(documentRef, precondition) {
this._writeBatch.delete(documentRef, precondition);
return this;
}
/**
* Starts a transaction and obtains the transaction id from the server.
*
* @private
*/
begin() {
const request = {
database: this._firestore.formattedName,
};
if (this._transactionId) {
request.options = {
readWrite: {
retryTransaction: this._transactionId,
},
};
}
return this._firestore
.request('beginTransaction', request, this._requestTag, ALLOW_RETRIES)
.then(resp => {
this._transactionId = resp.transaction;
});
}
/**
* Commits all queued-up changes in this transaction and releases all locks.
*
* @private
*/
commit() {
return this._writeBatch
.commit_({
transactionId: this._transactionId,
requestTag: this._requestTag,
})
.then(() => { });
}
/**
* Releases all locks and rolls back this transaction.
*
* @private
*/
rollback() {
const request = {
database: this._firestore.formattedName,
transaction: this._transactionId,
};
return this._firestore.request('rollback', request, this._requestTag,
/* allowRetries= */ false);
}
/**
* Returns the tag to use with with all request for this Transaction.
* @private
* @return A unique client-generated identifier for this transaction.
*/
get requestTag() {
return this._requestTag;
}
}
exports.Transaction = Transaction;
/**
* Parses the arguments for the `getAll()` call supported by both the Firestore
* and Transaction class.
*
* @private
* @param documentRefsOrReadOptions An array of document references followed by
* an optional ReadOptions object.
*/
function parseGetAllArguments(documentRefsOrReadOptions) {
let documents;
let readOptions = undefined;
if (Array.isArray(documentRefsOrReadOptions[0])) {
throw new Error('getAll() no longer accepts an array as its first argument. ' +
'Please unpack your array and call getAll() with individual arguments.');
}
if (documentRefsOrReadOptions.length > 0 &&
serializer_1.isPlainObject(documentRefsOrReadOptions[documentRefsOrReadOptions.length - 1])) {
readOptions = documentRefsOrReadOptions.pop();
documents = documentRefsOrReadOptions;
}
else {
documents = documentRefsOrReadOptions;
}
for (let i = 0; i < documents.length; ++i) {
reference_1.validateDocumentReference(i, documents[i]);
}
validateReadOptions('options', readOptions, { optional: true });
const fieldMask = readOptions && readOptions.fieldMask
? readOptions.fieldMask.map(fieldPath => path_1.FieldPath.fromArgument(fieldPath))
: null;
return { fieldMask, documents };
}
exports.parseGetAllArguments = parseGetAllArguments;
/**
* Validates the use of 'options' as ReadOptions and enforces that 'fieldMask'
* is an array of strings or field paths.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the ReadOptions can be omitted.
*/
function validateReadOptions(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} Input is not an object.'`);
}
const options = value;
if (options.fieldMask !== undefined) {
if (!Array.isArray(options.fieldMask)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} "fieldMask" is not an array.`);
}
for (let i = 0; i < options.fieldMask.length; ++i) {
try {
path_1.validateFieldPath(i, options.fieldMask[i]);
}
catch (err) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'read option')} "fieldMask" is not valid: ${err.message}`);
}
}
}
}
}
//# sourceMappingURL=transaction.js.map

View File

@ -0,0 +1,21 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
class GrpcError extends Error {
}
exports.GrpcError = GrpcError;
//# sourceMappingURL=types.js.map

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

@ -0,0 +1,89 @@
"use strict";
/*!
* Copyright 2018 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A Promise implementation that supports deferred resolution.
* @private
*/
class Deferred {
constructor() {
this.resolve = () => { };
this.reject = () => { };
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
exports.Deferred = Deferred;
/**
* Generate a unique client-side identifier.
*
* Used for the creation of new documents.
*
* @private
* @returns {string} A unique 20-character wide identifier.
*/
function autoId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let autoId = '';
for (let i = 0; i < 20; i++) {
autoId += chars.charAt(Math.floor(Math.random() * chars.length));
}
return autoId;
}
exports.autoId = autoId;
/**
* Generate a short and semi-random client-side identifier.
*
* Used for the creation of request tags.
*
* @private
* @returns {string} A random 5-character wide identifier.
*/
function requestTag() {
return autoId().substr(0, 5);
}
exports.requestTag = requestTag;
/**
* Determines whether `value` is a JavaScript object.
*
* @private
*/
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
exports.isObject = isObject;
/**
* Returns whether `value` has no custom properties.
*
* @private
*/
function isEmpty(value) {
return Object.keys(value).length === 0;
}
exports.isEmpty = isEmpty;
/**
* Determines whether `value` is a JavaScript function.
*
* @private
*/
function isFunction(value) {
return typeof value === 'function';
}
exports.isFunction = isFunction;
//# sourceMappingURL=util.js.map

View File

@ -0,0 +1,101 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* Represents a single field in the database.
*
* Fields are grouped by their "Collection Group", which represent all
* collections in the database with the same id.
*
* @property {string} name
* A field name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}`
*
* A field path may be a simple field name, e.g. `address` or a path to fields
* within map_value , e.g. `address.city`,
* or a special field path. The only valid special field is `*`, which
* represents any field.
*
* Field paths may be quoted using ` (backtick). The only character that needs
* to be escaped within a quoted field path is the backtick character itself,
* escaped using a backslash. Special characters in field paths that
* must be quoted include: `*`, `.`,
* ``` (backtick), `[`, `]`, as well as any ascii symbolic characters.
*
* Examples:
* (Note: Comments here are written in markdown syntax, so there is an
* additional layer of backticks to represent a code block)
* `\`address.city\`` represents a field named `address.city`, not the map key
* `city` in the field `address`.
* `\`*\`` represents a field named `*`, not any field.
*
* A special `Field` contains the default indexing settings for all fields.
* This field's resource name is:
* `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/*`
* Indexes defined on this `Field` will be applied to all fields which do not
* have their own `Field` index configuration.
*
* @property {Object} indexConfig
* The index configuration for this field. If unset, field indexing will
* revert to the configuration defined by the `ancestor_field`. To
* explicitly remove all indexes for this field, specify an index config
* with an empty list of indexes.
*
* This object should have the same structure as [IndexConfig]{@link google.firestore.admin.v1.IndexConfig}
*
* @typedef Field
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.Field definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/field.proto}
*/
const Field = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* The index configuration for this field.
*
* @property {Object[]} indexes
* The indexes supported for this field.
*
* This object should have the same structure as [Index]{@link google.firestore.admin.v1.Index}
*
* @property {boolean} usesAncestorConfig
* Output only.
* When true, the `Field`'s index configuration is set from the
* configuration specified by the `ancestor_field`.
* When false, the `Field`'s index configuration is defined explicitly.
*
* @property {string} ancestorField
* Output only.
* Specifies the resource name of the `Field` from which this field's
* index configuration is set (when `uses_ancestor_config` is true),
* or from which it *would* be set if this field had no index configuration
* (when `uses_ancestor_config` is false).
*
* @property {boolean} reverting
* Output only
* When true, the `Field`'s index configuration is in the process of being
* reverted. Once complete, the index config will transition to the same
* state as the field specified by `ancestor_field`, at which point
* `uses_ancestor_config` will be `true` and `reverting` will be `false`.
*
* @typedef IndexConfig
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.Field.IndexConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/field.proto}
*/
IndexConfig: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
};
//# sourceMappingURL=doc_field.js.map

View File

@ -0,0 +1,243 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* The request for FirestoreAdmin.CreateIndex.
*
* @property {string} parent
* A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
*
* @property {Object} index
* The composite index to create.
*
* This object should have the same structure as [Index]{@link google.firestore.admin.v1.Index}
*
* @typedef CreateIndexRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.CreateIndexRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const CreateIndexRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.ListIndexes.
*
* @property {string} parent
* A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
*
* @property {string} filter
* The filter to apply to list results.
*
* @property {number} pageSize
* The number of results to return.
*
* @property {string} pageToken
* A page token, returned from a previous call to
* FirestoreAdmin.ListIndexes, that may be used to get the next
* page of results.
*
* @typedef ListIndexesRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ListIndexesRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ListIndexesRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for FirestoreAdmin.ListIndexes.
*
* @property {Object[]} indexes
* The requested indexes.
*
* This object should have the same structure as [Index]{@link google.firestore.admin.v1.Index}
*
* @property {string} nextPageToken
* A page token that may be used to request another page of results. If blank,
* this is the last page.
*
* @typedef ListIndexesResponse
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ListIndexesResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ListIndexesResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.GetIndex.
*
* @property {string} name
* A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}`
*
* @typedef GetIndexRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.GetIndexRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const GetIndexRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.DeleteIndex.
*
* @property {string} name
* A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}`
*
* @typedef DeleteIndexRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.DeleteIndexRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const DeleteIndexRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.UpdateField.
*
* @property {Object} field
* The field to be updated.
*
* This object should have the same structure as [Field]{@link google.firestore.admin.v1.Field}
*
* @property {Object} updateMask
* A mask, relative to the field. If specified, only configuration specified
* by this field_mask will be updated in the field.
*
* This object should have the same structure as [FieldMask]{@link google.protobuf.FieldMask}
*
* @typedef UpdateFieldRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.UpdateFieldRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const UpdateFieldRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.GetField.
*
* @property {string} name
* A name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}`
*
* @typedef GetFieldRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.GetFieldRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const GetFieldRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.ListFields.
*
* @property {string} parent
* A parent name of the form
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}`
*
* @property {string} filter
* The filter to apply to list results. Currently,
* FirestoreAdmin.ListFields only supports listing fields
* that have been explicitly overridden. To issue this query, call
* FirestoreAdmin.ListFields with the filter set to
* `indexConfig.usesAncestorConfig:false`.
*
* @property {number} pageSize
* The number of results to return.
*
* @property {string} pageToken
* A page token, returned from a previous call to
* FirestoreAdmin.ListFields, that may be used to get the next
* page of results.
*
* @typedef ListFieldsRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ListFieldsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ListFieldsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for FirestoreAdmin.ListFields.
*
* @property {Object[]} fields
* The requested fields.
*
* This object should have the same structure as [Field]{@link google.firestore.admin.v1.Field}
*
* @property {string} nextPageToken
* A page token that may be used to request another page of results. If blank,
* this is the last page.
*
* @typedef ListFieldsResponse
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ListFieldsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ListFieldsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.ExportDocuments.
*
* @property {string} name
* Database to export. Should be of the form:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {string[]} collectionIds
* Which collection ids to export. Unspecified means all collections.
*
* @property {string} outputUriPrefix
* The output URI. Currently only supports Google Cloud Storage URIs of the
* form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name
* of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional
* Google Cloud Storage namespace path. When
* choosing a name, be sure to consider Google Cloud Storage naming
* guidelines: https://cloud.google.com/storage/docs/naming.
* If the URI is a bucket (without a namespace path), a prefix will be
* generated based on the start time.
*
* @typedef ExportDocumentsRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ExportDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ExportDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for FirestoreAdmin.ImportDocuments.
*
* @property {string} name
* Database to import into. Should be of the form:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {string[]} collectionIds
* Which collection ids to import. Unspecified means all collections included
* in the import.
*
* @property {string} inputUriPrefix
* Location of the exported files.
* This must match the output_uri_prefix of an ExportDocumentsResponse from
* an export that has completed successfully.
* See:
* google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix.
*
* @typedef ImportDocumentsRequest
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.ImportDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/firestore_admin.proto}
*/
const ImportDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_firestore_admin.js.map

View File

@ -0,0 +1,189 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* Cloud Firestore indexes enable simple and complex queries against
* documents in a database.
*
* @property {string} name
* Output only.
* A server defined name for this index.
* The form of this name for composite indexes will be:
* `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{composite_index_id}`
* For single field indexes, this field will be empty.
*
* @property {number} queryScope
* Indexes with a collection query scope specified allow queries
* against a collection that is the child of a specific document, specified at
* query time, and that has the same collection id.
*
* Indexes with a collection group query scope specified allow queries against
* all collections descended from a specific document, specified at query
* time, and that have the same collection id as this index.
*
* The number should be among the values of [QueryScope]{@link google.firestore.admin.v1.QueryScope}
*
* @property {Object[]} fields
* The fields supported by this index.
*
* For composite indexes, this is always 2 or more fields.
* The last field entry is always for the field path `__name__`. If, on
* creation, `__name__` was not specified as the last field, it will be added
* automatically with the same direction as that of the last field defined. If
* the final field in a composite index is not directional, the `__name__`
* will be ordered ASCENDING (unless explicitly specified).
*
* For single field indexes, this will always be exactly one entry with a
* field path equal to the field path of the associated field.
*
* This object should have the same structure as [IndexField]{@link google.firestore.admin.v1.IndexField}
*
* @property {number} state
* Output only.
* The serving state of the index.
*
* The number should be among the values of [State]{@link google.firestore.admin.v1.State}
*
* @typedef Index
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.Index definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/index.proto}
*/
const Index = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A field in an index.
* The field_path describes which field is indexed, the value_mode describes
* how the field value is indexed.
*
* @property {string} fieldPath
* Can be __name__.
* For single field indexes, this must match the name of the field or may
* be omitted.
*
* @property {number} order
* Indicates that this field supports ordering by the specified order or
* comparing using =, <, <=, >, >=.
*
* The number should be among the values of [Order]{@link google.firestore.admin.v1.Order}
*
* @property {number} arrayConfig
* Indicates that this field supports operations on `array_value`s.
*
* The number should be among the values of [ArrayConfig]{@link google.firestore.admin.v1.ArrayConfig}
*
* @typedef IndexField
* @memberof google.firestore.admin.v1
* @see [google.firestore.admin.v1.Index.IndexField definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/admin/v1/index.proto}
*/
IndexField: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* The supported array value configurations.
*
* @enum {number}
* @memberof google.firestore.admin.v1
*/
ArrayConfig: {
/**
* The index does not support additional array queries.
*/
ARRAY_CONFIG_UNSPECIFIED: 0,
/**
* The index supports array containment queries.
*/
CONTAINS: 1,
},
/**
* The supported orderings.
*
* @enum {number}
* @memberof google.firestore.admin.v1
*/
Order: {
/**
* The ordering is unspecified. Not a valid option.
*/
ORDER_UNSPECIFIED: 0,
/**
* The field is ordered by ascending field value.
*/
ASCENDING: 1,
/**
* The field is ordered by descending field value.
*/
DESCENDING: 2,
},
},
/**
* Query Scope defines the scope at which a query is run. This is specified on
* a StructuredQuery's `from` field.
*
* @enum {number}
* @memberof google.firestore.admin.v1
*/
QueryScope: {
/**
* The query scope is unspecified. Not a valid option.
*/
QUERY_SCOPE_UNSPECIFIED: 0,
/**
* Indexes with a collection query scope specified allow queries
* against a collection that is the child of a specific document, specified
* at query time, and that has the collection id specified by the index.
*/
COLLECTION: 1,
},
/**
* The state of an index. During index creation, an index will be in the
* `CREATING` state. If the index is created successfully, it will transition
* to the `READY` state. If the index creation encounters a problem, the index
* will transition to the `NEEDS_REPAIR` state.
*
* @enum {number}
* @memberof google.firestore.admin.v1
*/
State: {
/**
* The state is unspecified.
*/
STATE_UNSPECIFIED: 0,
/**
* The index is being created.
* There is an active long-running operation for the index.
* The index is updated when writing a document.
* Some index data may exist.
*/
CREATING: 1,
/**
* The index is ready to be used.
* The index is updated when writing a document.
* The index is fully populated from all stored documents it applies to.
*/
READY: 2,
/**
* The index was being created, but something went wrong.
* There is no active long-running operation for the index,
* and the most recently finished long-running operation failed.
* The index is not updated when writing a document.
* Some index data may exist.
* Use the google.longrunning.Operations API to determine why the operation
* that last attempted to create this index failed, then re-create the
* index.
*/
NEEDS_REPAIR: 3,
},
};
//# sourceMappingURL=doc_index.js.map

View File

@ -0,0 +1,104 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A set of field paths on a document.
* Used to restrict a get or update operation on a document to a subset of its
* fields.
* This is different from standard field masks, as this is always scoped to a
* Document, and takes in account the dynamic nature of Value.
*
* @property {string[]} fieldPaths
* The list of field paths in the mask. See Document.fields for a field
* path syntax reference.
*
* @typedef DocumentMask
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentMask definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/common.proto}
*/
const DocumentMask = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A precondition on a document, used for conditional operations.
*
* @property {boolean} exists
* When set to `true`, the target document must exist.
* When set to `false`, the target document must not exist.
*
* @property {Object} updateTime
* When set, the target document must exist and have been last updated at
* that time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef Precondition
* @memberof google.firestore.v1
* @see [google.firestore.v1.Precondition definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/common.proto}
*/
const Precondition = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* Options for creating a new transaction.
*
* @property {Object} readOnly
* The transaction can only be used for read operations.
*
* This object should have the same structure as [ReadOnly]{@link google.firestore.v1.ReadOnly}
*
* @property {Object} readWrite
* The transaction can be used for both read and write operations.
*
* This object should have the same structure as [ReadWrite]{@link google.firestore.v1.ReadWrite}
*
* @typedef TransactionOptions
* @memberof google.firestore.v1
* @see [google.firestore.v1.TransactionOptions definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/common.proto}
*/
const TransactionOptions = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* Options for a transaction that can be used to read and write documents.
*
* @property {Buffer} retryTransaction
* An optional transaction to retry.
*
* @typedef ReadWrite
* @memberof google.firestore.v1
* @see [google.firestore.v1.TransactionOptions.ReadWrite definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/common.proto}
*/
ReadWrite: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* Options for a transaction that can only be used to read documents.
*
* @property {Object} readTime
* Reads documents at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef ReadOnly
* @memberof google.firestore.v1
* @see [google.firestore.v1.TransactionOptions.ReadOnly definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/common.proto}
*/
ReadOnly: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
};
//# sourceMappingURL=doc_common.js.map

View File

@ -0,0 +1,177 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Firestore document.
*
* Must not exceed 1 MiB - 4 bytes.
*
* @property {string} name
* The resource name of the document, for example
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object.<string, Object>} fields
* The document's fields.
*
* The map keys represent field names.
*
* A simple field name contains only characters `a` to `z`, `A` to `Z`,
* `0` to `9`, or `_`, and must not start with `0` to `9`. For example,
* `foo_bar_17`.
*
* Field names matching the regular expression `__.*__` are reserved. Reserved
* field names are forbidden except in certain documented contexts. The map
* keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be
* empty.
*
* Field paths may be used in other contexts to refer to structured fields
* defined here. For `map_value`, the field path is represented by the simple
* or quoted field names of the containing fields, delimited by `.`. For
* example, the structured field
* `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be
* represented by the field path `foo.x&y`.
*
* Within a field path, a quoted field name starts and ends with `` ` `` and
* may contain any character. Some characters, including `` ` ``, must be
* escaped using a `\`. For example, `` `x&y` `` represents `x&y` and
* `` `bak\`tik` `` represents `` bak`tik ``.
*
* @property {Object} createTime
* Output only. The time at which the document was created.
*
* This value increases monotonically when a document is deleted then
* recreated. It can also be compared to values from other documents and
* the `read_time` of a query.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {Object} updateTime
* Output only. The time at which the document was last changed.
*
* This value is initially set to the `create_time` then increases
* monotonically with each change to the document. It can also be
* compared to values from other documents and the `read_time` of a query.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef Document
* @memberof google.firestore.v1
* @see [google.firestore.v1.Document definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/document.proto}
*/
const Document = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A message that can hold any of the supported value types.
*
* @property {number} nullValue
* A null value.
*
* The number should be among the values of [NullValue]{@link google.protobuf.NullValue}
*
* @property {boolean} booleanValue
* A boolean value.
*
* @property {number} integerValue
* An integer value.
*
* @property {number} doubleValue
* A double value.
*
* @property {Object} timestampValue
* A timestamp value.
*
* Precise only to microseconds. When stored, any additional precision is
* rounded down.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {string} stringValue
* A string value.
*
* The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes.
* Only the first 1,500 bytes of the UTF-8 representation are considered by
* queries.
*
* @property {Buffer} bytesValue
* A bytes value.
*
* Must not exceed 1 MiB - 89 bytes.
* Only the first 1,500 bytes are considered by queries.
*
* @property {string} referenceValue
* A reference to a document. For example:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} geoPointValue
* A geo point value representing a point on the surface of Earth.
*
* This object should have the same structure as [LatLng]{@link google.type.LatLng}
*
* @property {Object} arrayValue
* An array value.
*
* Cannot directly contain another array value, though can contain an
* map which contains another array.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1.ArrayValue}
*
* @property {Object} mapValue
* A map value.
*
* This object should have the same structure as [MapValue]{@link google.firestore.v1.MapValue}
*
* @typedef Value
* @memberof google.firestore.v1
* @see [google.firestore.v1.Value definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/document.proto}
*/
const Value = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* An array value.
*
* @property {Object[]} values
* Values in the array.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @typedef ArrayValue
* @memberof google.firestore.v1
* @see [google.firestore.v1.ArrayValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/document.proto}
*/
const ArrayValue = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A map value.
*
* @property {Object.<string, Object>} fields
* The map's fields.
*
* The map keys represent field names. Field names matching the regular
* expression `__.*__` are reserved. Reserved field names are forbidden except
* in certain documented contexts. The map keys, represented as UTF-8, must
* not exceed 1,500 bytes and cannot be empty.
*
* @typedef MapValue
* @memberof google.firestore.v1
* @see [google.firestore.v1.MapValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/document.proto}
*/
const MapValue = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_document.js.map

View File

@ -0,0 +1,840 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* The request for Firestore.GetDocument.
*
* @property {string} name
* The resource name of the Document to get. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Buffer} transaction
* Reads the document in a transaction.
*
* @property {Object} readTime
* Reads the version of the document at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef GetDocumentRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.GetDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const GetDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.ListDocuments.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {string} collectionId
* The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
*
* @property {number} pageSize
* The maximum number of documents to return.
*
* @property {string} pageToken
* The `next_page_token` value returned from a previous List request, if any.
*
* @property {string} orderBy
* The order to sort results by. For example: `priority desc, name`.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {boolean} showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, Document.create_time,
* or Document.update_time set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
*
* @typedef ListDocumentsRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.ListDocuments.
*
* @property {Object[]} documents
* The Documents found.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {string} nextPageToken
* The next page token.
*
* @typedef ListDocumentsResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListDocumentsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.CreateDocument.
*
* @property {string} parent
* The parent resource. For example:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`
*
* @property {string} collectionId
* The collection ID, relative to `parent`, to list. For example: `chatrooms`.
*
* @property {string} documentId
* The client-assigned document ID to use for this document.
*
* Optional. If not specified, an ID will be assigned by the service.
*
* @property {Object} document
* The document to create. `name` must not be set.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @typedef CreateDocumentRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.CreateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const CreateDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.UpdateDocument.
*
* @property {Object} document
* The updated document.
* Creates the document if it does not already exist.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {Object} updateMask
* The fields to update.
* None of the field paths in the mask may contain a reserved name.
*
* If the document exists on the server and has fields not referenced in the
* mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Object} currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1.Precondition}
*
* @typedef UpdateDocumentRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.UpdateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const UpdateDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.DeleteDocument.
*
* @property {string} name
* The resource name of the Document to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1.Precondition}
*
* @typedef DeleteDocumentRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.DeleteDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const DeleteDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.BatchGetDocuments.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {string[]} documents
* The names of the documents to retrieve. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* The request will fail if any of the document is not a child resource of the
* given `database`. Duplicate names will be elided.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field will
* not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1.TransactionOptions}
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef BatchGetDocumentsRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.BatchGetDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const BatchGetDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The streamed response for Firestore.BatchGetDocuments.
*
* @property {Object} found
* A document that was requested.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {string} missing
* A document name that was requested but does not exist. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Buffer} transaction
* The transaction that was started as part of this request.
* Will only be set in the first response, and only if
* BatchGetDocumentsRequest.new_transaction was set in the request.
*
* @property {Object} readTime
* The time at which the document was read.
* This may be monotically increasing, in this case the previous documents in
* the result stream are guaranteed not to have changed between their
* read_time and this one.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef BatchGetDocumentsResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.BatchGetDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const BatchGetDocumentsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.BeginTransaction.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object} options
* The options for the transaction.
* Defaults to a read-write transaction.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1.TransactionOptions}
*
* @typedef BeginTransactionRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.BeginTransactionRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const BeginTransactionRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.BeginTransaction.
*
* @property {Buffer} transaction
* The transaction that was started.
*
* @typedef BeginTransactionResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.BeginTransactionResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const BeginTransactionResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Commit.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object[]} writes
* The writes to apply.
*
* Always executed atomically and in order.
*
* This object should have the same structure as [Write]{@link google.firestore.v1.Write}
*
* @property {Buffer} transaction
* If set, applies all writes in this transaction, and commits it.
*
* @typedef CommitRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.CommitRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const CommitRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Commit.
*
* @property {Object[]} writeResults
* The result of applying the writes.
*
* This i-th write result corresponds to the i-th write in the
* request.
*
* This object should have the same structure as [WriteResult]{@link google.firestore.v1.WriteResult}
*
* @property {Object} commitTime
* The time at which the commit occurred.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef CommitResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.CommitResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const CommitResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Rollback.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Buffer} transaction
* The transaction to roll back.
*
* @typedef RollbackRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.RollbackRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const RollbackRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.RunQuery.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {Object} structuredQuery
* A structured query.
*
* This object should have the same structure as [StructuredQuery]{@link google.firestore.v1.StructuredQuery}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1.TransactionOptions}
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef RunQueryRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.RunQueryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const RunQueryRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.RunQuery.
*
* @property {Buffer} transaction
* The transaction that was started as part of this request.
* Can only be set in the first response, and only if
* RunQueryRequest.new_transaction was set in the request.
* If set, no other fields will be set in this response.
*
* @property {Object} document
* A query result.
* Not set when reporting partial progress.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {Object} readTime
* The time at which the document was read. This may be monotonically
* increasing; in this case, the previous documents in the result stream are
* guaranteed not to have changed between their `read_time` and this one.
*
* If the query returns no results, a response with `read_time` and no
* `document` will be sent, and this represents the time at which the query
* was run.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {number} skippedResults
* The number of results that have been skipped due to an offset between
* the last response and the current response.
*
* @typedef RunQueryResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.RunQueryResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const RunQueryResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Write.
*
* The first request creates a stream, or resumes an existing one from a token.
*
* When creating a new stream, the server replies with a response containing
* only an ID and a token, to use in the next request.
*
* When resuming a stream, the server first streams any responses later than the
* given token, then a response containing only an up-to-date token, to use in
* the next request.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
* This is only required in the first message.
*
* @property {string} streamId
* The ID of the write stream to resume.
* This may only be set in the first message. When left empty, a new write
* stream will be created.
*
* @property {Object[]} writes
* The writes to apply.
*
* Always executed atomically and in order.
* This must be empty on the first request.
* This may be empty on the last request.
* This must not be empty on all other requests.
*
* This object should have the same structure as [Write]{@link google.firestore.v1.Write}
*
* @property {Buffer} streamToken
* A stream token that was previously sent by the server.
*
* The client should set this field to the token from the most recent
* WriteResponse it has received. This acknowledges that the client has
* received responses up to this token. After sending this token, earlier
* tokens may not be used anymore.
*
* The server may close the stream if there are too many unacknowledged
* responses.
*
* Leave this field unset when creating a new stream. To resume a stream at
* a specific point, set this field and the `stream_id` field.
*
* Leave this field unset when creating a new stream.
*
* @property {Object.<string, string>} labels
* Labels associated with this write request.
*
* @typedef WriteRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.WriteRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const WriteRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Write.
*
* @property {string} streamId
* The ID of the stream.
* Only set on the first message, when a new stream was created.
*
* @property {Buffer} streamToken
* A token that represents the position of this response in the stream.
* This can be used by a client to resume the stream at this point.
*
* This field is always set.
*
* @property {Object[]} writeResults
* The result of applying the writes.
*
* This i-th write result corresponds to the i-th write in the
* request.
*
* This object should have the same structure as [WriteResult]{@link google.firestore.v1.WriteResult}
*
* @property {Object} commitTime
* The time at which the commit occurred.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef WriteResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.WriteResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const WriteResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A request for Firestore.Listen
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object} addTarget
* A target to add to this stream.
*
* This object should have the same structure as [Target]{@link google.firestore.v1.Target}
*
* @property {number} removeTarget
* The ID of a target to remove from this stream.
*
* @property {Object.<string, string>} labels
* Labels associated with this target change.
*
* @typedef ListenRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListenRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListenRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Listen.
*
* @property {Object} targetChange
* Targets have changed.
*
* This object should have the same structure as [TargetChange]{@link google.firestore.v1.TargetChange}
*
* @property {Object} documentChange
* A Document has changed.
*
* This object should have the same structure as [DocumentChange]{@link google.firestore.v1.DocumentChange}
*
* @property {Object} documentDelete
* A Document has been deleted.
*
* This object should have the same structure as [DocumentDelete]{@link google.firestore.v1.DocumentDelete}
*
* @property {Object} documentRemove
* A Document has been removed from a target (because it is no longer
* relevant to that target).
*
* This object should have the same structure as [DocumentRemove]{@link google.firestore.v1.DocumentRemove}
*
* @property {Object} filter
* A filter to apply to the set of documents previously returned for the
* given target.
*
* Returned when documents may have been removed from the given target, but
* the exact documents are unknown.
*
* This object should have the same structure as [ExistenceFilter]{@link google.firestore.v1.ExistenceFilter}
*
* @typedef ListenResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListenResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListenResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A specification of a set of documents to listen to.
*
* @property {Object} query
* A target specified by a query.
*
* This object should have the same structure as [QueryTarget]{@link google.firestore.v1.QueryTarget}
*
* @property {Object} documents
* A target specified by a set of document names.
*
* This object should have the same structure as [DocumentsTarget]{@link google.firestore.v1.DocumentsTarget}
*
* @property {Buffer} resumeToken
* A resume token from a prior TargetChange for an identical target.
*
* Using a resume token with a different target is unsupported and may fail.
*
* @property {Object} readTime
* Start listening after a specific `read_time`.
*
* The client must know the state of matching documents at this time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {number} targetId
* A client provided target ID.
*
* If not set, the server will assign an ID for the target.
*
* Used for resuming a target without changing IDs. The IDs can either be
* client-assigned or be server-assigned in a previous stream. All targets
* with client provided IDs must be added before adding a target that needs
* a server-assigned id.
*
* @property {boolean} once
* If the target should be removed once it is current and consistent.
*
* @typedef Target
* @memberof google.firestore.v1
* @see [google.firestore.v1.Target definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const Target = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A target specified by a set of documents names.
*
* @property {string[]} documents
* The names of the documents to retrieve. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* The request will fail if any of the document is not a child resource of
* the given `database`. Duplicate names will be elided.
*
* @typedef DocumentsTarget
* @memberof google.firestore.v1
* @see [google.firestore.v1.Target.DocumentsTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
DocumentsTarget: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A target specified by a query.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {Object} structuredQuery
* A structured query.
*
* This object should have the same structure as [StructuredQuery]{@link google.firestore.v1.StructuredQuery}
*
* @typedef QueryTarget
* @memberof google.firestore.v1
* @see [google.firestore.v1.Target.QueryTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
QueryTarget: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
};
/**
* Targets being watched have changed.
*
* @property {number} targetChangeType
* The type of change that occurred.
*
* The number should be among the values of [TargetChangeType]{@link google.firestore.v1.TargetChangeType}
*
* @property {number[]} targetIds
* The target IDs of targets that have changed.
*
* If empty, the change applies to all targets.
*
* For `target_change_type=ADD`, the order of the target IDs matches the order
* of the requests to add the targets. This allows clients to unambiguously
* associate server-assigned target IDs with added targets.
*
* For other states, the order of the target IDs is not defined.
*
* @property {Object} cause
* The error that resulted in this change, if applicable.
*
* This object should have the same structure as [Status]{@link google.rpc.Status}
*
* @property {Buffer} resumeToken
* A token that can be used to resume the stream for the given `target_ids`,
* or all targets if `target_ids` is empty.
*
* Not set on every target change.
*
* @property {Object} readTime
* The consistent `read_time` for the given `target_ids` (omitted when the
* target_ids are not at a consistent snapshot).
*
* The stream is guaranteed to send a `read_time` with `target_ids` empty
* whenever the entire stream reaches a new consistent snapshot. ADD,
* CURRENT, and RESET messages are guaranteed to (eventually) result in a
* new consistent snapshot (while NO_CHANGE and REMOVE messages are not).
*
* For a given stream, `read_time` is guaranteed to be monotonically
* increasing.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef TargetChange
* @memberof google.firestore.v1
* @see [google.firestore.v1.TargetChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const TargetChange = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* The type of change.
*
* @enum {number}
* @memberof google.firestore.v1
*/
TargetChangeType: {
/**
* No change has occurred. Used only to send an updated `resume_token`.
*/
NO_CHANGE: 0,
/**
* The targets have been added.
*/
ADD: 1,
/**
* The targets have been removed.
*/
REMOVE: 2,
/**
* The targets reflect all changes committed before the targets were added
* to the stream.
*
* This will be sent after or with a `read_time` that is greater than or
* equal to the time at which the targets were added.
*
* Listeners can wait for this change if read-after-write semantics
* are desired.
*/
CURRENT: 3,
/**
* The targets have been reset, and a new initial state for the targets
* will be returned in subsequent changes.
*
* After the initial state is complete, `CURRENT` will be returned even
* if the target was previously indicated to be `CURRENT`.
*/
RESET: 4,
},
};
/**
* The request for Firestore.ListCollectionIds.
*
* @property {string} parent
* The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {number} pageSize
* The maximum number of results to return.
*
* @property {string} pageToken
* A page token. Must be a value from
* ListCollectionIdsResponse.
*
* @typedef ListCollectionIdsRequest
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListCollectionIdsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListCollectionIdsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response from Firestore.ListCollectionIds.
*
* @property {string[]} collectionIds
* The collection ids.
*
* @property {string} nextPageToken
* A page token that may be used to continue the list.
*
* @typedef ListCollectionIdsResponse
* @memberof google.firestore.v1
* @see [google.firestore.v1.ListCollectionIdsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/firestore.proto}
*/
const ListCollectionIdsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_firestore.js.map

View File

@ -0,0 +1,363 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Firestore query.
*
* @property {Object} select
* The projection to return.
*
* This object should have the same structure as [Projection]{@link google.firestore.v1.Projection}
*
* @property {Object[]} from
* The collections to query.
*
* This object should have the same structure as [CollectionSelector]{@link google.firestore.v1.CollectionSelector}
*
* @property {Object} where
* The filter to apply.
*
* This object should have the same structure as [Filter]{@link google.firestore.v1.Filter}
*
* @property {Object[]} orderBy
* The order to apply to the query results.
*
* Firestore guarantees a stable ordering through the following rules:
*
* * Any field required to appear in `order_by`, that is not already
* specified in `order_by`, is appended to the order in field name order
* by default.
* * If an order on `__name__` is not specified, it is appended by default.
*
* Fields are appended with the same sort direction as the last order
* specified, or 'ASCENDING' if no order was specified. For example:
*
* * `SELECT * FROM Foo ORDER BY A` becomes
* `SELECT * FROM Foo ORDER BY A, __name__`
* * `SELECT * FROM Foo ORDER BY A DESC` becomes
* `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC`
* * `SELECT * FROM Foo WHERE A > 1` becomes
* `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__`
*
* This object should have the same structure as [Order]{@link google.firestore.v1.Order}
*
* @property {Object} startAt
* A starting point for the query results.
*
* This object should have the same structure as [Cursor]{@link google.firestore.v1.Cursor}
*
* @property {Object} endAt
* A end point for the query results.
*
* This object should have the same structure as [Cursor]{@link google.firestore.v1.Cursor}
*
* @property {number} offset
* The number of results to skip.
*
* Applies before limit, but after all other constraints. Must be >= 0 if
* specified.
*
* @property {Object} limit
* The maximum number of results to return.
*
* Applies after all other constraints.
* Must be >= 0 if specified.
*
* This object should have the same structure as [Int32Value]{@link google.protobuf.Int32Value}
*
* @typedef StructuredQuery
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
const StructuredQuery = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A selection of a collection, such as `messages as m1`.
*
* @property {string} collectionId
* The collection ID.
* When set, selects only collections with this ID.
*
* @property {boolean} allDescendants
* When false, selects only collections that are immediate children of
* the `parent` specified in the containing `RunQueryRequest`.
* When true, selects all descendant collections.
*
* @typedef CollectionSelector
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.CollectionSelector definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
CollectionSelector: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A filter.
*
* @property {Object} compositeFilter
* A composite filter.
*
* This object should have the same structure as [CompositeFilter]{@link google.firestore.v1.CompositeFilter}
*
* @property {Object} fieldFilter
* A filter on a document field.
*
* This object should have the same structure as [FieldFilter]{@link google.firestore.v1.FieldFilter}
*
* @property {Object} unaryFilter
* A filter that takes exactly one argument.
*
* This object should have the same structure as [UnaryFilter]{@link google.firestore.v1.UnaryFilter}
*
* @typedef Filter
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.Filter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
Filter: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A filter that merges multiple other filters using the given operator.
*
* @property {number} op
* The operator for combining multiple filters.
*
* The number should be among the values of [Operator]{@link google.firestore.v1.Operator}
*
* @property {Object[]} filters
* The list of filters to combine.
* Must contain at least one filter.
*
* This object should have the same structure as [Filter]{@link google.firestore.v1.Filter}
*
* @typedef CompositeFilter
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.CompositeFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
CompositeFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A composite filter operator.
*
* @enum {number}
* @memberof google.firestore.v1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* The results are required to satisfy each of the combined filters.
*/
AND: 1,
},
},
/**
* A filter on a specific field.
*
* @property {Object} field
* The field to filter by.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1.FieldReference}
*
* @property {number} op
* The operator to filter by.
*
* The number should be among the values of [Operator]{@link google.firestore.v1.Operator}
*
* @property {Object} value
* The value to compare to.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @typedef FieldFilter
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.FieldFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
FieldFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A field filter operator.
*
* @enum {number}
* @memberof google.firestore.v1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* Less than. Requires that the field come first in `order_by`.
*/
LESS_THAN: 1,
/**
* Less than or equal. Requires that the field come first in `order_by`.
*/
LESS_THAN_OR_EQUAL: 2,
/**
* Greater than. Requires that the field come first in `order_by`.
*/
GREATER_THAN: 3,
/**
* Greater than or equal. Requires that the field come first in
* `order_by`.
*/
GREATER_THAN_OR_EQUAL: 4,
/**
* Equal.
*/
EQUAL: 5,
/**
* Contains. Requires that the field is an array.
*/
ARRAY_CONTAINS: 7,
},
},
/**
* A filter with a single operand.
*
* @property {number} op
* The unary operator to apply.
*
* The number should be among the values of [Operator]{@link google.firestore.v1.Operator}
*
* @property {Object} field
* The field to which to apply the operator.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1.FieldReference}
*
* @typedef UnaryFilter
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.UnaryFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
UnaryFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A unary operator.
*
* @enum {number}
* @memberof google.firestore.v1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* Test if a field is equal to NaN.
*/
IS_NAN: 2,
/**
* Test if an exprestion evaluates to Null.
*/
IS_NULL: 3,
},
},
/**
* A reference to a field, such as `max(messages.time) as max_time`.
*
* @property {string} fieldPath
*
* @typedef FieldReference
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.FieldReference definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
FieldReference: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* An order on a field.
*
* @property {Object} field
* The field to order by.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1.FieldReference}
*
* @property {number} direction
* The direction to order by. Defaults to `ASCENDING`.
*
* The number should be among the values of [Direction]{@link google.firestore.v1.Direction}
*
* @typedef Order
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.Order definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
Order: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* The projection of document's fields to return.
*
* @property {Object[]} fields
* The fields to return.
*
* If empty, all fields are returned. To only return the name
* of the document, use `['__name__']`.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1.FieldReference}
*
* @typedef Projection
* @memberof google.firestore.v1
* @see [google.firestore.v1.StructuredQuery.Projection definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
Projection: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A sort direction.
*
* @enum {number}
* @memberof google.firestore.v1
*/
Direction: {
/**
* Unspecified.
*/
DIRECTION_UNSPECIFIED: 0,
/**
* Ascending.
*/
ASCENDING: 1,
/**
* Descending.
*/
DESCENDING: 2,
},
};
/**
* A position in a query result set.
*
* @property {Object[]} values
* The values that represent a position, in the order they appear in
* the order by clause of a query.
*
* Can contain fewer values than specified in the order by clause.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @property {boolean} before
* If the position is just before or just after the given values, relative
* to the sort order defined by the query.
*
* @typedef Cursor
* @memberof google.firestore.v1
* @see [google.firestore.v1.Cursor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/query.proto}
*/
const Cursor = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_query.js.map

View File

@ -0,0 +1,329 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A write on a document.
*
* @property {Object} update
* A document to write.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {string} delete
* A document name to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} transform
* Applies a transformation to a document.
* At most one `transform` per document is allowed in a given request.
* An `update` cannot follow a `transform` on the same document in a given
* request.
*
* This object should have the same structure as [DocumentTransform]{@link google.firestore.v1.DocumentTransform}
*
* @property {Object} updateMask
* The fields to update in this write.
*
* This field can be set only when the operation is `update`.
* If the mask is not set for an `update` and the document exists, any
* existing data will be overwritten.
* If the mask is set and the document on the server has fields not covered by
* the mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
* The field paths in this mask must not contain a reserved field name.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1.DocumentMask}
*
* @property {Object} currentDocument
* An optional precondition on the document.
*
* The write will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1.Precondition}
*
* @typedef Write
* @memberof google.firestore.v1
* @see [google.firestore.v1.Write definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const Write = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A transformation of a document.
*
* @property {string} document
* The name of the document to transform.
*
* @property {Object[]} fieldTransforms
* The list of transformations to apply to the fields of the document, in
* order.
* This must not be empty.
*
* This object should have the same structure as [FieldTransform]{@link google.firestore.v1.FieldTransform}
*
* @typedef DocumentTransform
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const DocumentTransform = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A transformation of a field of the document.
*
* @property {string} fieldPath
* The path of the field. See Document.fields for the field path syntax
* reference.
*
* @property {number} setToServerValue
* Sets the field to the given server value.
*
* The number should be among the values of [ServerValue]{@link google.firestore.v1.ServerValue}
*
* @property {Object} increment
* Adds the given value to the field's current value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the given value.
* If either of the given value or the current field value are doubles,
* both values will be interpreted as doubles. Double arithmetic and
* representation of double values follow IEEE 754 semantics.
* If there is positive/negative integer overflow, the field is resolved
* to the largest magnitude positive/negative integer.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @property {Object} maximum
* Sets the field to the maximum of its current value and the given value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the given value.
* If a maximum operation is applied where the field and the input value
* are of mixed types (that is - one is an integer and one is a double)
* the field takes on the type of the larger operand. If the operands are
* equivalent (e.g. 3 and 3.0), the field does not change.
* 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and
* zero input value is always the stored value.
* The maximum of any numeric value x and NaN is NaN.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @property {Object} minimum
* Sets the field to the minimum of its current value and the given value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the input value.
* If a minimum operation is applied where the field and the input value
* are of mixed types (that is - one is an integer and one is a double)
* the field takes on the type of the smaller operand. If the operands are
* equivalent (e.g. 3 and 3.0), the field does not change.
* 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and
* zero input value is always the stored value.
* The minimum of any numeric value x and NaN is NaN.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @property {Object} appendMissingElements
* Append the given elements in order if they are not already present in
* the current field value.
* If the field is not an array, or if the field does not yet exist, it is
* first set to the empty array.
*
* Equivalent numbers of different types (e.g. 3L and 3.0) are
* considered equal when checking if a value is missing.
* NaN is equal to NaN, and Null is equal to Null.
* If the input contains multiple equivalent values, only the first will
* be considered.
*
* The corresponding transform_result will be the null value.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1.ArrayValue}
*
* @property {Object} removeAllFromArray
* Remove all of the given elements from the array in the field.
* If the field is not an array, or if the field does not yet exist, it is
* set to the empty array.
*
* Equivalent numbers of the different types (e.g. 3L and 3.0) are
* considered equal when deciding whether an element should be removed.
* NaN is equal to NaN, and Null is equal to Null.
* This will remove all equivalent values if there are duplicates.
*
* The corresponding transform_result will be the null value.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1.ArrayValue}
*
* @typedef FieldTransform
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentTransform.FieldTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
FieldTransform: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A value that is calculated by the server.
*
* @enum {number}
* @memberof google.firestore.v1
*/
ServerValue: {
/**
* Unspecified. This value must not be used.
*/
SERVER_VALUE_UNSPECIFIED: 0,
/**
* The time at which the server processed the request, with millisecond
* precision.
*/
REQUEST_TIME: 1,
},
},
};
/**
* The result of applying a write.
*
* @property {Object} updateTime
* The last update time of the document after applying the write. Not set
* after a `delete`.
*
* If the write did not actually change the document, this will be the
* previous update_time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {Object[]} transformResults
* The results of applying each DocumentTransform.FieldTransform, in the
* same order.
*
* This object should have the same structure as [Value]{@link google.firestore.v1.Value}
*
* @typedef WriteResult
* @memberof google.firestore.v1
* @see [google.firestore.v1.WriteResult definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const WriteResult = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has changed.
*
* May be the result of multiple writes, including deletes, that
* ultimately resulted in a new value for the Document.
*
* Multiple DocumentChange messages may be returned for the same logical
* change, if multiple targets are affected.
*
* @property {Object} document
* The new state of the Document.
*
* If `mask` is set, contains only fields that were updated or added.
*
* This object should have the same structure as [Document]{@link google.firestore.v1.Document}
*
* @property {number[]} targetIds
* A set of target IDs of targets that match this document.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that no longer match this document.
*
* @typedef DocumentChange
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const DocumentChange = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has been deleted.
*
* May be the result of multiple writes, including updates, the
* last of which deleted the Document.
*
* Multiple DocumentDelete messages may be returned for the same logical
* delete, if multiple targets are affected.
*
* @property {string} document
* The resource name of the Document that was deleted.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that previously matched this entity.
*
* @property {Object} readTime
* The read timestamp at which the delete was observed.
*
* Greater or equal to the `commit_time` of the delete.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef DocumentDelete
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentDelete definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const DocumentDelete = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has been removed from the view of the targets.
*
* Sent if the document is no longer relevant to a target and is out of view.
* Can be sent instead of a DocumentDelete or a DocumentChange if the server
* can not send the new value of the document.
*
* Multiple DocumentRemove messages may be returned for the same logical
* write or delete, if multiple targets are affected.
*
* @property {string} document
* The resource name of the Document that has gone out of view.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that previously matched this document.
*
* @property {Object} readTime
* The read timestamp at which the remove was observed.
*
* Greater or equal to the `commit_time` of the change/delete/remove.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef DocumentRemove
* @memberof google.firestore.v1
* @see [google.firestore.v1.DocumentRemove definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const DocumentRemove = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A digest of all the documents that match a given target.
*
* @property {number} targetId
* The target ID to which this filter applies.
*
* @property {number} count
* The total count of documents that match target_id.
*
* If different from the count of documents in the client that match, the
* client must manually determine which documents no longer match the target.
*
* @typedef ExistenceFilter
* @memberof google.firestore.v1
* @see [google.firestore.v1.ExistenceFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1/write.proto}
*/
const ExistenceFilter = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_write.js.map

View File

@ -0,0 +1,63 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* This resource represents a long-running operation that is the result of a
* network API call.
*
* @property {string} name
* The server-assigned name, which is only unique within the same service that
* originally returns it. If you use the default HTTP mapping, the
* `name` should have the format of `operations/some/unique/name`.
*
* @property {Object} metadata
* Service-specific metadata associated with the operation. It typically
* contains progress information and common metadata such as create time.
* Some services might not provide such metadata. Any method that returns a
* long-running operation should document the metadata type, if any.
*
* This object should have the same structure as [Any]{@link google.protobuf.Any}
*
* @property {boolean} done
* If the value is `false`, it means the operation is still in progress.
* If `true`, the operation is completed, and either `error` or `response` is
* available.
*
* @property {Object} error
* The error result of the operation in case of failure or cancellation.
*
* This object should have the same structure as [Status]{@link google.rpc.Status}
*
* @property {Object} response
* The normal response of the operation in case of success. If the original
* method returns no data on success, such as `Delete`, the response is
* `google.protobuf.Empty`. If the original method is standard
* `Get`/`Create`/`Update`, the response should be the resource. For other
* methods, the response should have the type `XxxResponse`, where `Xxx`
* is the original method name. For example, if the original method name
* is `TakeSnapshot()`, the inferred response type is
* `TakeSnapshotResponse`.
*
* This object should have the same structure as [Any]{@link google.protobuf.Any}
*
* @typedef Operation
* @memberof google.longrunning
* @see [google.longrunning.Operation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/longrunning/operations.proto}
*/
const Operation = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_operations.js.map

View File

@ -0,0 +1,137 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := ptypes.MarshalAny(foo)
* ...
* foo := &pb.Foo{}
* if err := ptypes.UnmarshalAny(any, foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
*
* # JSON
*
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message google.protobuf.Duration):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
* @property {string} typeUrl
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a google.protobuf.Type
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
* @property {Buffer} value
* Must be a valid serialized protocol buffer of the above specified type.
*
* @typedef Any
* @memberof google.protobuf
* @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto}
*/
const Any = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_any.js.map

View File

@ -0,0 +1,34 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
* The JSON representation for `Empty` is empty JSON object `{}`.
* @typedef Empty
* @memberof google.protobuf
* @see [google.protobuf.Empty definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/empty.proto}
*/
const Empty = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_empty.js.map

View File

@ -0,0 +1,228 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* `FieldMask` represents a set of symbolic field paths, for example:
*
* paths: "f.a"
* paths: "f.b.d"
*
* Here `f` represents a field in some root message, `a` and `b`
* fields in the message found in `f`, and `d` a field found in the
* message in `f.b`.
*
* Field masks are used to specify a subset of fields that should be
* returned by a get operation or modified by an update operation.
* Field masks also have a custom JSON encoding (see below).
*
* # Field Masks in Projections
*
* When used in the context of a projection, a response message or
* sub-message is filtered by the API to only contain those fields as
* specified in the mask. For example, if the mask in the previous
* example is applied to a response message as follows:
*
* f {
* a : 22
* b {
* d : 1
* x : 2
* }
* y : 13
* }
* z: 8
*
* The result will not contain specific values for fields x,y and z
* (their value will be set to the default, and omitted in proto text
* output):
*
*
* f {
* a : 22
* b {
* d : 1
* }
* }
*
* A repeated field is not allowed except at the last position of a
* paths string.
*
* If a FieldMask object is not present in a get operation, the
* operation applies to all fields (as if a FieldMask of all fields
* had been specified).
*
* Note that a field mask does not necessarily apply to the
* top-level response message. In case of a REST get operation, the
* field mask applies directly to the response, but in case of a REST
* list operation, the mask instead applies to each individual message
* in the returned resource list. In case of a REST custom method,
* other definitions may be used. Where the mask applies will be
* clearly documented together with its declaration in the API. In
* any case, the effect on the returned resource/resources is required
* behavior for APIs.
*
* # Field Masks in Update Operations
*
* A field mask in update operations specifies which fields of the
* targeted resource are going to be updated. The API is required
* to only change the values of the fields as specified in the mask
* and leave the others untouched. If a resource is passed in to
* describe the updated values, the API ignores the values of all
* fields not covered by the mask.
*
* If a repeated field is specified for an update operation, new values will
* be appended to the existing repeated field in the target resource. Note that
* a repeated field is only allowed in the last position of a `paths` string.
*
* If a sub-message is specified in the last position of the field mask for an
* update operation, then new value will be merged into the existing sub-message
* in the target resource.
*
* For example, given the target message:
*
* f {
* b {
* d: 1
* x: 2
* }
* c: [1]
* }
*
* And an update message:
*
* f {
* b {
* d: 10
* }
* c: [2]
* }
*
* then if the field mask is:
*
* paths: ["f.b", "f.c"]
*
* then the result will be:
*
* f {
* b {
* d: 10
* x: 2
* }
* c: [1, 2]
* }
*
* An implementation may provide options to override this default behavior for
* repeated and message fields.
*
* In order to reset a field's value to the default, the field must
* be in the mask and set to the default value in the provided resource.
* Hence, in order to reset all fields of a resource, provide a default
* instance of the resource and set all fields in the mask, or do
* not provide a mask as described below.
*
* If a field mask is not present on update, the operation applies to
* all fields (as if a field mask of all fields has been specified).
* Note that in the presence of schema evolution, this may mean that
* fields the client does not know and has therefore not filled into
* the request will be reset to their default. If this is unwanted
* behavior, a specific service may require a client to always specify
* a field mask, producing an error if not.
*
* As with get operations, the location of the resource which
* describes the updated values in the request message depends on the
* operation kind. In any case, the effect of the field mask is
* required to be honored by the API.
*
* ## Considerations for HTTP REST
*
* The HTTP kind of an update operation which uses a field mask must
* be set to PATCH instead of PUT in order to satisfy HTTP semantics
* (PUT must only be used for full updates).
*
* # JSON Encoding of Field Masks
*
* In JSON, a field mask is encoded as a single string where paths are
* separated by a comma. Fields name in each path are converted
* to/from lower-camel naming conventions.
*
* As an example, consider the following message declarations:
*
* message Profile {
* User user = 1;
* Photo photo = 2;
* }
* message User {
* string display_name = 1;
* string address = 2;
* }
*
* In proto a field mask for `Profile` may look as such:
*
* mask {
* paths: "user.display_name"
* paths: "photo"
* }
*
* In JSON, the same mask is represented as below:
*
* {
* mask: "user.displayName,photo"
* }
*
* # Field Masks and Oneof Fields
*
* Field masks treat fields in oneofs just as regular fields. Consider the
* following message:
*
* message SampleMessage {
* oneof test_oneof {
* string name = 4;
* SubMessage sub_message = 9;
* }
* }
*
* The field mask can be:
*
* mask {
* paths: "name"
* }
*
* Or:
*
* mask {
* paths: "sub_message"
* }
*
* Note that oneof type names ("test_oneof" in this case) cannot be used in
* paths.
*
* ## Field Mask Verification
*
* The implementation of any API method which has a FieldMask type field in the
* request should verify the included field paths, and return an
* `INVALID_ARGUMENT` error if any path is duplicated or unmappable.
*
* @property {string[]} paths
* The set of field mask paths.
*
* @typedef FieldMask
* @memberof google.protobuf
* @see [google.protobuf.FieldMask definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto}
*/
const FieldMask = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_field_mask.js.map

View File

@ -0,0 +1,117 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
*
* Example 5: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](https://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D) to obtain a formatter capable of generating timestamps in this format.
*
* @property {number} seconds
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*
* @property {number} nanos
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*
* @typedef Timestamp
* @memberof google.protobuf
* @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto}
*/
const Timestamp = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_timestamp.js.map

View File

@ -0,0 +1,32 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* @property {number} value
* The int32 value.
*
* @typedef Int32Value
* @memberof google.protobuf
* @see [google.protobuf.Int32Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto}
*/
const Int32Value = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_wrappers.js.map

View File

@ -0,0 +1,95 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* The `Status` type defines a logical error model that is suitable for
* different programming environments, including REST APIs and RPC APIs. It is
* used by [gRPC](https://github.com/grpc). The error model is designed to be:
*
* - Simple to use and understand for most users
* - Flexible enough to meet unexpected needs
*
* # Overview
*
* The `Status` message contains three pieces of data: error code, error
* message, and error details. The error code should be an enum value of
* google.rpc.Code, but it may accept additional error codes
* if needed. The error message should be a developer-facing English message
* that helps developers *understand* and *resolve* the error. If a localized
* user-facing error message is needed, put the localized message in the error
* details or localize it in the client. The optional error details may contain
* arbitrary information about the error. There is a predefined set of error
* detail types in the package `google.rpc` that can be used for common error
* conditions.
*
* # Language mapping
*
* The `Status` message is the logical representation of the error model, but it
* is not necessarily the actual wire format. When the `Status` message is
* exposed in different client libraries and different wire protocols, it can be
* mapped differently. For example, it will likely be mapped to some exceptions
* in Java, but more likely mapped to some error codes in C.
*
* # Other uses
*
* The error model and the `Status` message can be used in a variety of
* environments, either with or without APIs, to provide a
* consistent developer experience across different environments.
*
* Example uses of this error model include:
*
* - Partial errors. If a service needs to return partial errors to the client,
* it may embed the `Status` in the normal response to indicate the partial
* errors.
*
* - Workflow errors. A typical workflow has multiple steps. Each step may
* have a `Status` message for error reporting.
*
* - Batch operations. If a client uses batch request and batch response, the
* `Status` message should be used directly inside batch response, one for
* each error sub-response.
*
* - Asynchronous operations. If an API call embeds asynchronous operation
* results in its response, the status of those operations should be
* represented directly using the `Status` message.
*
* - Logging. If some API errors are stored in logs, the message `Status` could
* be used directly after any stripping needed for security/privacy reasons.
*
* @property {number} code
* The status code, which should be an enum value of
* google.rpc.Code.
*
* @property {string} message
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized
* by the client.
*
* @property {Object[]} details
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*
* This object should have the same structure as [Any]{@link google.protobuf.Any}
*
* @typedef Status
* @memberof google.rpc
* @see [google.rpc.Status definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto}
*/
const Status = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_status.js.map

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,71 @@
{
"interfaces": {
"google.firestore.admin.v1.FirestoreAdmin": {
"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": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000
}
},
"methods": {
"CreateIndex": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"ListIndexes": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"GetIndex": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"DeleteIndex": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ImportDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"ExportDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"GetField": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListFields": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"UpdateField": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,101 @@
{
"interfaces": {
"google.firestore.v1.Firestore": {
"retry_codes": {
"idempotent": [
"DEADLINE_EXCEEDED",
"INTERNAL",
"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": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000
},
"streaming": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 300000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 300000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CreateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"UpdateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"DeleteDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"BatchGetDocuments": {
"timeout_millis": 300000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"BeginTransaction": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"Commit": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Rollback": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"RunQuery": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"Write": {
"timeout_millis": 86400000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "streaming"
},
"Listen": {
"timeout_millis": 86400000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"ListCollectionIds": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}

View File

@ -0,0 +1,20 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
'use strict';
const FirestoreClient = require('./firestore_client');
const FirestoreAdminClient = require('./firestore_admin_client');
FirestoreClient.FirestoreClient = FirestoreClient;
FirestoreClient.FirestoreAdminClient = FirestoreAdminClient;
module.exports = FirestoreClient;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,104 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A set of field paths on a document.
* Used to restrict a get or update operation on a document to a subset of its
* fields.
* This is different from standard field masks, as this is always scoped to a
* Document, and takes in account the dynamic nature of Value.
*
* @property {string[]} fieldPaths
* The list of field paths in the mask. See Document.fields for a field
* path syntax reference.
*
* @typedef DocumentMask
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentMask definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto}
*/
const DocumentMask = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A precondition on a document, used for conditional operations.
*
* @property {boolean} exists
* When set to `true`, the target document must exist.
* When set to `false`, the target document must not exist.
*
* @property {Object} updateTime
* When set, the target document must exist and have been last updated at
* that time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef Precondition
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Precondition definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto}
*/
const Precondition = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* Options for creating a new transaction.
*
* @property {Object} readOnly
* The transaction can only be used for read operations.
*
* This object should have the same structure as [ReadOnly]{@link google.firestore.v1beta1.ReadOnly}
*
* @property {Object} readWrite
* The transaction can be used for both read and write operations.
*
* This object should have the same structure as [ReadWrite]{@link google.firestore.v1beta1.ReadWrite}
*
* @typedef TransactionOptions
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.TransactionOptions definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto}
*/
const TransactionOptions = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* Options for a transaction that can be used to read and write documents.
*
* @property {Buffer} retryTransaction
* An optional transaction to retry.
*
* @typedef ReadWrite
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.TransactionOptions.ReadWrite definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto}
*/
ReadWrite: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* Options for a transaction that can only be used to read documents.
*
* @property {Object} readTime
* Reads documents at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef ReadOnly
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.TransactionOptions.ReadOnly definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/common.proto}
*/
ReadOnly: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
};
//# sourceMappingURL=doc_common.js.map

View File

@ -0,0 +1,177 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Firestore document.
*
* Must not exceed 1 MiB - 4 bytes.
*
* @property {string} name
* The resource name of the document, for example
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object.<string, Object>} fields
* The document's fields.
*
* The map keys represent field names.
*
* A simple field name contains only characters `a` to `z`, `A` to `Z`,
* `0` to `9`, or `_`, and must not start with `0` to `9`. For example,
* `foo_bar_17`.
*
* Field names matching the regular expression `__.*__` are reserved. Reserved
* field names are forbidden except in certain documented contexts. The map
* keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be
* empty.
*
* Field paths may be used in other contexts to refer to structured fields
* defined here. For `map_value`, the field path is represented by the simple
* or quoted field names of the containing fields, delimited by `.`. For
* example, the structured field
* `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be
* represented by the field path `foo.x&y`.
*
* Within a field path, a quoted field name starts and ends with `` ` `` and
* may contain any character. Some characters, including `` ` ``, must be
* escaped using a `\`. For example, `` `x&y` `` represents `x&y` and
* `` `bak\`tik` `` represents `` bak`tik ``.
*
* @property {Object} createTime
* Output only. The time at which the document was created.
*
* This value increases monotonically when a document is deleted then
* recreated. It can also be compared to values from other documents and
* the `read_time` of a query.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {Object} updateTime
* Output only. The time at which the document was last changed.
*
* This value is initially set to the `create_time` then increases
* monotonically with each change to the document. It can also be
* compared to values from other documents and the `read_time` of a query.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef Document
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Document definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto}
*/
const Document = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A message that can hold any of the supported value types.
*
* @property {number} nullValue
* A null value.
*
* The number should be among the values of [NullValue]{@link google.protobuf.NullValue}
*
* @property {boolean} booleanValue
* A boolean value.
*
* @property {number} integerValue
* An integer value.
*
* @property {number} doubleValue
* A double value.
*
* @property {Object} timestampValue
* A timestamp value.
*
* Precise only to microseconds. When stored, any additional precision is
* rounded down.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {string} stringValue
* A string value.
*
* The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes.
* Only the first 1,500 bytes of the UTF-8 representation are considered by
* queries.
*
* @property {Buffer} bytesValue
* A bytes value.
*
* Must not exceed 1 MiB - 89 bytes.
* Only the first 1,500 bytes are considered by queries.
*
* @property {string} referenceValue
* A reference to a document. For example:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} geoPointValue
* A geo point value representing a point on the surface of Earth.
*
* This object should have the same structure as [LatLng]{@link google.type.LatLng}
*
* @property {Object} arrayValue
* An array value.
*
* Cannot directly contain another array value, though can contain an
* map which contains another array.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1beta1.ArrayValue}
*
* @property {Object} mapValue
* A map value.
*
* This object should have the same structure as [MapValue]{@link google.firestore.v1beta1.MapValue}
*
* @typedef Value
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Value definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto}
*/
const Value = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* An array value.
*
* @property {Object[]} values
* Values in the array.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @typedef ArrayValue
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ArrayValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto}
*/
const ArrayValue = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A map value.
*
* @property {Object.<string, Object>} fields
* The map's fields.
*
* The map keys represent field names. Field names matching the regular
* expression `__.*__` are reserved. Reserved field names are forbidden except
* in certain documented contexts. The map keys, represented as UTF-8, must
* not exceed 1,500 bytes and cannot be empty.
*
* @typedef MapValue
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.MapValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/document.proto}
*/
const MapValue = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_document.js.map

View File

@ -0,0 +1,840 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* The request for Firestore.GetDocument.
*
* @property {string} name
* The resource name of the Document to get. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Buffer} transaction
* Reads the document in a transaction.
*
* @property {Object} readTime
* Reads the version of the document at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef GetDocumentRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.GetDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const GetDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.ListDocuments.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {string} collectionId
* The collection ID, relative to `parent`, to list. For example: `chatrooms`
* or `messages`.
*
* @property {number} pageSize
* The maximum number of documents to return.
*
* @property {string} pageToken
* The `next_page_token` value returned from a previous List request, if any.
*
* @property {string} orderBy
* The order to sort results by. For example: `priority desc, name`.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {boolean} showMissing
* If the list should show missing documents. A missing document is a
* document that does not exist but has sub-documents. These documents will
* be returned with a key but will not have fields, Document.create_time,
* or Document.update_time set.
*
* Requests with `show_missing` may not specify `where` or
* `order_by`.
*
* @typedef ListDocumentsRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.ListDocuments.
*
* @property {Object[]} documents
* The Documents found.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {string} nextPageToken
* The next page token.
*
* @typedef ListDocumentsResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListDocumentsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.CreateDocument.
*
* @property {string} parent
* The parent resource. For example:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}`
*
* @property {string} collectionId
* The collection ID, relative to `parent`, to list. For example: `chatrooms`.
*
* @property {string} documentId
* The client-assigned document ID to use for this document.
*
* Optional. If not specified, an ID will be assigned by the service.
*
* @property {Object} document
* The document to create. `name` must not be set.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @typedef CreateDocumentRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.CreateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const CreateDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.UpdateDocument.
*
* @property {Object} document
* The updated document.
* Creates the document if it does not already exist.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {Object} updateMask
* The fields to update.
* None of the field paths in the mask may contain a reserved name.
*
* If the document exists on the server and has fields not referenced in the
* mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If the document has a field that is not present in this mask, that field
* will not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Object} currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1beta1.Precondition}
*
* @typedef UpdateDocumentRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.UpdateDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const UpdateDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.DeleteDocument.
*
* @property {string} name
* The resource name of the Document to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} currentDocument
* An optional precondition on the document.
* The request will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1beta1.Precondition}
*
* @typedef DeleteDocumentRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DeleteDocumentRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const DeleteDocumentRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.BatchGetDocuments.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {string[]} documents
* The names of the documents to retrieve. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* The request will fail if any of the document is not a child resource of the
* given `database`. Duplicate names will be elided.
*
* @property {Object} mask
* The fields to return. If not set, returns all fields.
*
* If a document has a field that is not present in this mask, that field will
* not be returned in the response.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1beta1.TransactionOptions}
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef BatchGetDocumentsRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.BatchGetDocumentsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const BatchGetDocumentsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The streamed response for Firestore.BatchGetDocuments.
*
* @property {Object} found
* A document that was requested.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {string} missing
* A document name that was requested but does not exist. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Buffer} transaction
* The transaction that was started as part of this request.
* Will only be set in the first response, and only if
* BatchGetDocumentsRequest.new_transaction was set in the request.
*
* @property {Object} readTime
* The time at which the document was read.
* This may be monotically increasing, in this case the previous documents in
* the result stream are guaranteed not to have changed between their
* read_time and this one.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef BatchGetDocumentsResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.BatchGetDocumentsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const BatchGetDocumentsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.BeginTransaction.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object} options
* The options for the transaction.
* Defaults to a read-write transaction.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1beta1.TransactionOptions}
*
* @typedef BeginTransactionRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.BeginTransactionRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const BeginTransactionRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.BeginTransaction.
*
* @property {Buffer} transaction
* The transaction that was started.
*
* @typedef BeginTransactionResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.BeginTransactionResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const BeginTransactionResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Commit.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object[]} writes
* The writes to apply.
*
* Always executed atomically and in order.
*
* This object should have the same structure as [Write]{@link google.firestore.v1beta1.Write}
*
* @property {Buffer} transaction
* If set, applies all writes in this transaction, and commits it.
*
* @typedef CommitRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.CommitRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const CommitRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Commit.
*
* @property {Object[]} writeResults
* The result of applying the writes.
*
* This i-th write result corresponds to the i-th write in the
* request.
*
* This object should have the same structure as [WriteResult]{@link google.firestore.v1beta1.WriteResult}
*
* @property {Object} commitTime
* The time at which the commit occurred.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef CommitResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.CommitResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const CommitResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Rollback.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Buffer} transaction
* The transaction to roll back.
*
* @typedef RollbackRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.RollbackRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const RollbackRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.RunQuery.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {Object} structuredQuery
* A structured query.
*
* This object should have the same structure as [StructuredQuery]{@link google.firestore.v1beta1.StructuredQuery}
*
* @property {Buffer} transaction
* Reads documents in a transaction.
*
* @property {Object} newTransaction
* Starts a new transaction and reads the documents.
* Defaults to a read-only transaction.
* The new transaction ID will be returned as the first response in the
* stream.
*
* This object should have the same structure as [TransactionOptions]{@link google.firestore.v1beta1.TransactionOptions}
*
* @property {Object} readTime
* Reads documents as they were at the given time.
* This may not be older than 60 seconds.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef RunQueryRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.RunQueryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const RunQueryRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.RunQuery.
*
* @property {Buffer} transaction
* The transaction that was started as part of this request.
* Can only be set in the first response, and only if
* RunQueryRequest.new_transaction was set in the request.
* If set, no other fields will be set in this response.
*
* @property {Object} document
* A query result.
* Not set when reporting partial progress.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {Object} readTime
* The time at which the document was read. This may be monotonically
* increasing; in this case, the previous documents in the result stream are
* guaranteed not to have changed between their `read_time` and this one.
*
* If the query returns no results, a response with `read_time` and no
* `document` will be sent, and this represents the time at which the query
* was run.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {number} skippedResults
* The number of results that have been skipped due to an offset between
* the last response and the current response.
*
* @typedef RunQueryResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.RunQueryResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const RunQueryResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The request for Firestore.Write.
*
* The first request creates a stream, or resumes an existing one from a token.
*
* When creating a new stream, the server replies with a response containing
* only an ID and a token, to use in the next request.
*
* When resuming a stream, the server first streams any responses later than the
* given token, then a response containing only an up-to-date token, to use in
* the next request.
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
* This is only required in the first message.
*
* @property {string} streamId
* The ID of the write stream to resume.
* This may only be set in the first message. When left empty, a new write
* stream will be created.
*
* @property {Object[]} writes
* The writes to apply.
*
* Always executed atomically and in order.
* This must be empty on the first request.
* This may be empty on the last request.
* This must not be empty on all other requests.
*
* This object should have the same structure as [Write]{@link google.firestore.v1beta1.Write}
*
* @property {Buffer} streamToken
* A stream token that was previously sent by the server.
*
* The client should set this field to the token from the most recent
* WriteResponse it has received. This acknowledges that the client has
* received responses up to this token. After sending this token, earlier
* tokens may not be used anymore.
*
* The server may close the stream if there are too many unacknowledged
* responses.
*
* Leave this field unset when creating a new stream. To resume a stream at
* a specific point, set this field and the `stream_id` field.
*
* Leave this field unset when creating a new stream.
*
* @property {Object.<string, string>} labels
* Labels associated with this write request.
*
* @typedef WriteRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.WriteRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const WriteRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Write.
*
* @property {string} streamId
* The ID of the stream.
* Only set on the first message, when a new stream was created.
*
* @property {Buffer} streamToken
* A token that represents the position of this response in the stream.
* This can be used by a client to resume the stream at this point.
*
* This field is always set.
*
* @property {Object[]} writeResults
* The result of applying the writes.
*
* This i-th write result corresponds to the i-th write in the
* request.
*
* This object should have the same structure as [WriteResult]{@link google.firestore.v1beta1.WriteResult}
*
* @property {Object} commitTime
* The time at which the commit occurred.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef WriteResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.WriteResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const WriteResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A request for Firestore.Listen
*
* @property {string} database
* The database name. In the format:
* `projects/{project_id}/databases/{database_id}`.
*
* @property {Object} addTarget
* A target to add to this stream.
*
* This object should have the same structure as [Target]{@link google.firestore.v1beta1.Target}
*
* @property {number} removeTarget
* The ID of a target to remove from this stream.
*
* @property {Object.<string, string>} labels
* Labels associated with this target change.
*
* @typedef ListenRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListenRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListenRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response for Firestore.Listen.
*
* @property {Object} targetChange
* Targets have changed.
*
* This object should have the same structure as [TargetChange]{@link google.firestore.v1beta1.TargetChange}
*
* @property {Object} documentChange
* A Document has changed.
*
* This object should have the same structure as [DocumentChange]{@link google.firestore.v1beta1.DocumentChange}
*
* @property {Object} documentDelete
* A Document has been deleted.
*
* This object should have the same structure as [DocumentDelete]{@link google.firestore.v1beta1.DocumentDelete}
*
* @property {Object} documentRemove
* A Document has been removed from a target (because it is no longer
* relevant to that target).
*
* This object should have the same structure as [DocumentRemove]{@link google.firestore.v1beta1.DocumentRemove}
*
* @property {Object} filter
* A filter to apply to the set of documents previously returned for the
* given target.
*
* Returned when documents may have been removed from the given target, but
* the exact documents are unknown.
*
* This object should have the same structure as [ExistenceFilter]{@link google.firestore.v1beta1.ExistenceFilter}
*
* @typedef ListenResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListenResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListenResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A specification of a set of documents to listen to.
*
* @property {Object} query
* A target specified by a query.
*
* This object should have the same structure as [QueryTarget]{@link google.firestore.v1beta1.QueryTarget}
*
* @property {Object} documents
* A target specified by a set of document names.
*
* This object should have the same structure as [DocumentsTarget]{@link google.firestore.v1beta1.DocumentsTarget}
*
* @property {Buffer} resumeToken
* A resume token from a prior TargetChange for an identical target.
*
* Using a resume token with a different target is unsupported and may fail.
*
* @property {Object} readTime
* Start listening after a specific `read_time`.
*
* The client must know the state of matching documents at this time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {number} targetId
* A client provided target ID.
*
* If not set, the server will assign an ID for the target.
*
* Used for resuming a target without changing IDs. The IDs can either be
* client-assigned or be server-assigned in a previous stream. All targets
* with client provided IDs must be added before adding a target that needs
* a server-assigned id.
*
* @property {boolean} once
* If the target should be removed once it is current and consistent.
*
* @typedef Target
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Target definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const Target = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A target specified by a set of documents names.
*
* @property {string[]} documents
* The names of the documents to retrieve. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* The request will fail if any of the document is not a child resource of
* the given `database`. Duplicate names will be elided.
*
* @typedef DocumentsTarget
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Target.DocumentsTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
DocumentsTarget: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A target specified by a query.
*
* @property {string} parent
* The parent resource name. In the format:
* `projects/{project_id}/databases/{database_id}/documents` or
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents` or
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {Object} structuredQuery
* A structured query.
*
* This object should have the same structure as [StructuredQuery]{@link google.firestore.v1beta1.StructuredQuery}
*
* @typedef QueryTarget
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Target.QueryTarget definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
QueryTarget: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
};
/**
* Targets being watched have changed.
*
* @property {number} targetChangeType
* The type of change that occurred.
*
* The number should be among the values of [TargetChangeType]{@link google.firestore.v1beta1.TargetChangeType}
*
* @property {number[]} targetIds
* The target IDs of targets that have changed.
*
* If empty, the change applies to all targets.
*
* For `target_change_type=ADD`, the order of the target IDs matches the order
* of the requests to add the targets. This allows clients to unambiguously
* associate server-assigned target IDs with added targets.
*
* For other states, the order of the target IDs is not defined.
*
* @property {Object} cause
* The error that resulted in this change, if applicable.
*
* This object should have the same structure as [Status]{@link google.rpc.Status}
*
* @property {Buffer} resumeToken
* A token that can be used to resume the stream for the given `target_ids`,
* or all targets if `target_ids` is empty.
*
* Not set on every target change.
*
* @property {Object} readTime
* The consistent `read_time` for the given `target_ids` (omitted when the
* target_ids are not at a consistent snapshot).
*
* The stream is guaranteed to send a `read_time` with `target_ids` empty
* whenever the entire stream reaches a new consistent snapshot. ADD,
* CURRENT, and RESET messages are guaranteed to (eventually) result in a
* new consistent snapshot (while NO_CHANGE and REMOVE messages are not).
*
* For a given stream, `read_time` is guaranteed to be monotonically
* increasing.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef TargetChange
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.TargetChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const TargetChange = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* The type of change.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
TargetChangeType: {
/**
* No change has occurred. Used only to send an updated `resume_token`.
*/
NO_CHANGE: 0,
/**
* The targets have been added.
*/
ADD: 1,
/**
* The targets have been removed.
*/
REMOVE: 2,
/**
* The targets reflect all changes committed before the targets were added
* to the stream.
*
* This will be sent after or with a `read_time` that is greater than or
* equal to the time at which the targets were added.
*
* Listeners can wait for this change if read-after-write semantics
* are desired.
*/
CURRENT: 3,
/**
* The targets have been reset, and a new initial state for the targets
* will be returned in subsequent changes.
*
* After the initial state is complete, `CURRENT` will be returned even
* if the target was previously indicated to be `CURRENT`.
*/
RESET: 4,
},
};
/**
* The request for Firestore.ListCollectionIds.
*
* @property {string} parent
* The parent document. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
* For example:
* `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom`
*
* @property {number} pageSize
* The maximum number of results to return.
*
* @property {string} pageToken
* A page token. Must be a value from
* ListCollectionIdsResponse.
*
* @typedef ListCollectionIdsRequest
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListCollectionIdsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListCollectionIdsRequest = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* The response from Firestore.ListCollectionIds.
*
* @property {string[]} collectionIds
* The collection ids.
*
* @property {string} nextPageToken
* A page token that may be used to continue the list.
*
* @typedef ListCollectionIdsResponse
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ListCollectionIdsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/firestore.proto}
*/
const ListCollectionIdsResponse = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_firestore.js.map

View File

@ -0,0 +1,363 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Firestore query.
*
* @property {Object} select
* The projection to return.
*
* This object should have the same structure as [Projection]{@link google.firestore.v1beta1.Projection}
*
* @property {Object[]} from
* The collections to query.
*
* This object should have the same structure as [CollectionSelector]{@link google.firestore.v1beta1.CollectionSelector}
*
* @property {Object} where
* The filter to apply.
*
* This object should have the same structure as [Filter]{@link google.firestore.v1beta1.Filter}
*
* @property {Object[]} orderBy
* The order to apply to the query results.
*
* Firestore guarantees a stable ordering through the following rules:
*
* * Any field required to appear in `order_by`, that is not already
* specified in `order_by`, is appended to the order in field name order
* by default.
* * If an order on `__name__` is not specified, it is appended by default.
*
* Fields are appended with the same sort direction as the last order
* specified, or 'ASCENDING' if no order was specified. For example:
*
* * `SELECT * FROM Foo ORDER BY A` becomes
* `SELECT * FROM Foo ORDER BY A, __name__`
* * `SELECT * FROM Foo ORDER BY A DESC` becomes
* `SELECT * FROM Foo ORDER BY A DESC, __name__ DESC`
* * `SELECT * FROM Foo WHERE A > 1` becomes
* `SELECT * FROM Foo WHERE A > 1 ORDER BY A, __name__`
*
* This object should have the same structure as [Order]{@link google.firestore.v1beta1.Order}
*
* @property {Object} startAt
* A starting point for the query results.
*
* This object should have the same structure as [Cursor]{@link google.firestore.v1beta1.Cursor}
*
* @property {Object} endAt
* A end point for the query results.
*
* This object should have the same structure as [Cursor]{@link google.firestore.v1beta1.Cursor}
*
* @property {number} offset
* The number of results to skip.
*
* Applies before limit, but after all other constraints. Must be >= 0 if
* specified.
*
* @property {Object} limit
* The maximum number of results to return.
*
* Applies after all other constraints.
* Must be >= 0 if specified.
*
* This object should have the same structure as [Int32Value]{@link google.protobuf.Int32Value}
*
* @typedef StructuredQuery
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
const StructuredQuery = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A selection of a collection, such as `messages as m1`.
*
* @property {string} collectionId
* The collection ID.
* When set, selects only collections with this ID.
*
* @property {boolean} allDescendants
* When false, selects only collections that are immediate children of
* the `parent` specified in the containing `RunQueryRequest`.
* When true, selects all descendant collections.
*
* @typedef CollectionSelector
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.CollectionSelector definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
CollectionSelector: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A filter.
*
* @property {Object} compositeFilter
* A composite filter.
*
* This object should have the same structure as [CompositeFilter]{@link google.firestore.v1beta1.CompositeFilter}
*
* @property {Object} fieldFilter
* A filter on a document field.
*
* This object should have the same structure as [FieldFilter]{@link google.firestore.v1beta1.FieldFilter}
*
* @property {Object} unaryFilter
* A filter that takes exactly one argument.
*
* This object should have the same structure as [UnaryFilter]{@link google.firestore.v1beta1.UnaryFilter}
*
* @typedef Filter
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.Filter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
Filter: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A filter that merges multiple other filters using the given operator.
*
* @property {number} op
* The operator for combining multiple filters.
*
* The number should be among the values of [Operator]{@link google.firestore.v1beta1.Operator}
*
* @property {Object[]} filters
* The list of filters to combine.
* Must contain at least one filter.
*
* This object should have the same structure as [Filter]{@link google.firestore.v1beta1.Filter}
*
* @typedef CompositeFilter
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.CompositeFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
CompositeFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A composite filter operator.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* The results are required to satisfy each of the combined filters.
*/
AND: 1,
},
},
/**
* A filter on a specific field.
*
* @property {Object} field
* The field to filter by.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1beta1.FieldReference}
*
* @property {number} op
* The operator to filter by.
*
* The number should be among the values of [Operator]{@link google.firestore.v1beta1.Operator}
*
* @property {Object} value
* The value to compare to.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @typedef FieldFilter
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.FieldFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
FieldFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A field filter operator.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* Less than. Requires that the field come first in `order_by`.
*/
LESS_THAN: 1,
/**
* Less than or equal. Requires that the field come first in `order_by`.
*/
LESS_THAN_OR_EQUAL: 2,
/**
* Greater than. Requires that the field come first in `order_by`.
*/
GREATER_THAN: 3,
/**
* Greater than or equal. Requires that the field come first in
* `order_by`.
*/
GREATER_THAN_OR_EQUAL: 4,
/**
* Equal.
*/
EQUAL: 5,
/**
* Contains. Requires that the field is an array.
*/
ARRAY_CONTAINS: 7,
},
},
/**
* The projection of document's fields to return.
*
* @property {Object[]} fields
* The fields to return.
*
* If empty, all fields are returned. To only return the name
* of the document, use `['__name__']`.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1beta1.FieldReference}
*
* @typedef Projection
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.Projection definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
Projection: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A filter with a single operand.
*
* @property {number} op
* The unary operator to apply.
*
* The number should be among the values of [Operator]{@link google.firestore.v1beta1.Operator}
*
* @property {Object} field
* The field to which to apply the operator.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1beta1.FieldReference}
*
* @typedef UnaryFilter
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.UnaryFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
UnaryFilter: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A unary operator.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
Operator: {
/**
* Unspecified. This value must not be used.
*/
OPERATOR_UNSPECIFIED: 0,
/**
* Test if a field is equal to NaN.
*/
IS_NAN: 2,
/**
* Test if an exprestion evaluates to Null.
*/
IS_NULL: 3,
},
},
/**
* An order on a field.
*
* @property {Object} field
* The field to order by.
*
* This object should have the same structure as [FieldReference]{@link google.firestore.v1beta1.FieldReference}
*
* @property {number} direction
* The direction to order by. Defaults to `ASCENDING`.
*
* The number should be among the values of [Direction]{@link google.firestore.v1beta1.Direction}
*
* @typedef Order
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.Order definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
Order: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A reference to a field, such as `max(messages.time) as max_time`.
*
* @property {string} fieldPath
*
* @typedef FieldReference
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.StructuredQuery.FieldReference definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
FieldReference: {
// This is for documentation. Actual contents will be loaded by gRPC.
},
/**
* A sort direction.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
Direction: {
/**
* Unspecified.
*/
DIRECTION_UNSPECIFIED: 0,
/**
* Ascending.
*/
ASCENDING: 1,
/**
* Descending.
*/
DESCENDING: 2,
},
};
/**
* A position in a query result set.
*
* @property {Object[]} values
* The values that represent a position, in the order they appear in
* the order by clause of a query.
*
* Can contain fewer values than specified in the order by clause.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @property {boolean} before
* If the position is just before or just after the given values, relative
* to the sort order defined by the query.
*
* @typedef Cursor
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Cursor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/query.proto}
*/
const Cursor = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_query.js.map

View File

@ -0,0 +1,329 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A write on a document.
*
* @property {Object} update
* A document to write.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {string} delete
* A document name to delete. In the format:
* `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
*
* @property {Object} transform
* Applies a transformation to a document.
* At most one `transform` per document is allowed in a given request.
* An `update` cannot follow a `transform` on the same document in a given
* request.
*
* This object should have the same structure as [DocumentTransform]{@link google.firestore.v1beta1.DocumentTransform}
*
* @property {Object} updateMask
* The fields to update in this write.
*
* This field can be set only when the operation is `update`.
* If the mask is not set for an `update` and the document exists, any
* existing data will be overwritten.
* If the mask is set and the document on the server has fields not covered by
* the mask, they are left unchanged.
* Fields referenced in the mask, but not present in the input document, are
* deleted from the document on the server.
* The field paths in this mask must not contain a reserved field name.
*
* This object should have the same structure as [DocumentMask]{@link google.firestore.v1beta1.DocumentMask}
*
* @property {Object} currentDocument
* An optional precondition on the document.
*
* The write will fail if this is set and not met by the target document.
*
* This object should have the same structure as [Precondition]{@link google.firestore.v1beta1.Precondition}
*
* @typedef Write
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.Write definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const Write = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A transformation of a document.
*
* @property {string} document
* The name of the document to transform.
*
* @property {Object[]} fieldTransforms
* The list of transformations to apply to the fields of the document, in
* order.
* This must not be empty.
*
* This object should have the same structure as [FieldTransform]{@link google.firestore.v1beta1.FieldTransform}
*
* @typedef DocumentTransform
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const DocumentTransform = {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A transformation of a field of the document.
*
* @property {string} fieldPath
* The path of the field. See Document.fields for the field path syntax
* reference.
*
* @property {number} setToServerValue
* Sets the field to the given server value.
*
* The number should be among the values of [ServerValue]{@link google.firestore.v1beta1.ServerValue}
*
* @property {Object} increment
* Adds the given value to the field's current value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the given value.
* If either of the given value or the current field value are doubles,
* both values will be interpreted as doubles. Double arithmetic and
* representation of double values follow IEEE 754 semantics.
* If there is positive/negative integer overflow, the field is resolved
* to the largest magnitude positive/negative integer.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @property {Object} maximum
* Sets the field to the maximum of its current value and the given value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the given value.
* If a maximum operation is applied where the field and the input value
* are of mixed types (that is - one is an integer and one is a double)
* the field takes on the type of the larger operand. If the operands are
* equivalent (e.g. 3 and 3.0), the field does not change.
* 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and
* zero input value is always the stored value.
* The maximum of any numeric value x and NaN is NaN.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @property {Object} minimum
* Sets the field to the minimum of its current value and the given value.
*
* This must be an integer or a double value.
* If the field is not an integer or double, or if the field does not yet
* exist, the transformation will set the field to the input value.
* If a minimum operation is applied where the field and the input value
* are of mixed types (that is - one is an integer and one is a double)
* the field takes on the type of the smaller operand. If the operands are
* equivalent (e.g. 3 and 3.0), the field does not change.
* 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and
* zero input value is always the stored value.
* The minimum of any numeric value x and NaN is NaN.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @property {Object} appendMissingElements
* Append the given elements in order if they are not already present in
* the current field value.
* If the field is not an array, or if the field does not yet exist, it is
* first set to the empty array.
*
* Equivalent numbers of different types (e.g. 3L and 3.0) are
* considered equal when checking if a value is missing.
* NaN is equal to NaN, and Null is equal to Null.
* If the input contains multiple equivalent values, only the first will
* be considered.
*
* The corresponding transform_result will be the null value.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1beta1.ArrayValue}
*
* @property {Object} removeAllFromArray
* Remove all of the given elements from the array in the field.
* If the field is not an array, or if the field does not yet exist, it is
* set to the empty array.
*
* Equivalent numbers of the different types (e.g. 3L and 3.0) are
* considered equal when deciding whether an element should be removed.
* NaN is equal to NaN, and Null is equal to Null.
* This will remove all equivalent values if there are duplicates.
*
* The corresponding transform_result will be the null value.
*
* This object should have the same structure as [ArrayValue]{@link google.firestore.v1beta1.ArrayValue}
*
* @typedef FieldTransform
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentTransform.FieldTransform definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
FieldTransform: {
// This is for documentation. Actual contents will be loaded by gRPC.
/**
* A value that is calculated by the server.
*
* @enum {number}
* @memberof google.firestore.v1beta1
*/
ServerValue: {
/**
* Unspecified. This value must not be used.
*/
SERVER_VALUE_UNSPECIFIED: 0,
/**
* The time at which the server processed the request, with millisecond
* precision.
*/
REQUEST_TIME: 1,
},
},
};
/**
* The result of applying a write.
*
* @property {Object} updateTime
* The last update time of the document after applying the write. Not set
* after a `delete`.
*
* If the write did not actually change the document, this will be the
* previous update_time.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @property {Object[]} transformResults
* The results of applying each DocumentTransform.FieldTransform, in the
* same order.
*
* This object should have the same structure as [Value]{@link google.firestore.v1beta1.Value}
*
* @typedef WriteResult
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.WriteResult definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const WriteResult = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has changed.
*
* May be the result of multiple writes, including deletes, that
* ultimately resulted in a new value for the Document.
*
* Multiple DocumentChange messages may be returned for the same logical
* change, if multiple targets are affected.
*
* @property {Object} document
* The new state of the Document.
*
* If `mask` is set, contains only fields that were updated or added.
*
* This object should have the same structure as [Document]{@link google.firestore.v1beta1.Document}
*
* @property {number[]} targetIds
* A set of target IDs of targets that match this document.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that no longer match this document.
*
* @typedef DocumentChange
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentChange definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const DocumentChange = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has been deleted.
*
* May be the result of multiple writes, including updates, the
* last of which deleted the Document.
*
* Multiple DocumentDelete messages may be returned for the same logical
* delete, if multiple targets are affected.
*
* @property {string} document
* The resource name of the Document that was deleted.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that previously matched this entity.
*
* @property {Object} readTime
* The read timestamp at which the delete was observed.
*
* Greater or equal to the `commit_time` of the delete.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef DocumentDelete
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentDelete definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const DocumentDelete = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A Document has been removed from the view of the targets.
*
* Sent if the document is no longer relevant to a target and is out of view.
* Can be sent instead of a DocumentDelete or a DocumentChange if the server
* can not send the new value of the document.
*
* Multiple DocumentRemove messages may be returned for the same logical
* write or delete, if multiple targets are affected.
*
* @property {string} document
* The resource name of the Document that has gone out of view.
*
* @property {number[]} removedTargetIds
* A set of target IDs for targets that previously matched this document.
*
* @property {Object} readTime
* The read timestamp at which the remove was observed.
*
* Greater or equal to the `commit_time` of the change/delete/remove.
*
* This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp}
*
* @typedef DocumentRemove
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.DocumentRemove definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const DocumentRemove = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
/**
* A digest of all the documents that match a given target.
*
* @property {number} targetId
* The target ID to which this filter applies.
*
* @property {number} count
* The total count of documents that match target_id.
*
* If different from the count of documents in the client that match, the
* client must manually determine which documents no longer match the target.
*
* @typedef ExistenceFilter
* @memberof google.firestore.v1beta1
* @see [google.firestore.v1beta1.ExistenceFilter definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/firestore/v1beta1/write.proto}
*/
const ExistenceFilter = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_write.js.map

View File

@ -0,0 +1,137 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* `Any` contains an arbitrary serialized protocol buffer message along with a
* URL that describes the type of the serialized message.
*
* Protobuf library provides support to pack/unpack Any values in the form
* of utility functions or additional generated methods of the Any type.
*
* Example 1: Pack and unpack a message in C++.
*
* Foo foo = ...;
* Any any;
* any.PackFrom(foo);
* ...
* if (any.UnpackTo(&foo)) {
* ...
* }
*
* Example 2: Pack and unpack a message in Java.
*
* Foo foo = ...;
* Any any = Any.pack(foo);
* ...
* if (any.is(Foo.class)) {
* foo = any.unpack(Foo.class);
* }
*
* Example 3: Pack and unpack a message in Python.
*
* foo = Foo(...)
* any = Any()
* any.Pack(foo)
* ...
* if any.Is(Foo.DESCRIPTOR):
* any.Unpack(foo)
* ...
*
* Example 4: Pack and unpack a message in Go
*
* foo := &pb.Foo{...}
* any, err := ptypes.MarshalAny(foo)
* ...
* foo := &pb.Foo{}
* if err := ptypes.UnmarshalAny(any, foo); err != nil {
* ...
* }
*
* The pack methods provided by protobuf library will by default use
* 'type.googleapis.com/full.type.name' as the type URL and the unpack
* methods only use the fully qualified type name after the last '/'
* in the type URL, for example "foo.bar.com/x/y.z" will yield type
* name "y.z".
*
*
* # JSON
*
* The JSON representation of an `Any` value uses the regular
* representation of the deserialized, embedded message, with an
* additional field `@type` which contains the type URL. Example:
*
* package google.profile;
* message Person {
* string first_name = 1;
* string last_name = 2;
* }
*
* {
* "@type": "type.googleapis.com/google.profile.Person",
* "firstName": <string>,
* "lastName": <string>
* }
*
* If the embedded message type is well-known and has a custom JSON
* representation, that representation will be embedded adding a field
* `value` which holds the custom JSON in addition to the `@type`
* field. Example (for message google.protobuf.Duration):
*
* {
* "@type": "type.googleapis.com/google.protobuf.Duration",
* "value": "1.212s"
* }
*
* @property {string} typeUrl
* A URL/resource name that uniquely identifies the type of the serialized
* protocol buffer message. This string must contain at least
* one "/" character. The last segment of the URL's path must represent
* the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form
* (e.g., leading "." is not accepted).
*
* In practice, teams usually precompile into the binary all types that they
* expect it to use in the context of Any. However, for URLs which use the
* scheme `http`, `https`, or no scheme, one can optionally set up a type
* server that maps type URLs to message definitions as follows:
*
* * If no scheme is provided, `https` is assumed.
* * An HTTP GET on the URL must yield a google.protobuf.Type
* value in binary format, or produce an error.
* * Applications are allowed to cache lookup results based on the
* URL, or have them precompiled into a binary to avoid any
* lookup. Therefore, binary compatibility needs to be preserved
* on changes to types. (Use versioned type names to manage
* breaking changes.)
*
* Note: this functionality is not currently available in the official
* protobuf release, and it is not used for type URLs beginning with
* type.googleapis.com.
*
* Schemes other than `http`, `https` (or the empty scheme) might be
* used with implementation specific semantics.
*
* @property {Buffer} value
* Must be a valid serialized protocol buffer of the above specified type.
*
* @typedef Any
* @memberof google.protobuf
* @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto}
*/
const Any = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_any.js.map

View File

@ -0,0 +1,34 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A generic empty message that you can re-use to avoid defining duplicated
* empty messages in your APIs. A typical example is to use it as the request
* or the response type of an API method. For instance:
*
* service Foo {
* rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
* }
*
* The JSON representation for `Empty` is empty JSON object `{}`.
* @typedef Empty
* @memberof google.protobuf
* @see [google.protobuf.Empty definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/empty.proto}
*/
const Empty = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_empty.js.map

View File

@ -0,0 +1,117 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* A Timestamp represents a point in time independent of any time zone or local
* calendar, encoded as a count of seconds and fractions of seconds at
* nanosecond resolution. The count is relative to an epoch at UTC midnight on
* January 1, 1970, in the proleptic Gregorian calendar which extends the
* Gregorian calendar backwards to year one.
*
* All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
* second table is needed for interpretation, using a [24-hour linear
* smear](https://developers.google.com/time/smear).
*
* The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
* restricting to that range, we ensure that we can convert to and from [RFC
* 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
*
* # Examples
*
* Example 1: Compute Timestamp from POSIX `time()`.
*
* Timestamp timestamp;
* timestamp.set_seconds(time(NULL));
* timestamp.set_nanos(0);
*
* Example 2: Compute Timestamp from POSIX `gettimeofday()`.
*
* struct timeval tv;
* gettimeofday(&tv, NULL);
*
* Timestamp timestamp;
* timestamp.set_seconds(tv.tv_sec);
* timestamp.set_nanos(tv.tv_usec * 1000);
*
* Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
*
* FILETIME ft;
* GetSystemTimeAsFileTime(&ft);
* UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
*
* // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
* // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
* Timestamp timestamp;
* timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
* timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
*
* Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
*
* long millis = System.currentTimeMillis();
*
* Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
* .setNanos((int) ((millis % 1000) * 1000000)).build();
*
*
* Example 5: Compute Timestamp from current time in Python.
*
* timestamp = Timestamp()
* timestamp.GetCurrentTime()
*
* # JSON Mapping
*
* In JSON format, the Timestamp type is encoded as a string in the
* [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
* format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
* where {year} is always expressed using four digits while {month}, {day},
* {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
* seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
* are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
* is required. A proto3 JSON serializer should always use UTC (as indicated by
* "Z") when printing the Timestamp type and a proto3 JSON parser should be
* able to accept both UTC and other timezones (as indicated by an offset).
*
* For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
* 01:30 UTC on January 15, 2017.
*
* In JavaScript, one can convert a Date object to this format using the
* standard
* [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
* method. In Python, a standard `datetime.datetime` object can be converted
* to this format using
* [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
* the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
* the Joda Time's [`ISODateTimeFormat.dateTime()`](https://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D) to obtain a formatter capable of generating timestamps in this format.
*
* @property {number} seconds
* Represents seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
*
* @property {number} nanos
* Non-negative fractions of a second at nanosecond resolution. Negative
* second values with fractions must still have non-negative nanos values
* that count forward in time. Must be from 0 to 999,999,999
* inclusive.
*
* @typedef Timestamp
* @memberof google.protobuf
* @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto}
*/
const Timestamp = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_timestamp.js.map

View File

@ -0,0 +1,32 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* Wrapper message for `int32`.
*
* The JSON representation for `Int32Value` is JSON number.
*
* @property {number} value
* The int32 value.
*
* @typedef Int32Value
* @memberof google.protobuf
* @see [google.protobuf.Int32Value definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/wrappers.proto}
*/
const Int32Value = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_wrappers.js.map

View File

@ -0,0 +1,95 @@
"use strict";
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
// Note: this file is purely for documentation. Any contents are not expected
// to be loaded as the JS file.
/**
* The `Status` type defines a logical error model that is suitable for
* different programming environments, including REST APIs and RPC APIs. It is
* used by [gRPC](https://github.com/grpc). The error model is designed to be:
*
* - Simple to use and understand for most users
* - Flexible enough to meet unexpected needs
*
* # Overview
*
* The `Status` message contains three pieces of data: error code, error
* message, and error details. The error code should be an enum value of
* google.rpc.Code, but it may accept additional error codes
* if needed. The error message should be a developer-facing English message
* that helps developers *understand* and *resolve* the error. If a localized
* user-facing error message is needed, put the localized message in the error
* details or localize it in the client. The optional error details may contain
* arbitrary information about the error. There is a predefined set of error
* detail types in the package `google.rpc` that can be used for common error
* conditions.
*
* # Language mapping
*
* The `Status` message is the logical representation of the error model, but it
* is not necessarily the actual wire format. When the `Status` message is
* exposed in different client libraries and different wire protocols, it can be
* mapped differently. For example, it will likely be mapped to some exceptions
* in Java, but more likely mapped to some error codes in C.
*
* # Other uses
*
* The error model and the `Status` message can be used in a variety of
* environments, either with or without APIs, to provide a
* consistent developer experience across different environments.
*
* Example uses of this error model include:
*
* - Partial errors. If a service needs to return partial errors to the client,
* it may embed the `Status` in the normal response to indicate the partial
* errors.
*
* - Workflow errors. A typical workflow has multiple steps. Each step may
* have a `Status` message for error reporting.
*
* - Batch operations. If a client uses batch request and batch response, the
* `Status` message should be used directly inside batch response, one for
* each error sub-response.
*
* - Asynchronous operations. If an API call embeds asynchronous operation
* results in its response, the status of those operations should be
* represented directly using the `Status` message.
*
* - Logging. If some API errors are stored in logs, the message `Status` could
* be used directly after any stripping needed for security/privacy reasons.
*
* @property {number} code
* The status code, which should be an enum value of
* google.rpc.Code.
*
* @property {string} message
* A developer-facing error message, which should be in English. Any
* user-facing error message should be localized and sent in the
* google.rpc.Status.details field, or localized
* by the client.
*
* @property {Object[]} details
* A list of messages that carry the error details. There is a common set of
* message types for APIs to use.
*
* This object should have the same structure as [Any]{@link google.protobuf.Any}
*
* @typedef Status
* @memberof google.rpc
* @see [google.rpc.Status definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto}
*/
const Status = {
// This is for documentation. Actual contents will be loaded by gRPC.
};
//# sourceMappingURL=doc_status.js.map

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,100 @@
{
"interfaces": {
"google.firestore.v1beta1.Firestore": {
"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": 20000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 20000,
"total_timeout_millis": 600000
},
"streaming": {
"initial_retry_delay_millis": 100,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 300000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 300000,
"total_timeout_millis": 600000
}
},
"methods": {
"GetDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"ListDocuments": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"CreateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"UpdateDocument": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"DeleteDocument": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"BatchGetDocuments": {
"timeout_millis": 300000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"BeginTransaction": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"Commit": {
"timeout_millis": 60000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "default"
},
"Rollback": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
},
"RunQuery": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"Write": {
"timeout_millis": 86400000,
"retry_codes_name": "non_idempotent",
"retry_params_name": "streaming"
},
"Listen": {
"timeout_millis": 86400000,
"retry_codes_name": "idempotent",
"retry_params_name": "streaming"
},
"ListCollectionIds": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}

View File

@ -0,0 +1,20 @@
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
'use strict';
const FirestoreClient = require('./firestore_client');
// For backwards compatibility, we continue to support the default
// export.
module.exports = FirestoreClient;
module.exports.FirestoreClient = FirestoreClient;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1,295 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
const util_1 = require("./util");
/**
* Generates an error message to use with custom objects that cannot be
* serialized.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The value that failed serialization.
* @param path The field path that the object is assigned to.
*/
function customObjectMessage(arg, value, path) {
const fieldPathMessage = path ? ` (found in field ${path})` : '';
if (util_1.isObject(value)) {
const typeName = value.constructor.name;
switch (typeName) {
case 'DocumentReference':
case 'FieldPath':
case 'FieldValue':
case 'GeoPoint':
case 'Timestamp':
return (`${invalidArgumentMessage(arg, 'Firestore document')} Detected an object of type "${typeName}" that doesn't match the ` +
`expected instance${fieldPathMessage}. Please ensure that the ` +
'Firestore types you are using are from the same NPM package.)');
case 'Object':
return `${invalidArgumentMessage(arg, 'Firestore document')} Invalid use of type "${typeof value}" as a Firestore argument${fieldPathMessage}.`;
default:
return (`${invalidArgumentMessage(arg, 'Firestore document')} Couldn't serialize object of type "${typeName}"${fieldPathMessage}. Firestore doesn't support JavaScript ` +
'objects with custom prototypes (i.e. objects that were created ' +
'via the "new" operator).');
}
}
else {
return `${invalidArgumentMessage(arg, 'Firestore document')} Input is not a plain JavaScript object${fieldPathMessage}.`;
}
}
exports.customObjectMessage = customObjectMessage;
/**
* Validates that 'value' is a function.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the function can be omitted.
*/
function validateFunction(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isFunction(value)) {
throw new Error(invalidArgumentMessage(arg, 'function'));
}
}
}
exports.validateFunction = validateFunction;
/**
* Validates that 'value' is an object.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the object can be omitted.
*/
function validateObject(arg, value, options) {
if (!validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(invalidArgumentMessage(arg, 'object'));
}
}
}
exports.validateObject = validateObject;
/**
* Validates that 'value' is a string.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the string can be omitted.
*/
function validateString(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'string') {
throw new Error(invalidArgumentMessage(arg, 'string'));
}
}
}
exports.validateString = validateString;
/**
* Validates that 'value' is a host.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the host can be omitted.
*/
function validateHost(arg, value, options) {
if (!validateOptional(value, options)) {
validateString(arg, value);
const urlString = `http://${value}/`;
let parsed;
try {
parsed = new url_1.URL(urlString);
}
catch (e) {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
if (parsed.search !== '' ||
parsed.pathname !== '/' ||
parsed.username !== '') {
throw new Error(invalidArgumentMessage(arg, 'host'));
}
}
}
exports.validateHost = validateHost;
/**
* Validates that 'value' is a boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the boolean can be omitted.
*/
function validateBoolean(arg, value, options) {
if (!validateOptional(value, options)) {
if (typeof value !== 'boolean') {
throw new Error(invalidArgumentMessage(arg, 'boolean'));
}
}
}
exports.validateBoolean = validateBoolean;
/**
* Validates that 'value' is a number.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the number can be omitted.
*/
function validateNumber(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value)) {
throw new Error(invalidArgumentMessage(arg, 'number'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
}
exports.validateNumber = validateNumber;
/**
* Validates that 'value' is a integer.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The input to validate.
* @param options Options that specify whether the integer can be omitted.
*/
function validateInteger(arg, value, options) {
const min = options !== undefined && options.minValue !== undefined
? options.minValue
: -Infinity;
const max = options !== undefined && options.maxValue !== undefined
? options.maxValue
: Infinity;
if (!validateOptional(value, options)) {
if (typeof value !== 'number' || isNaN(value) || value % 1 !== 0) {
throw new Error(invalidArgumentMessage(arg, 'integer'));
}
else if (value < min || value > max) {
throw new Error(`${formatArgumentName(arg)} must be within [${min}, ${max}] inclusive, but was: ${value}`);
}
}
}
exports.validateInteger = validateInteger;
/**
* Generates an error message to use with invalid arguments.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param expectedType The expected input type.
*/
function invalidArgumentMessage(arg, expectedType) {
return `${formatArgumentName(arg)} is not a valid ${expectedType}.`;
}
exports.invalidArgumentMessage = invalidArgumentMessage;
/**
* Enforces the 'options.optional' constraint for 'value'.
*
* @private
* @param value The input to validate.
* @param options Whether the function can be omitted.
* @return Whether the object is omitted and is allowed to be omitted.
*/
function validateOptional(value, options) {
return (value === undefined && options !== undefined && options.optional === true);
}
exports.validateOptional = validateOptional;
/**
* Formats the given word as plural conditionally given the preceding number.
*
* @private
* @param num The number to use for formatting.
* @param str The string to format.
*/
function formatPlural(num, str) {
return `${num} ${str}` + (num === 1 ? '' : 's');
}
/**
* Creates a descriptive name for the provided argument name or index.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @return Either the argument name or its index description.
*/
function formatArgumentName(arg) {
return typeof arg === 'string'
? `Value for argument "${arg}"`
: `Element at index ${arg}`;
}
/**
* Verifies that 'args' has at least 'minSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param minSize The minimum number of elements to enforce.
* @throws if the expectation is not met.
*/
function validateMinNumberOfArguments(funcName, args, minSize) {
if (args.length < minSize) {
throw new Error(`Function "${funcName}()" requires at least ` +
`${formatPlural(minSize, 'argument')}.`);
}
}
exports.validateMinNumberOfArguments = validateMinNumberOfArguments;
/**
* Verifies that 'args' has at most 'maxSize' elements.
*
* @private
* @param funcName The function name to use in the error message.
* @param args The array (or array-like structure) to verify.
* @param maxSize The maximum number of elements to enforce.
* @throws if the expectation is not met.
*/
function validateMaxNumberOfArguments(funcName, args, maxSize) {
if (args.length > maxSize) {
throw new Error(`Function "${funcName}()" accepts at most ` +
`${formatPlural(maxSize, 'argument')}.`);
}
}
exports.validateMaxNumberOfArguments = validateMaxNumberOfArguments;
/**
* Validates that the provided named option equals one of the expected values.
*
* @param arg The argument name or argument index (for varargs methods).).
* @param value The input to validate.
* @param allowedValues A list of expected values.
* @param options Whether the input can be omitted.
* @private
*/
function validateEnumValue(arg, value, allowedValues, options) {
if (!validateOptional(value, options)) {
const expectedDescription = [];
for (const allowed of allowedValues) {
if (allowed === value) {
return;
}
expectedDescription.push(allowed);
}
throw new Error(`${formatArgumentName(arg)} is invalid. Acceptable values are: ${expectedDescription.join(', ')}`);
}
}
exports.validateEnumValue = validateEnumValue;
//# sourceMappingURL=validate.js.map

692
node_modules/@google-cloud/firestore/build/src/watch.js generated vendored Normal file
View File

@ -0,0 +1,692 @@
"use strict";
/*!
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const rbtree = require("functional-red-black-tree");
const backoff_1 = require("./backoff");
const document_1 = require("./document");
const document_change_1 = require("./document-change");
const logger_1 = require("./logger");
const path_1 = require("./path");
const timestamp_1 = require("./timestamp");
const types_1 = require("./types");
const util_1 = require("./util");
/*!
* Target ID used by watch. Watch uses a fixed target id since we only support
* one target per stream.
* @type {number}
*/
const WATCH_TARGET_ID = 0x1;
/*!
* Sentinel value for a document remove.
*/
const REMOVED = {};
/*!
* The change type for document change events.
*/
// tslint:disable-next-line:variable-name
const ChangeType = {
added: 'added',
modified: 'modified',
removed: 'removed',
};
/*!
* List of GRPC Error Codes.
*
* This corresponds to
* {@link https://github.com/grpc/grpc/blob/master/doc/statuscodes.md}.
*/
const GRPC_STATUS_CODE = {
// Not an error; returned on success.
OK: 0,
// The operation was cancelled (typically by the caller).
CANCELLED: 1,
// Unknown error. An example of where this error may be returned is if a
// Status value received from another address space belongs to an error-space
// that is not known in this address space. Also errors raised by APIs that
// do not return enough error information may be converted to this error.
UNKNOWN: 2,
// Client specified an invalid argument. Note that this differs from
// FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
// problematic regardless of the state of the system (e.g., a malformed file
// name).
INVALID_ARGUMENT: 3,
// Deadline expired before operation could complete. For operations that
// change the state of the system, this error may be returned even if the
// operation has completed successfully. For example, a successful response
// from a server could have been delayed long enough for the deadline to
// expire.
DEADLINE_EXCEEDED: 4,
// Some requested entity (e.g., file or directory) was not found.
NOT_FOUND: 5,
// Some entity that we attempted to create (e.g., file or directory) already
// exists.
ALREADY_EXISTS: 6,
// The caller does not have permission to execute the specified operation.
// PERMISSION_DENIED must not be used for rejections caused by exhausting
// some resource (use RESOURCE_EXHAUSTED instead for those errors).
// PERMISSION_DENIED must not be used if the caller can not be identified
// (use UNAUTHENTICATED instead for those errors).
PERMISSION_DENIED: 7,
// The request does not have valid authentication credentials for the
// operation.
UNAUTHENTICATED: 16,
// Some resource has been exhausted, perhaps a per-user quota, or perhaps the
// entire file system is out of space.
RESOURCE_EXHAUSTED: 8,
// Operation was rejected because the system is not in a state required for
// the operation's execution. For example, directory to be deleted may be
// non-empty, an rmdir operation is applied to a non-directory, etc.
//
// A litmus test that may help a service implementor in deciding
// between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
// (a) Use UNAVAILABLE if the client can retry just the failing call.
// (b) Use ABORTED if the client should retry at a higher-level
// (e.g., restarting a read-modify-write sequence).
// (c) Use FAILED_PRECONDITION if the client should not retry until
// the system state has been explicitly fixed. E.g., if an "rmdir"
// fails because the directory is non-empty, FAILED_PRECONDITION
// should be returned since the client should not retry unless
// they have first fixed up the directory by deleting files from it.
// (d) Use FAILED_PRECONDITION if the client performs conditional
// REST Get/Update/Delete on a resource and the resource on the
// server does not match the condition. E.g., conflicting
// read-modify-write on the same resource.
FAILED_PRECONDITION: 9,
// The operation was aborted, typically due to a concurrency issue like
// sequencer check failures, transaction aborts, etc.
//
// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
// and UNAVAILABLE.
ABORTED: 10,
// Operation was attempted past the valid range. E.g., seeking or reading
// past end of file.
//
// Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
// if the system state changes. For example, a 32-bit file system will
// generate INVALID_ARGUMENT if asked to read at an offset that is not in the
// range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
// an offset past the current file size.
//
// There is a fair bit of overlap between FAILED_PRECONDITION and
// OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
// when it applies so that callers who are iterating through a space can
// easily look for an OUT_OF_RANGE error to detect when they are done.
OUT_OF_RANGE: 11,
// Operation is not implemented or not supported/enabled in this service.
UNIMPLEMENTED: 12,
// Internal errors. Means some invariants expected by underlying System has
// been broken. If you see one of these errors, Something is very broken.
INTERNAL: 13,
// The service is currently unavailable. This is a most likely a transient
// condition and may be corrected by retrying with a backoff.
//
// See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
// and UNAVAILABLE.
UNAVAILABLE: 14,
// Unrecoverable data loss or corruption.
DATA_LOSS: 15,
// Force users to include a default branch:
DO_NOT_USE: -1,
};
/*!
* The comparator used for document watches (which should always get called with
* the same document).
*/
const DOCUMENT_WATCH_COMPARATOR = (doc1, doc2) => {
assert(doc1 === doc2, 'Document watches only support one document.');
return 0;
};
const EMPTY_FUNCTION = () => { };
/**
* Watch provides listen functionality and exposes the 'onSnapshot' observer. It
* can be used with a valid Firestore Listen target.
*
* @class
* @private
*/
class Watch {
/**
* @private
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore) {
/**
* Indicates whether we are interested in data from the stream. Set to false in the
* 'unsubscribe()' callback.
* @private
*/
this.isActive = true;
/**
* The current stream to the backend.
* @private
*/
this.currentStream = null;
/**
* The server assigns and updates the resume token.
* @private
*/
this.resumeToken = undefined;
/**
* A map of document names to QueryDocumentSnapshots for the last sent snapshot.
* @private
*/
this.docMap = new Map();
/**
* The accumulated map of document changes (keyed by document name) for the
* current snapshot.
* @private
*/
this.changeMap = new Map();
/**
* The current state of the query results. *
* @private
*/
this.current = false;
/**
* We need this to track whether we've pushed an initial set of changes,
* since we should push those even when there are no changes, if there
* aren't docs.
* @private
*/
this.hasPushed = false;
this.firestore = firestore;
this.backoff = new backoff_1.ExponentialBackoff();
this.requestTag = util_1.requestTag();
this.onNext = EMPTY_FUNCTION;
this.onError = EMPTY_FUNCTION;
}
/**
* Starts a watch and attaches a listener for document change events.
*
* @private
* @param onNext A callback to be called every time a new snapshot is
* available.
* @param onError A callback to be called if the listen fails or is cancelled.
* No further callbacks will occur.
*
* @returns An unsubscribe function that can be called to cancel the snapshot
* listener.
*/
onSnapshot(onNext, onError) {
assert(this.onNext === EMPTY_FUNCTION, 'onNext should not already be defined.');
assert(this.onError === EMPTY_FUNCTION, 'onError should not already be defined.');
assert(this.docTree === undefined, 'docTree should not already be defined.');
this.onNext = onNext;
this.onError = onError;
this.docTree = rbtree(this.getComparator());
this.initStream();
return () => {
logger_1.logger('Watch.onSnapshot', this.requestTag, 'Ending stream');
// Prevent further callbacks.
this.isActive = false;
this.onNext = () => { };
this.onError = () => { };
if (this.currentStream) {
this.currentStream.end();
}
};
}
/**
* Returns the current count of all documents, including the changes from
* the current changeMap.
* @private
*/
currentSize() {
const changes = this.extractCurrentChanges(timestamp_1.Timestamp.now());
return this.docMap.size + changes.adds.length - changes.deletes.length;
}
/**
* Splits up document changes into removals, additions, and updates.
* @private
*/
extractCurrentChanges(readTime) {
const deletes = [];
const adds = [];
const updates = [];
this.changeMap.forEach((value, name) => {
if (value === REMOVED) {
if (this.docMap.has(name)) {
deletes.push(name);
}
}
else if (this.docMap.has(name)) {
value.readTime = readTime;
updates.push(value.build());
}
else {
value.readTime = readTime;
adds.push(value.build());
}
});
return { deletes, adds, updates };
}
/**
* Helper to clear the docs on RESET or filter mismatch.
* @private
*/
resetDocs() {
logger_1.logger('Watch.resetDocs', this.requestTag, 'Resetting documents');
this.changeMap.clear();
this.resumeToken = undefined;
this.docTree.forEach((snapshot) => {
// Mark each document as deleted. If documents are not deleted, they
// will be send again by the server.
this.changeMap.set(snapshot.ref.path, REMOVED);
});
this.current = false;
}
/**
* Closes the stream and calls onError() if the stream is still active.
* @private
*/
closeStream(err) {
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
if (this.isActive) {
this.isActive = false;
logger_1.logger('Watch.closeStream', this.requestTag, 'Invoking onError: ', err);
this.onError(err);
}
}
/**
* Re-opens the stream unless the specified error is considered permanent.
* Clears the change map.
* @private
*/
maybeReopenStream(err) {
if (this.isActive && !this.isPermanentError(err)) {
logger_1.logger('Watch.maybeReopenStream', this.requestTag, 'Stream ended, re-opening after retryable error: ', err);
this.changeMap.clear();
if (this.isResourceExhaustedError(err)) {
this.backoff.resetToMax();
}
this.initStream();
}
else {
this.closeStream(err);
}
}
/**
* Helper to restart the outgoing stream to the backend.
* @private
*/
resetStream() {
logger_1.logger('Watch.resetStream', this.requestTag, 'Restarting stream');
if (this.currentStream) {
this.currentStream.end();
this.currentStream = null;
}
this.initStream();
}
/**
* Initializes a new stream to the backend with backoff.
* @private
*/
initStream() {
this.backoff
.backoffAndWait()
.then(async () => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Not initializing inactive stream');
return;
}
await this.firestore.initializeIfNeeded(this.requestTag);
const request = {};
request.database = this.firestore.formattedName;
request.addTarget = this.getTarget(this.resumeToken);
// Note that we need to call the internal _listen API to pass additional
// header values in readWriteStream.
return this.firestore
.readWriteStream('listen', request, this.requestTag, true)
.then(backendStream => {
if (!this.isActive) {
logger_1.logger('Watch.initStream', this.requestTag, 'Closing inactive stream');
backendStream.end();
return;
}
logger_1.logger('Watch.initStream', this.requestTag, 'Opened new stream');
this.currentStream = backendStream;
this.currentStream.on('data', (proto) => {
this.onData(proto);
})
.on('error', err => {
if (this.currentStream === backendStream) {
this.currentStream = null;
this.maybeReopenStream(err);
}
})
.on('end', () => {
if (this.currentStream === backendStream) {
this.currentStream = null;
const err = new types_1.GrpcError('Stream ended unexpectedly');
err.code = GRPC_STATUS_CODE.UNKNOWN;
this.maybeReopenStream(err);
}
});
this.currentStream.resume();
});
})
.catch(err => {
this.closeStream(err);
});
}
/**
* Handles 'data' events and closes the stream if the response type is
* invalid.
* @private
*/
onData(proto) {
if (proto.targetChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing target change');
const change = proto.targetChange;
const noTargetIds = !change.targetIds || change.targetIds.length === 0;
if (change.targetChangeType === 'NO_CHANGE') {
if (noTargetIds && change.readTime && this.current) {
// This means everything is up-to-date, so emit the current
// set of docs as a snapshot, if there were changes.
this.pushSnapshot(timestamp_1.Timestamp.fromProto(change.readTime), change.resumeToken);
}
}
else if (change.targetChangeType === 'ADD') {
if (WATCH_TARGET_ID !== change.targetIds[0]) {
this.closeStream(Error('Unexpected target ID sent by server'));
}
}
else if (change.targetChangeType === 'REMOVE') {
let code = 13;
let message = 'internal error';
if (change.cause) {
code = change.cause.code;
message = change.cause.message;
}
// @todo: Surface a .code property on the exception.
this.closeStream(new Error('Error ' + code + ': ' + message));
}
else if (change.targetChangeType === 'RESET') {
// Whatever changes have happened so far no longer matter.
this.resetDocs();
}
else if (change.targetChangeType === 'CURRENT') {
this.current = true;
}
else {
this.closeStream(new Error('Unknown target change type: ' + JSON.stringify(change)));
}
if (change.resumeToken &&
this.affectsTarget(change.targetIds, WATCH_TARGET_ID)) {
this.backoff.reset();
}
}
else if (proto.documentChange) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing change event');
// No other targetIds can show up here, but we still need to see
// if the targetId was in the added list or removed list.
const targetIds = proto.documentChange.targetIds || [];
const removedTargetIds = proto.documentChange.removedTargetIds || [];
let changed = false;
let removed = false;
for (let i = 0; i < targetIds.length; i++) {
if (targetIds[i] === WATCH_TARGET_ID) {
changed = true;
}
}
for (let i = 0; i < removedTargetIds.length; i++) {
if (removedTargetIds[i] === WATCH_TARGET_ID) {
removed = true;
}
}
const document = proto.documentChange.document;
const name = document.name;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
if (changed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document change');
const snapshot = new document_1.DocumentSnapshotBuilder();
snapshot.ref = this.firestore.doc(relativeName);
snapshot.fieldsProto = document.fields || {};
snapshot.createTime = timestamp_1.Timestamp.fromProto(document.createTime);
snapshot.updateTime = timestamp_1.Timestamp.fromProto(document.updateTime);
this.changeMap.set(relativeName, snapshot);
}
else if (removed) {
logger_1.logger('Watch.onData', this.requestTag, 'Received document remove');
this.changeMap.set(relativeName, REMOVED);
}
}
else if (proto.documentDelete || proto.documentRemove) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing remove event');
const name = (proto.documentDelete || proto.documentRemove).document;
const relativeName = path_1.QualifiedResourcePath.fromSlashSeparatedString(name)
.relativeName;
this.changeMap.set(relativeName, REMOVED);
}
else if (proto.filter) {
logger_1.logger('Watch.onData', this.requestTag, 'Processing filter update');
if (proto.filter.count !== this.currentSize()) {
// We need to remove all the current results.
this.resetDocs();
// The filter didn't match, so re-issue the query.
this.resetStream();
}
}
else {
this.closeStream(new Error('Unknown listen response type: ' + JSON.stringify(proto)));
}
}
/**
* Checks if the current target id is included in the list of target ids.
* If no targetIds are provided, returns true.
* @private
*/
affectsTarget(targetIds, currentId) {
if (targetIds === undefined || targetIds.length === 0) {
return true;
}
for (const targetId of targetIds) {
if (targetId === currentId) {
return true;
}
}
return false;
}
/**
* Assembles a new snapshot from the current set of changes and invokes the
* user's callback. Clears the current changes on completion.
* @private
*/
pushSnapshot(readTime, nextResumeToken) {
const appliedChanges = this.computeSnapshot(readTime);
if (!this.hasPushed || appliedChanges.length > 0) {
logger_1.logger('Watch.pushSnapshot', this.requestTag, 'Sending snapshot with %d changes and %d documents', String(appliedChanges.length), this.docTree.length);
// We pass the current set of changes, even if `docTree` is modified later.
const currentTree = this.docTree;
this.onNext(readTime, currentTree.length, () => currentTree.keys, () => appliedChanges);
this.hasPushed = true;
}
this.changeMap.clear();
this.resumeToken = nextResumeToken;
}
/**
* Applies a document delete to the document tree and the document map.
* Returns the corresponding DocumentChange event.
* @private
*/
deleteDoc(name) {
assert(this.docMap.has(name), 'Document to delete does not exist');
const oldDocument = this.docMap.get(name);
const existing = this.docTree.find(oldDocument);
const oldIndex = existing.index;
this.docTree = existing.remove();
this.docMap.delete(name);
return new document_change_1.DocumentChange(ChangeType.removed, oldDocument, oldIndex, -1);
}
/**
* Applies a document add to the document tree and the document map. Returns
* the corresponding DocumentChange event.
* @private
*/
addDoc(newDocument) {
const name = newDocument.ref.path;
assert(!this.docMap.has(name), 'Document to add already exists');
this.docTree = this.docTree.insert(newDocument, null);
const newIndex = this.docTree.find(newDocument).index;
this.docMap.set(name, newDocument);
return new document_change_1.DocumentChange(ChangeType.added, newDocument, -1, newIndex);
}
/**
* Applies a document modification to the document tree and the document map.
* Returns the DocumentChange event for successful modifications.
* @private
*/
modifyDoc(newDocument) {
const name = newDocument.ref.path;
assert(this.docMap.has(name), 'Document to modify does not exist');
const oldDocument = this.docMap.get(name);
if (!oldDocument.updateTime.isEqual(newDocument.updateTime)) {
const removeChange = this.deleteDoc(name);
const addChange = this.addDoc(newDocument);
return new document_change_1.DocumentChange(ChangeType.modified, newDocument, removeChange.oldIndex, addChange.newIndex);
}
return null;
}
/**
* Applies the mutations in changeMap to both the document tree and the
* document lookup map. Modified docMap in-place and returns the updated
* state.
* @private
*/
computeSnapshot(readTime) {
const changeSet = this.extractCurrentChanges(readTime);
const appliedChanges = [];
// Process the sorted changes in the order that is expected by our clients
// (removals, additions, and then modifications). We also need to sort the
// individual changes to assure that oldIndex/newIndex keep incrementing.
changeSet.deletes.sort((name1, name2) => {
// Deletes are sorted based on the order of the existing document.
return this.getComparator()(this.docMap.get(name1), this.docMap.get(name2));
});
changeSet.deletes.forEach(name => {
const change = this.deleteDoc(name);
appliedChanges.push(change);
});
changeSet.adds.sort(this.getComparator());
changeSet.adds.forEach(snapshot => {
const change = this.addDoc(snapshot);
appliedChanges.push(change);
});
changeSet.updates.sort(this.getComparator());
changeSet.updates.forEach(snapshot => {
const change = this.modifyDoc(snapshot);
if (change) {
appliedChanges.push(change);
}
});
assert(this.docTree.length === this.docMap.size, 'The update document ' +
'tree and document map should have the same number of entries.');
return appliedChanges;
}
/**
* Determines whether an error is considered permanent and should not be
* retried. Errors that don't provide a GRPC error code are always considered
* transient in this context.
*
* @private
* @param error An error object.
* @return Whether the error is permanent.
*/
isPermanentError(error) {
if (error.code === undefined) {
logger_1.logger('Watch.isPermanentError', this.requestTag, 'Unable to determine error code: ', error);
return false;
}
switch (error.code) {
case GRPC_STATUS_CODE.ABORTED:
case GRPC_STATUS_CODE.CANCELLED:
case GRPC_STATUS_CODE.UNKNOWN:
case GRPC_STATUS_CODE.DEADLINE_EXCEEDED:
case GRPC_STATUS_CODE.RESOURCE_EXHAUSTED:
case GRPC_STATUS_CODE.INTERNAL:
case GRPC_STATUS_CODE.UNAVAILABLE:
case GRPC_STATUS_CODE.UNAUTHENTICATED:
return false;
default:
return true;
}
}
/**
* Determines whether we need to initiate a longer backoff due to system
* overload.
*
* @private
* @param error A GRPC Error object that exposes an error code.
* @return Whether we need to back off our retries.
*/
isResourceExhaustedError(error) {
return error.code === GRPC_STATUS_CODE.RESOURCE_EXHAUSTED;
}
}
/**
* Creates a new Watch instance to listen on DocumentReferences.
*
* @private
*/
class DocumentWatch extends Watch {
constructor(firestore, ref) {
super(firestore);
this.ref = ref;
}
getComparator() {
return DOCUMENT_WATCH_COMPARATOR;
}
getTarget(resumeToken) {
const formattedName = this.ref.formattedName;
return {
documents: {
documents: [formattedName],
},
targetId: WATCH_TARGET_ID,
resumeToken,
};
}
}
exports.DocumentWatch = DocumentWatch;
/**
* Creates a new Watch instance to listen on Queries.
*
* @private
*/
class QueryWatch extends Watch {
constructor(firestore, query) {
super(firestore);
this.query = query;
this.comparator = query.comparator();
}
getComparator() {
return this.query.comparator();
}
getTarget(resumeToken) {
const query = this.query.toProto();
return { query, targetId: WATCH_TARGET_ID, resumeToken };
}
}
exports.QueryWatch = QueryWatch;
//# sourceMappingURL=watch.js.map

View File

@ -0,0 +1,673 @@
"use strict";
/*!
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const assert = require("assert");
const document_1 = require("./document");
const logger_1 = require("./logger");
const path_1 = require("./path");
const reference_1 = require("./reference");
const serializer_1 = require("./serializer");
const timestamp_1 = require("./timestamp");
const util_1 = require("./util");
const validate_1 = require("./validate");
/*!
* Google Cloud Functions terminates idle connections after two minutes. After
* longer periods of idleness, we issue transactional commits to allow for
* retries.
*/
const GCF_IDLE_TIMEOUT_MS = 110 * 1000;
/**
* A WriteResult wraps the write time set by the Firestore servers on sets(),
* updates(), and creates().
*
* @class
*/
class WriteResult {
/**
* @hideconstructor
*
* @param _writeTime The time of the corresponding document write.
*/
constructor(_writeTime) {
this._writeTime = _writeTime;
}
/**
* The write time as set by the Firestore servers.
*
* @type {Timestamp}
* @name WriteResult#writeTime
* @readonly
*
* @example
* let documentRef = firestore.doc('col/doc');
*
* documentRef.set({foo: 'bar'}).then(writeResult => {
* console.log(`Document written at: ${writeResult.writeTime.toDate()}`);
* });
*/
get writeTime() {
return this._writeTime;
}
/**
* Returns true if this `WriteResult` is equal to the provided value.
*
* @param {*} other The value to compare against.
* @return true if this `WriteResult` is equal to the provided value.
*/
isEqual(other) {
return (this === other ||
(other instanceof WriteResult &&
this._writeTime.isEqual(other._writeTime)));
}
}
exports.WriteResult = WriteResult;
/**
* A Firestore WriteBatch that can be used to atomically commit multiple write
* operations at once.
*
* @class
*/
class WriteBatch {
/**
* @hideconstructor
*
* @param firestore The Firestore Database client.
*/
constructor(firestore) {
/**
* An array of write operations that are executed as part of the commit. The
* resulting `api.IWrite` will be sent to the backend.
* @private
*/
this._ops = [];
this._committed = false;
this._firestore = firestore;
this._serializer = new serializer_1.Serializer(firestore);
}
/**
* Checks if this write batch has any pending operations.
*
* @private
*/
get isEmpty() {
return this._ops.length === 0;
}
/**
* Throws an error if this batch has already been committed.
*
* @private
*/
verifyNotCommitted() {
if (this._committed) {
throw new Error('Cannot modify a WriteBatch that has been committed.');
}
}
/**
* Create a document with the provided object values. This will fail the batch
* if a document exists at its location.
*
* @param {DocumentReference} documentRef A reference to the document to be
* created.
* @param {DocumentData} data The object to serialize as the document.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.collection('col').doc();
*
* writeBatch.create(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
create(documentRef, data) {
reference_1.validateDocumentReference('documentRef', documentRef);
validateDocumentData('data', data, /* allowDeletes= */ false);
this.verifyNotCommitted();
const transform = document_1.DocumentTransform.fromObject(documentRef, data);
transform.validate();
const precondition = new document_1.Precondition({ exists: false });
const op = () => {
const document = document_1.DocumentSnapshot.fromObject(documentRef, data);
const write = !document.isEmpty || transform.isEmpty ? document.toProto() : null;
return {
write,
transform: transform.toProto(this._serializer),
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Deletes a document from the database.
*
* @param {DocumentReference} documentRef A reference to the document to be
* deleted.
* @param {Precondition=} precondition A precondition to enforce for this
* delete.
* @param {Timestamp=} precondition.lastUpdateTime If set, enforces that the
* document was last updated at lastUpdateTime. Fails the batch if the
* document doesn't exist or was last updated at a different time.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.delete(documentRef);
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
delete(documentRef, precondition) {
reference_1.validateDocumentReference('documentRef', documentRef);
validateDeletePrecondition('precondition', precondition, { optional: true });
this.verifyNotCommitted();
const conditions = new document_1.Precondition(precondition);
const op = () => {
return {
write: {
delete: documentRef.formattedName,
},
precondition: conditions.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Write to the document referred to by the provided
* [DocumentReference]{@link DocumentReference}.
* If the document does not exist yet, it will be created. If you pass
* [SetOptions]{@link SetOptions}., the provided data can be merged
* into the existing document.
*
* @param {DocumentReference} documentRef A reference to the document to be
* set.
* @param {DocumentData} data The object to serialize as the document.
* @param {SetOptions=} options An object to configure the set behavior.
* @param {boolean=} options.merge - If true, set() merges the values
* specified in its data argument. Fields omitted from this set() call
* remain untouched.
* @param {Array.<string|FieldPath>=} options.mergeFields - If provided,
* set() only replaces the specified field paths. Any field path that is not
* specified is ignored and remains untouched.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
set(documentRef, data, options) {
validateSetOptions('options', options, { optional: true });
const mergeLeaves = options && options.merge === true;
const mergePaths = options && options.mergeFields;
reference_1.validateDocumentReference('documentRef', documentRef);
validateDocumentData('data', data,
/* allowDeletes= */ !!(mergePaths || mergeLeaves));
this.verifyNotCommitted();
let documentMask;
if (mergePaths) {
documentMask = document_1.DocumentMask.fromFieldMask(options.mergeFields);
data = documentMask.applyTo(data);
}
const transform = document_1.DocumentTransform.fromObject(documentRef, data);
transform.validate();
const op = () => {
const document = document_1.DocumentSnapshot.fromObject(documentRef, data);
if (mergePaths) {
documentMask.removeFields(transform.fields);
}
else {
documentMask = document_1.DocumentMask.fromObject(data);
}
const hasDocumentData = !document.isEmpty || !documentMask.isEmpty;
let write;
if (!mergePaths && !mergeLeaves) {
write = document.toProto();
}
else if (hasDocumentData || transform.isEmpty) {
write = document.toProto();
write.updateMask = documentMask.toProto();
}
return {
write,
transform: transform.toProto(this._serializer),
};
};
this._ops.push(op);
return this;
}
/**
* Update fields of the document referred to by the provided
* [DocumentReference]{@link DocumentReference}. If the document
* doesn't yet exist, the update fails and the entire batch will be rejected.
*
* The update() method accepts either an object with field paths encoded as
* keys and field values encoded as values, or a variable number of arguments
* that alternate between field paths and field values. Nested fields can be
* updated by providing dot-separated field path strings or by providing
* FieldPath objects.
*
* A Precondition restricting this update can be specified as the last
* argument.
*
* @param {DocumentReference} documentRef A reference to the document to be
* updated.
* @param {UpdateData|string|FieldPath} dataOrField An object
* containing the fields and values with which to update the document
* or the path of the first field to update.
* @param {
* ...(Precondition|*|string|FieldPath)} preconditionOrValues -
* An alternating list of field paths and values to update or a Precondition
* to restrict this update.
* @returns {WriteBatch} This WriteBatch instance. Used for chaining
* method calls.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.update(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
update(documentRef, dataOrField, ...preconditionOrValues) {
validate_1.validateMinNumberOfArguments('WriteBatch.update', arguments, 2);
reference_1.validateDocumentReference('documentRef', documentRef);
this.verifyNotCommitted();
const updateMap = new Map();
let precondition = new document_1.Precondition({ exists: true });
const argumentError = 'Update() requires either a single JavaScript ' +
'object or an alternating list of field/value pairs that can be ' +
'followed by an optional precondition.';
const usesVarargs = typeof dataOrField === 'string' || dataOrField instanceof path_1.FieldPath;
if (usesVarargs) {
try {
for (let i = 1; i < arguments.length; i += 2) {
if (i === arguments.length - 1) {
validateUpdatePrecondition(i, arguments[i]);
precondition = new document_1.Precondition(arguments[i]);
}
else {
path_1.validateFieldPath(i, arguments[i]);
// Unlike the `validateMinNumberOfArguments` invocation above, this
// validation can be triggered both from `WriteBatch.update()` and
// `DocumentReference.update()`. Hence, we don't use the fully
// qualified API name in the error message.
validate_1.validateMinNumberOfArguments('update', arguments, i + 1);
const fieldPath = path_1.FieldPath.fromArgument(arguments[i]);
validateFieldValue(i, arguments[i + 1], fieldPath);
updateMap.set(fieldPath, arguments[i + 1]);
}
}
}
catch (err) {
logger_1.logger('WriteBatch.update', null, 'Varargs validation failed:', err);
// We catch the validation error here and re-throw to provide a better
// error message.
throw new Error(`${argumentError} ${err.message}`);
}
}
else {
try {
validateUpdateMap('dataOrField', dataOrField);
validate_1.validateMaxNumberOfArguments('update', arguments, 3);
const data = dataOrField;
Object.keys(data).forEach(key => {
path_1.validateFieldPath(key, key);
updateMap.set(path_1.FieldPath.fromArgument(key), data[key]);
});
if (preconditionOrValues.length > 0) {
validateUpdatePrecondition('preconditionOrValues', preconditionOrValues[0]);
precondition = new document_1.Precondition(preconditionOrValues[0]);
}
}
catch (err) {
logger_1.logger('WriteBatch.update', null, 'Non-varargs validation failed:', err);
// We catch the validation error here and prefix the error with a custom
// message to describe the usage of update() better.
throw new Error(`${argumentError} ${err.message}`);
}
}
validateNoConflictingFields('dataOrField', updateMap);
const transform = document_1.DocumentTransform.fromUpdateMap(documentRef, updateMap);
transform.validate();
const documentMask = document_1.DocumentMask.fromUpdateMap(updateMap);
const op = () => {
const document = document_1.DocumentSnapshot.fromUpdateMap(documentRef, updateMap);
let write = null;
if (!document.isEmpty || !documentMask.isEmpty) {
write = document.toProto();
write.updateMask = documentMask.toProto();
}
return {
write,
transform: transform.toProto(this._serializer),
precondition: precondition.toProto(),
};
};
this._ops.push(op);
return this;
}
/**
* Atomically commits all pending operations to the database and verifies all
* preconditions. Fails the entire write if any precondition is not met.
*
* @returns {Promise.<Array.<WriteResult>>} A Promise that resolves
* when this batch completes.
*
* @example
* let writeBatch = firestore.batch();
* let documentRef = firestore.doc('col/doc');
*
* writeBatch.set(documentRef, {foo: 'bar'});
*
* writeBatch.commit().then(() => {
* console.log('Successfully executed batch.');
* });
*/
commit() {
return this.commit_();
}
/**
* Commit method that takes an optional transaction ID.
*
* @private
* @param commitOptions Options to use for this commit.
* @param commitOptions.transactionId The transaction ID of this commit.
* @param commitOptions.requestTag A unique client-assigned identifier for
* this request.
* @returns A Promise that resolves when this batch completes.
*/
async commit_(commitOptions) {
// Note: We don't call `verifyNotCommitted()` to allow for retries.
this._committed = true;
const tag = (commitOptions && commitOptions.requestTag) || util_1.requestTag();
await this._firestore.initializeIfNeeded(tag);
const database = this._firestore.formattedName;
const request = { database };
// On GCF, we periodically force transactional commits to allow for
// request retries in case GCF closes our backend connection.
const explicitTransaction = commitOptions && commitOptions.transactionId;
if (!explicitTransaction && this._shouldCreateTransaction()) {
logger_1.logger('WriteBatch.commit', tag, 'Using transaction for commit');
return this._firestore
.request('beginTransaction', request, tag, true)
.then(resp => {
return this.commit_({ transactionId: resp.transaction });
});
}
const writes = this._ops.map(op => op());
request.writes = [];
for (const req of writes) {
assert(req.write || req.transform, 'Either a write or transform must be set');
if (req.precondition) {
(req.write || req.transform).currentDocument = req.precondition;
}
if (req.write) {
request.writes.push(req.write);
}
if (req.transform) {
request.writes.push(req.transform);
}
}
logger_1.logger('WriteBatch.commit', tag, 'Sending %d writes', request.writes.length);
if (explicitTransaction) {
request.transaction = explicitTransaction;
}
return this._firestore
.request('commit', request, tag,
/* allowRetries= */ false)
.then(resp => {
const writeResults = [];
if (request.writes.length > 0) {
assert(Array.isArray(resp.writeResults) &&
request.writes.length === resp.writeResults.length, `Expected one write result per operation, but got ${resp.writeResults.length} results for ${request.writes.length} operations.`);
const commitTime = timestamp_1.Timestamp.fromProto(resp.commitTime);
let offset = 0;
for (let i = 0; i < writes.length; ++i) {
const writeRequest = writes[i];
// Don't return two write results for a write that contains a
// transform, as the fact that we have to split one write
// operation into two distinct write requests is an implementation
// detail.
if (writeRequest.write && writeRequest.transform) {
// The document transform is always sent last and produces the
// latest update time.
++offset;
}
const writeResult = resp.writeResults[i + offset];
writeResults.push(new WriteResult(writeResult.updateTime
? timestamp_1.Timestamp.fromProto(writeResult.updateTime)
: commitTime));
}
}
return writeResults;
});
}
/**
* Determines whether we should issue a transactional commit. On GCF, this
* happens after two minutes of idleness.
*
* @private
* @returns Whether to use a transaction.
*/
_shouldCreateTransaction() {
if (!this._firestore._preferTransactions) {
return false;
}
if (this._firestore._lastSuccessfulRequest) {
const now = new Date().getTime();
return now - this._firestore._lastSuccessfulRequest > GCF_IDLE_TIMEOUT_MS;
}
return true;
}
}
exports.WriteBatch = WriteBatch;
/**
* Validates the use of 'value' as a Precondition and enforces that 'exists'
* and 'lastUpdateTime' use valid types.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate
* @param allowExists Whether to allow the 'exists' preconditions.
*/
function validatePrecondition(arg, value, allowExists) {
if (typeof value !== 'object' || value === null) {
throw new Error('Input is not an object.');
}
const precondition = value;
let conditions = 0;
if (precondition.exists !== undefined) {
++conditions;
if (!allowExists) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "exists" is not an allowed precondition.`);
}
if (typeof precondition.exists !== 'boolean') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "exists" is not a boolean.'`);
}
}
if (precondition.lastUpdateTime !== undefined) {
++conditions;
if (!(precondition.lastUpdateTime instanceof timestamp_1.Timestamp)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} "lastUpdateTime" is not a Firestore Timestamp.`);
}
}
if (conditions > 1) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'precondition')} Input specifies more than one precondition.`);
}
}
/**
* Validates the use of 'value' as an update Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateUpdatePrecondition(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ false);
}
}
/**
* Validates the use of 'value' as a delete Precondition.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
*/
function validateDeletePrecondition(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
validatePrecondition(arg, value, /* allowExists= */ true);
}
}
/**
* Validates the use of 'value' as SetOptions and enforces that 'merge' is a
* boolean.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param value The object to validate.
* @param options Optional validation options specifying whether the value can
* be omitted.
* @throws if the input is not a valid SetOptions object.
*/
function validateSetOptions(arg, value, options) {
if (!validate_1.validateOptional(value, options)) {
if (!util_1.isObject(value)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} Input is not an object.`);
}
const setOptions = value;
if ('merge' in setOptions && typeof setOptions.merge !== 'boolean') {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "merge" is not a boolean.`);
}
if ('mergeFields' in setOptions) {
if (!Array.isArray(setOptions.mergeFields)) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "mergeFields" is not an array.`);
}
for (let i = 0; i < setOptions.mergeFields.length; ++i) {
try {
path_1.validateFieldPath(i, setOptions.mergeFields[i]);
}
catch (err) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} "mergeFields" is not valid: ${err.message}`);
}
}
}
if ('merge' in setOptions && 'mergeFields' in setOptions) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'set() options argument')} You cannot specify both "merge" and "mergeFields".`);
}
}
}
exports.validateSetOptions = validateSetOptions;
/**
* Validates a JavaScript object for usage as a Firestore document.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @param allowDeletes Whether to allow FieldValue.delete() sentinels.
* @throws when the object is invalid.
*/
function validateDocumentData(arg, obj, allowDeletes) {
if (!serializer_1.isPlainObject(obj)) {
throw new Error(validate_1.customObjectMessage(arg, obj));
}
for (const prop of Object.keys(obj)) {
serializer_1.validateUserInput(arg, obj[prop], 'Firestore document', {
allowDeletes: allowDeletes ? 'all' : 'none',
allowTransforms: true,
}, new path_1.FieldPath(prop));
}
}
exports.validateDocumentData = validateDocumentData;
/**
* Validates that a value can be used as field value during an update.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param val The value to verify.
* @param path The path to show in the error message.
*/
function validateFieldValue(arg, val, path) {
serializer_1.validateUserInput(arg, val, 'Firestore value', { allowDeletes: 'root', allowTransforms: true }, path);
}
exports.validateFieldValue = validateFieldValue;
/**
* Validates that the update data does not contain any ambiguous field
* definitions (such as 'a.b' and 'a').
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param data An update map with field/value pairs.
*/
function validateNoConflictingFields(arg, data) {
const fields = [];
data.forEach((value, key) => {
fields.push(key);
});
fields.sort((left, right) => left.compareTo(right));
for (let i = 1; i < fields.length; ++i) {
if (fields[i - 1].isPrefixOf(fields[i])) {
throw new Error(`${validate_1.invalidArgumentMessage(arg, 'update map')} Field "${fields[i - 1]}" was specified multiple times.`);
}
}
}
/**
* Validates that a JavaScript object is a map of field paths to field values.
*
* @private
* @param arg The argument name or argument index (for varargs methods).
* @param obj JavaScript object to validate.
* @throws when the object is invalid.
*/
function validateUpdateMap(arg, obj) {
if (!serializer_1.isPlainObject(obj)) {
throw new Error(validate_1.customObjectMessage(arg, obj));
}
let isEmpty = true;
if (obj) {
for (const prop of Object.keys(obj)) {
isEmpty = false;
validateFieldValue(arg, obj[prop], new path_1.FieldPath(prop));
}
}
if (isEmpty) {
throw new Error('At least one field must be updated.');
}
}
//# sourceMappingURL=write-batch.js.map