firebase-functions 3.21.0 → 3.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/lib/bin/firebase-functions.js +21 -0
  2. package/lib/cloud-functions.d.ts +54 -88
  3. package/lib/cloud-functions.js +2 -59
  4. package/lib/common/change.d.ts +46 -0
  5. package/lib/common/change.js +82 -0
  6. package/lib/common/encoding.js +21 -1
  7. package/lib/common/providers/database.d.ts +145 -0
  8. package/lib/common/providers/database.js +271 -0
  9. package/lib/common/providers/https.d.ts +37 -17
  10. package/lib/common/providers/https.js +3 -0
  11. package/lib/common/providers/identity.d.ts +5 -1
  12. package/lib/common/providers/identity.js +12 -4
  13. package/lib/common/providers/tasks.d.ts +9 -0
  14. package/lib/common/providers/tasks.js +13 -12
  15. package/lib/function-builder.d.ts +3 -3
  16. package/lib/function-builder.js +2 -2
  17. package/lib/logger/common.js +21 -0
  18. package/lib/logger/compat.js +21 -0
  19. package/lib/logger/index.d.ts +14 -6
  20. package/lib/logger/index.js +33 -6
  21. package/lib/providers/auth.d.ts +26 -5
  22. package/lib/providers/auth.js +18 -4
  23. package/lib/providers/database.d.ts +4 -146
  24. package/lib/providers/database.js +7 -251
  25. package/lib/providers/firestore.d.ts +2 -1
  26. package/lib/providers/firestore.js +2 -1
  27. package/lib/providers/pubsub.d.ts +6 -6
  28. package/lib/providers/pubsub.js +6 -6
  29. package/lib/providers/tasks.d.ts +29 -14
  30. package/lib/providers/tasks.js +10 -3
  31. package/lib/utilities/path-pattern.d.ts +1 -0
  32. package/lib/utilities/path-pattern.js +142 -0
  33. package/lib/v2/core.d.ts +25 -1
  34. package/lib/v2/core.js +7 -0
  35. package/lib/v2/index.d.ts +11 -3
  36. package/lib/v2/index.js +12 -3
  37. package/lib/v2/options.d.ts +13 -34
  38. package/lib/v2/options.js +6 -58
  39. package/lib/v2/params/index.d.ts +4 -1
  40. package/lib/v2/params/index.js +25 -1
  41. package/lib/v2/params/types.js +21 -0
  42. package/lib/v2/providers/alerts/alerts.d.ts +94 -3
  43. package/lib/v2/providers/alerts/alerts.js +23 -7
  44. package/lib/v2/providers/alerts/appDistribution.d.ts +101 -1
  45. package/lib/v2/providers/alerts/appDistribution.js +28 -1
  46. package/lib/v2/providers/alerts/billing.d.ts +23 -2
  47. package/lib/v2/providers/alerts/billing.js +37 -0
  48. package/lib/v2/providers/alerts/crashlytics.d.ts +193 -18
  49. package/lib/v2/providers/alerts/crashlytics.js +62 -1
  50. package/lib/v2/providers/alerts/index.d.ts +6 -0
  51. package/lib/v2/providers/alerts/index.js +27 -0
  52. package/lib/v2/providers/database.d.ts +182 -0
  53. package/lib/v2/providers/database.js +204 -0
  54. package/lib/v2/providers/eventarc.d.ts +89 -5
  55. package/lib/v2/providers/eventarc.js +4 -0
  56. package/lib/v2/providers/https.d.ts +123 -2
  57. package/lib/v2/providers/https.js +13 -3
  58. package/lib/v2/providers/identity.d.ts +108 -4
  59. package/lib/v2/providers/identity.js +33 -2
  60. package/lib/v2/providers/pubsub.d.ts +122 -5
  61. package/lib/v2/providers/pubsub.js +58 -2
  62. package/lib/v2/providers/storage.d.ts +192 -4
  63. package/lib/v2/providers/storage.js +52 -9
  64. package/lib/v2/providers/tasks.d.ts +106 -6
  65. package/lib/v2/providers/tasks.js +4 -0
  66. package/package.json +12 -6
@@ -1,4 +1,25 @@
1
1
  "use strict";
2
+ // The MIT License (MIT)
3
+ //
4
+ // Copyright (c) 2017 Firebase
5
+ //
6
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ // of this software and associated documentation files (the "Software"), to deal
8
+ // in the Software without restriction, including without limitation the rights
9
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ // copies of the Software, and to permit persons to whom the Software is
11
+ // furnished to do so, subject to the following conditions:
12
+ //
13
+ // The above copyright notice and this permission notice shall be included in all
14
+ // copies or substantial portions of the Software.
15
+ //
16
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ // SOFTWARE.
2
23
  Object.defineProperty(exports, "__esModule", { value: true });
3
24
  exports.error = exports.warn = exports.info = exports.log = exports.debug = exports.write = void 0;
4
25
  const util_1 = require("util");
@@ -37,7 +58,8 @@ function removeCircular(obj, refs = []) {
37
58
  }
38
59
  /**
39
60
  * Writes a `LogEntry` to `stdout`/`stderr` (depending on severity).
40
- * @param entry The `LogEntry` including severity, message, and any additional structured metadata.
61
+ * @param entry - The `LogEntry` including severity, message, and any additional structured metadata.
62
+ * @public
41
63
  */
42
64
  function write(entry) {
43
65
  if (common_1.SUPPORTS_STRUCTURED_LOGS) {
@@ -62,7 +84,8 @@ exports.write = write;
62
84
  /**
63
85
  * Writes a `DEBUG` severity log. If the last argument provided is a plain object,
64
86
  * it is added to the `jsonPayload` in the Cloud Logging entry.
65
- * @param args Arguments, concatenated into the log message with space separators.
87
+ * @param args - Arguments, concatenated into the log message with space separators.
88
+ * @public
66
89
  */
67
90
  function debug(...args) {
68
91
  write(entryFromArgs('DEBUG', args));
@@ -71,7 +94,8 @@ exports.debug = debug;
71
94
  /**
72
95
  * Writes an `INFO` severity log. If the last argument provided is a plain object,
73
96
  * it is added to the `jsonPayload` in the Cloud Logging entry.
74
- * @param args Arguments, concatenated into the log message with space separators.
97
+ * @param args - Arguments, concatenated into the log message with space separators.
98
+ * @public
75
99
  */
76
100
  function log(...args) {
77
101
  write(entryFromArgs('INFO', args));
@@ -80,7 +104,8 @@ exports.log = log;
80
104
  /**
81
105
  * Writes an `INFO` severity log. If the last argument provided is a plain object,
82
106
  * it is added to the `jsonPayload` in the Cloud Logging entry.
83
- * @param args Arguments, concatenated into the log message with space separators.
107
+ * @param args - Arguments, concatenated into the log message with space separators.
108
+ * @public
84
109
  */
85
110
  function info(...args) {
86
111
  write(entryFromArgs('INFO', args));
@@ -89,7 +114,8 @@ exports.info = info;
89
114
  /**
90
115
  * Writes a `WARNING` severity log. If the last argument provided is a plain object,
91
116
  * it is added to the `jsonPayload` in the Cloud Logging entry.
92
- * @param args Arguments, concatenated into the log message with space separators.
117
+ * @param args - Arguments, concatenated into the log message with space separators.
118
+ * @public
93
119
  */
94
120
  function warn(...args) {
95
121
  write(entryFromArgs('WARNING', args));
@@ -98,7 +124,8 @@ exports.warn = warn;
98
124
  /**
99
125
  * Writes an `ERROR` severity log. If the last argument provided is a plain object,
100
126
  * it is added to the `jsonPayload` in the Cloud Logging entry.
101
- * @param args Arguments, concatenated into the log message with space separators.
127
+ * @param args - Arguments, concatenated into the log message with space separators.
128
+ * @public
102
129
  */
103
130
  function error(...args) {
104
131
  write(entryFromArgs('ERROR', args));
@@ -7,21 +7,34 @@ export { HttpsError };
7
7
  export declare const provider = "google.firebase.auth";
8
8
  /** @hidden */
9
9
  export declare const service = "firebaseauth.googleapis.com";
10
- /** Resource level options */
10
+ /**
11
+ * Resource level options
12
+ * @public
13
+ */
11
14
  export interface UserOptions {
15
+ /** Options to set configuration at the resource level for blocking functions. */
12
16
  blockingOptions?: {
17
+ /** Pass the ID Token credential to the function. */
13
18
  idToken?: boolean;
19
+ /** Pass the Access Token credential to the function. */
14
20
  accessToken?: boolean;
21
+ /** Pass the Refresh Token credential to the function. */
15
22
  refreshToken?: boolean;
16
23
  };
17
24
  }
18
25
  /**
19
- * Handle events related to Firebase authentication users.
26
+ * Handles events related to Firebase authentication users.
27
+ * @param userOptions - Resource level options
28
+ * @returns UserBuilder - Builder used to create Cloud Functions for Firebase Auth user lifecycle events
29
+ * @public
20
30
  */
21
31
  export declare function user(userOptions?: UserOptions): UserBuilder;
22
32
  /** @hidden */
23
33
  export declare function _userWithOptions(options: DeploymentOptions, userOptions: UserOptions): UserBuilder;
24
- /** Builder used to create Cloud Functions for Firebase Auth user lifecycle events. */
34
+ /**
35
+ * Builder used to create Cloud Functions for Firebase Auth user lifecycle events.
36
+ * @public
37
+ */
25
38
  export declare class UserBuilder {
26
39
  private triggerResource;
27
40
  private options;
@@ -29,12 +42,20 @@ export declare class UserBuilder {
29
42
  private static dataConstructor;
30
43
  /** @hidden */
31
44
  constructor(triggerResource: () => string, options: DeploymentOptions, userOptions?: UserOptions);
32
- /** Respond to the creation of a Firebase Auth user. */
45
+ /**
46
+ * Responds to the creation of a Firebase Auth user.
47
+ * @public
48
+ */
33
49
  onCreate(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
34
- /** Respond to the deletion of a Firebase Auth user. */
50
+ /**
51
+ * Responds to the deletion of a Firebase Auth user.
52
+ * @public
53
+ */
35
54
  onDelete(handler: (user: UserRecord, context: EventContext) => PromiseLike<any> | any): CloudFunction<UserRecord>;
36
55
  beforeCreate(handler: (user: AuthUserRecord, context: AuthEventContext) => BeforeCreateResponse | void | Promise<BeforeCreateResponse> | Promise<void>): BlockingFunction;
37
56
  beforeSignIn(handler: (user: AuthUserRecord, context: AuthEventContext) => BeforeSignInResponse | void | Promise<BeforeSignInResponse> | Promise<void>): BlockingFunction;
57
+ /** @hidden */
38
58
  private onOperation;
59
+ /** @hidden */
39
60
  private beforeOperation;
40
61
  }
@@ -32,7 +32,10 @@ exports.provider = 'google.firebase.auth';
32
32
  /** @hidden */
33
33
  exports.service = 'firebaseauth.googleapis.com';
34
34
  /**
35
- * Handle events related to Firebase authentication users.
35
+ * Handles events related to Firebase authentication users.
36
+ * @param userOptions - Resource level options
37
+ * @returns UserBuilder - Builder used to create Cloud Functions for Firebase Auth user lifecycle events
38
+ * @public
36
39
  */
37
40
  function user(userOptions) {
38
41
  return _userWithOptions({}, userOptions || {});
@@ -48,7 +51,10 @@ function _userWithOptions(options, userOptions) {
48
51
  }, options, userOptions);
49
52
  }
50
53
  exports._userWithOptions = _userWithOptions;
51
- /** Builder used to create Cloud Functions for Firebase Auth user lifecycle events. */
54
+ /**
55
+ * Builder used to create Cloud Functions for Firebase Auth user lifecycle events.
56
+ * @public
57
+ */
52
58
  class UserBuilder {
53
59
  /** @hidden */
54
60
  constructor(triggerResource, options, userOptions) {
@@ -59,11 +65,17 @@ class UserBuilder {
59
65
  static dataConstructor(raw) {
60
66
  return (0, identity_1.userRecordConstructor)(raw.data);
61
67
  }
62
- /** Respond to the creation of a Firebase Auth user. */
68
+ /**
69
+ * Responds to the creation of a Firebase Auth user.
70
+ * @public
71
+ */
63
72
  onCreate(handler) {
64
73
  return this.onOperation(handler, 'user.create');
65
74
  }
66
- /** Respond to the deletion of a Firebase Auth user. */
75
+ /**
76
+ * Responds to the deletion of a Firebase Auth user.
77
+ * @public
78
+ */
67
79
  onDelete(handler) {
68
80
  return this.onOperation(handler, 'user.delete');
69
81
  }
@@ -73,6 +85,7 @@ class UserBuilder {
73
85
  beforeSignIn(handler) {
74
86
  return this.beforeOperation(handler, 'beforeSignIn');
75
87
  }
88
+ /** @hidden */
76
89
  onOperation(handler, eventType) {
77
90
  return (0, cloud_functions_1.makeCloudFunction)({
78
91
  handler,
@@ -85,6 +98,7 @@ class UserBuilder {
85
98
  options: this.options,
86
99
  });
87
100
  }
101
+ /** @hidden */
88
102
  beforeOperation(handler, eventType) {
89
103
  var _a, _b, _c, _d, _e, _f;
90
104
  const accessToken = ((_b = (_a = this.userOptions) === null || _a === void 0 ? void 0 : _a.blockingOptions) === null || _b === void 0 ? void 0 : _b.accessToken) || false;
@@ -1,7 +1,9 @@
1
- import * as firebase from 'firebase-admin';
2
1
  import { apps } from '../apps';
3
- import { Change, CloudFunction, EventContext } from '../cloud-functions';
2
+ import { CloudFunction, EventContext } from '../cloud-functions';
3
+ import { Change } from '../common/change';
4
+ import { DataSnapshot } from '../common/providers/database';
4
5
  import { DeploymentOptions } from '../function-configuration';
6
+ export { DataSnapshot };
5
7
  /** @hidden */
6
8
  export declare const provider = "google.firebase.database";
7
9
  /** @hidden */
@@ -130,147 +132,3 @@ export declare class RefBuilder {
130
132
  */
131
133
  /** @hidden */
132
134
  export declare function extractInstanceAndPath(resource: string, domain?: string): string[];
133
- /**
134
- * Interface representing a Firebase Realtime Database data snapshot.
135
- */
136
- export declare class DataSnapshot {
137
- private app?;
138
- instance: string;
139
- /** @hidden */
140
- private _ref;
141
- /** @hidden */
142
- private _path;
143
- /** @hidden */
144
- private _data;
145
- /** @hidden */
146
- private _childPath;
147
- constructor(data: any, path?: string, // path will be undefined for the database root
148
- app?: firebase.app.App, instance?: string);
149
- /**
150
- * Returns a [`Reference`](/docs/reference/admin/node/admin.database.Reference)
151
- * to the Database location where the triggering write occurred. Has
152
- * full read and write access.
153
- */
154
- get ref(): firebase.database.Reference;
155
- /**
156
- * The key (last part of the path) of the location of this `DataSnapshot`.
157
- *
158
- * The last token in a Database location is considered its key. For example,
159
- * "ada" is the key for the `/users/ada/` node. Accessing the key on any
160
- * `DataSnapshot` will return the key for the location that generated it.
161
- * However, accessing the key on the root URL of a Database will return `null`.
162
- */
163
- get key(): string;
164
- /**
165
- * Extracts a JavaScript value from a `DataSnapshot`.
166
- *
167
- * Depending on the data in a `DataSnapshot`, the `val()` method may return a
168
- * scalar type (string, number, or boolean), an array, or an object. It may also
169
- * return `null`, indicating that the `DataSnapshot` is empty (contains no
170
- * data).
171
- *
172
- * @return The DataSnapshot's contents as a JavaScript value (Object,
173
- * Array, string, number, boolean, or `null`).
174
- */
175
- val(): any;
176
- /**
177
- * Exports the entire contents of the `DataSnapshot` as a JavaScript object.
178
- *
179
- * The `exportVal()` method is similar to `val()`, except priority information
180
- * is included (if available), making it suitable for backing up your data.
181
- *
182
- * @return The contents of the `DataSnapshot` as a JavaScript value
183
- * (Object, Array, string, number, boolean, or `null`).
184
- */
185
- exportVal(): any;
186
- /**
187
- * Gets the priority value of the data in this `DataSnapshot`.
188
- *
189
- * As an alternative to using priority, applications can order collections by
190
- * ordinary properties. See [Sorting and filtering
191
- * data](/docs/database/web/lists-of-data#sorting_and_filtering_data).
192
- *
193
- * @return The priority value of the data.
194
- */
195
- getPriority(): string | number | null;
196
- /**
197
- * Returns `true` if this `DataSnapshot` contains any data. It is slightly more
198
- * efficient than using `snapshot.val() !== null`.
199
- *
200
- * @return `true` if this `DataSnapshot` contains any data; otherwise, `false`.
201
- */
202
- exists(): boolean;
203
- /**
204
- * Gets a `DataSnapshot` for the location at the specified relative path.
205
- *
206
- * The relative path can either be a simple child name (for example, "ada") or
207
- * a deeper slash-separated path (for example, "ada/name/first").
208
- *
209
- * @param path A relative path from this location to the desired child
210
- * location.
211
- * @return The specified child location.
212
- */
213
- child(childPath: string): DataSnapshot;
214
- /**
215
- * Enumerates the `DataSnapshot`s of the children items.
216
- *
217
- * Because of the way JavaScript objects work, the ordering of data in the
218
- * JavaScript object returned by `val()` is not guaranteed to match the ordering
219
- * on the server nor the ordering of `child_added` events. That is where
220
- * `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
221
- * will be iterated in their query order.
222
- *
223
- * If no explicit `orderBy*()` method is used, results are returned
224
- * ordered by key (unless priorities are used, in which case, results are
225
- * returned by priority).
226
- *
227
- * @param action A function that will be called for each child `DataSnapshot`.
228
- * The callback can return `true` to cancel further enumeration.
229
- *
230
- * @return `true` if enumeration was canceled due to your callback
231
- * returning `true`.
232
- */
233
- forEach(action: (a: DataSnapshot) => boolean | void): boolean;
234
- /**
235
- * Returns `true` if the specified child path has (non-`null`) data.
236
- *
237
- * @param path A relative path to the location of a potential child.
238
- * @return `true` if data exists at the specified child path; otherwise,
239
- * `false`.
240
- */
241
- hasChild(childPath: string): boolean;
242
- /**
243
- * Returns whether or not the `DataSnapshot` has any non-`null` child
244
- * properties.
245
- *
246
- * You can use `hasChildren()` to determine if a `DataSnapshot` has any
247
- * children. If it does, you can enumerate them using `forEach()`. If it
248
- * doesn't, then either this snapshot contains a primitive value (which can be
249
- * retrieved with `val()`) or it is empty (in which case, `val()` will return
250
- * `null`).
251
- *
252
- * @return `true` if this snapshot has any children; else `false`.
253
- */
254
- hasChildren(): boolean;
255
- /**
256
- * Returns the number of child properties of this `DataSnapshot`.
257
- *
258
- * @return Number of child properties of this `DataSnapshot`.
259
- */
260
- numChildren(): number;
261
- /**
262
- * Returns a JSON-serializable representation of this object.
263
- *
264
- * @return A JSON-serializable representation of this object.
265
- */
266
- toJSON(): Object;
267
- /** Recursive function to check if keys are numeric & convert node object to array if they are
268
- *
269
- * @hidden
270
- */
271
- private _checkAndConvertToArray;
272
- /** @hidden */
273
- private _dup;
274
- /** @hidden */
275
- private _fullPath;
276
- }
@@ -21,10 +21,11 @@
21
21
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.DataSnapshot = exports.extractInstanceAndPath = exports.RefBuilder = exports._refWithOptions = exports.InstanceBuilder = exports._instanceWithOptions = exports.ref = exports.instance = exports.service = exports.provider = void 0;
25
- const _ = require("lodash");
24
+ exports.extractInstanceAndPath = exports.RefBuilder = exports._refWithOptions = exports.InstanceBuilder = exports._instanceWithOptions = exports.ref = exports.instance = exports.service = exports.provider = exports.DataSnapshot = void 0;
26
25
  const apps_1 = require("../apps");
27
26
  const cloud_functions_1 = require("../cloud-functions");
27
+ const database_1 = require("../common/providers/database");
28
+ Object.defineProperty(exports, "DataSnapshot", { enumerable: true, get: function () { return database_1.DataSnapshot; } });
28
29
  const config_1 = require("../config");
29
30
  const path_1 = require("../utilities/path");
30
31
  const utils_1 = require("../utils");
@@ -152,8 +153,8 @@ class RefBuilder {
152
153
  this.options = options;
153
154
  this.changeConstructor = (raw) => {
154
155
  const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
155
- const before = new DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
156
- const after = new DataSnapshot((0, utils_1.applyChange)(raw.data.data, raw.data.delta), path, this.apps.admin, dbInstance);
156
+ const before = new database_1.DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
157
+ const after = new database_1.DataSnapshot((0, utils_1.applyChange)(raw.data.data, raw.data.delta), path, this.apps.admin, dbInstance);
157
158
  return {
158
159
  before,
159
160
  after,
@@ -194,7 +195,7 @@ class RefBuilder {
194
195
  onCreate(handler) {
195
196
  const dataConstructor = (raw) => {
196
197
  const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
197
- return new DataSnapshot(raw.data.delta, path, this.apps.admin, dbInstance);
198
+ return new database_1.DataSnapshot(raw.data.delta, path, this.apps.admin, dbInstance);
198
199
  };
199
200
  return this.onOperation(handler, 'ref.create', dataConstructor);
200
201
  }
@@ -209,7 +210,7 @@ class RefBuilder {
209
210
  onDelete(handler) {
210
211
  const dataConstructor = (raw) => {
211
212
  const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
212
- return new DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
213
+ return new database_1.DataSnapshot(raw.data.data, path, this.apps.admin, dbInstance);
213
214
  };
214
215
  return this.onOperation(handler, 'ref.delete', dataConstructor);
215
216
  }
@@ -260,248 +261,3 @@ function extractInstanceAndPath(resource, domain = 'firebaseio.com') {
260
261
  }
261
262
  }
262
263
  exports.extractInstanceAndPath = extractInstanceAndPath;
263
- /**
264
- * Interface representing a Firebase Realtime Database data snapshot.
265
- */
266
- class DataSnapshot {
267
- constructor(data, path, // path will be undefined for the database root
268
- app, instance) {
269
- var _a, _b;
270
- this.app = app;
271
- if ((_b = (_a = app === null || app === void 0 ? void 0 : app.options) === null || _a === void 0 ? void 0 : _a.databaseURL) === null || _b === void 0 ? void 0 : _b.startsWith('http:')) {
272
- // In this case we're dealing with an emulator
273
- this.instance = app.options.databaseURL;
274
- }
275
- else if (instance) {
276
- // SDK always supplies instance, but user's unit tests may not
277
- this.instance = instance;
278
- }
279
- else if (app) {
280
- this.instance = app.options.databaseURL;
281
- }
282
- else if (process.env.GCLOUD_PROJECT) {
283
- this.instance =
284
- 'https://' + process.env.GCLOUD_PROJECT + '.firebaseio.com';
285
- }
286
- this._path = path;
287
- this._data = data;
288
- }
289
- /**
290
- * Returns a [`Reference`](/docs/reference/admin/node/admin.database.Reference)
291
- * to the Database location where the triggering write occurred. Has
292
- * full read and write access.
293
- */
294
- get ref() {
295
- if (!this.app) {
296
- // may be unpopulated in user's unit tests
297
- throw new Error('Please supply a Firebase app in the constructor for DataSnapshot' +
298
- ' in order to use the .ref method.');
299
- }
300
- if (!this._ref) {
301
- this._ref = this.app.database(this.instance).ref(this._fullPath());
302
- }
303
- return this._ref;
304
- }
305
- /**
306
- * The key (last part of the path) of the location of this `DataSnapshot`.
307
- *
308
- * The last token in a Database location is considered its key. For example,
309
- * "ada" is the key for the `/users/ada/` node. Accessing the key on any
310
- * `DataSnapshot` will return the key for the location that generated it.
311
- * However, accessing the key on the root URL of a Database will return `null`.
312
- */
313
- get key() {
314
- const last = _.last((0, path_1.pathParts)(this._fullPath()));
315
- return !last || last === '' ? null : last;
316
- }
317
- /**
318
- * Extracts a JavaScript value from a `DataSnapshot`.
319
- *
320
- * Depending on the data in a `DataSnapshot`, the `val()` method may return a
321
- * scalar type (string, number, or boolean), an array, or an object. It may also
322
- * return `null`, indicating that the `DataSnapshot` is empty (contains no
323
- * data).
324
- *
325
- * @return The DataSnapshot's contents as a JavaScript value (Object,
326
- * Array, string, number, boolean, or `null`).
327
- */
328
- val() {
329
- const parts = (0, path_1.pathParts)(this._childPath);
330
- const source = this._data;
331
- const node = _.cloneDeep(parts.length ? _.get(source, parts, null) : source);
332
- return this._checkAndConvertToArray(node);
333
- }
334
- /**
335
- * Exports the entire contents of the `DataSnapshot` as a JavaScript object.
336
- *
337
- * The `exportVal()` method is similar to `val()`, except priority information
338
- * is included (if available), making it suitable for backing up your data.
339
- *
340
- * @return The contents of the `DataSnapshot` as a JavaScript value
341
- * (Object, Array, string, number, boolean, or `null`).
342
- */
343
- exportVal() {
344
- return this.val();
345
- }
346
- /**
347
- * Gets the priority value of the data in this `DataSnapshot`.
348
- *
349
- * As an alternative to using priority, applications can order collections by
350
- * ordinary properties. See [Sorting and filtering
351
- * data](/docs/database/web/lists-of-data#sorting_and_filtering_data).
352
- *
353
- * @return The priority value of the data.
354
- */
355
- getPriority() {
356
- return 0;
357
- }
358
- /**
359
- * Returns `true` if this `DataSnapshot` contains any data. It is slightly more
360
- * efficient than using `snapshot.val() !== null`.
361
- *
362
- * @return `true` if this `DataSnapshot` contains any data; otherwise, `false`.
363
- */
364
- exists() {
365
- return !_.isNull(this.val());
366
- }
367
- /**
368
- * Gets a `DataSnapshot` for the location at the specified relative path.
369
- *
370
- * The relative path can either be a simple child name (for example, "ada") or
371
- * a deeper slash-separated path (for example, "ada/name/first").
372
- *
373
- * @param path A relative path from this location to the desired child
374
- * location.
375
- * @return The specified child location.
376
- */
377
- child(childPath) {
378
- if (!childPath) {
379
- return this;
380
- }
381
- return this._dup(childPath);
382
- }
383
- /**
384
- * Enumerates the `DataSnapshot`s of the children items.
385
- *
386
- * Because of the way JavaScript objects work, the ordering of data in the
387
- * JavaScript object returned by `val()` is not guaranteed to match the ordering
388
- * on the server nor the ordering of `child_added` events. That is where
389
- * `forEach()` comes in handy. It guarantees the children of a `DataSnapshot`
390
- * will be iterated in their query order.
391
- *
392
- * If no explicit `orderBy*()` method is used, results are returned
393
- * ordered by key (unless priorities are used, in which case, results are
394
- * returned by priority).
395
- *
396
- * @param action A function that will be called for each child `DataSnapshot`.
397
- * The callback can return `true` to cancel further enumeration.
398
- *
399
- * @return `true` if enumeration was canceled due to your callback
400
- * returning `true`.
401
- */
402
- forEach(action) {
403
- const val = this.val();
404
- if (_.isPlainObject(val)) {
405
- return _.some(val, (value, key) => action(this.child(key)) === true);
406
- }
407
- return false;
408
- }
409
- /**
410
- * Returns `true` if the specified child path has (non-`null`) data.
411
- *
412
- * @param path A relative path to the location of a potential child.
413
- * @return `true` if data exists at the specified child path; otherwise,
414
- * `false`.
415
- */
416
- hasChild(childPath) {
417
- return this.child(childPath).exists();
418
- }
419
- /**
420
- * Returns whether or not the `DataSnapshot` has any non-`null` child
421
- * properties.
422
- *
423
- * You can use `hasChildren()` to determine if a `DataSnapshot` has any
424
- * children. If it does, you can enumerate them using `forEach()`. If it
425
- * doesn't, then either this snapshot contains a primitive value (which can be
426
- * retrieved with `val()`) or it is empty (in which case, `val()` will return
427
- * `null`).
428
- *
429
- * @return `true` if this snapshot has any children; else `false`.
430
- */
431
- hasChildren() {
432
- const val = this.val();
433
- return _.isPlainObject(val) && _.keys(val).length > 0;
434
- }
435
- /**
436
- * Returns the number of child properties of this `DataSnapshot`.
437
- *
438
- * @return Number of child properties of this `DataSnapshot`.
439
- */
440
- numChildren() {
441
- const val = this.val();
442
- return _.isPlainObject(val) ? Object.keys(val).length : 0;
443
- }
444
- /**
445
- * Returns a JSON-serializable representation of this object.
446
- *
447
- * @return A JSON-serializable representation of this object.
448
- */
449
- toJSON() {
450
- return this.val();
451
- }
452
- /** Recursive function to check if keys are numeric & convert node object to array if they are
453
- *
454
- * @hidden
455
- */
456
- _checkAndConvertToArray(node) {
457
- if (node === null || typeof node === 'undefined') {
458
- return null;
459
- }
460
- if (typeof node !== 'object') {
461
- return node;
462
- }
463
- const obj = {};
464
- let numKeys = 0;
465
- let maxKey = 0;
466
- let allIntegerKeys = true;
467
- for (const key in node) {
468
- if (!node.hasOwnProperty(key)) {
469
- continue;
470
- }
471
- const childNode = node[key];
472
- obj[key] = this._checkAndConvertToArray(childNode);
473
- numKeys++;
474
- const integerRegExp = /^(0|[1-9]\d*)$/;
475
- if (allIntegerKeys && integerRegExp.test(key)) {
476
- maxKey = Math.max(maxKey, Number(key));
477
- }
478
- else {
479
- allIntegerKeys = false;
480
- }
481
- }
482
- if (allIntegerKeys && maxKey < 2 * numKeys) {
483
- // convert to array.
484
- const array = [];
485
- _.forOwn(obj, (val, key) => {
486
- array[key] = val;
487
- });
488
- return array;
489
- }
490
- return obj;
491
- }
492
- /** @hidden */
493
- _dup(childPath) {
494
- const dup = new DataSnapshot(this._data, undefined, this.app, this.instance);
495
- [dup._path, dup._childPath] = [this._path, this._childPath];
496
- if (childPath) {
497
- dup._childPath = (0, path_1.joinPath)(dup._childPath, childPath);
498
- }
499
- return dup;
500
- }
501
- /** @hidden */
502
- _fullPath() {
503
- const out = (this._path || '') + '/' + (this._childPath || '');
504
- return out;
505
- }
506
- }
507
- exports.DataSnapshot = DataSnapshot;
@@ -1,5 +1,6 @@
1
1
  import * as firebase from 'firebase-admin';
2
- import { Change, CloudFunction, Event, EventContext } from '../cloud-functions';
2
+ import { CloudFunction, Event, EventContext } from '../cloud-functions';
3
+ import { Change } from '../common/change';
3
4
  import { DeploymentOptions } from '../function-configuration';
4
5
  /** @hidden */
5
6
  export declare const provider = "google.firestore";
@@ -27,6 +27,7 @@ const _ = require("lodash");
27
27
  const path_1 = require("path");
28
28
  const apps_1 = require("../apps");
29
29
  const cloud_functions_1 = require("../cloud-functions");
30
+ const change_1 = require("../common/change");
30
31
  const encoder_1 = require("../encoder");
31
32
  const logger = require("../logger");
32
33
  /** @hidden */
@@ -147,7 +148,7 @@ function beforeSnapshotConstructor(event) {
147
148
  }
148
149
  exports.beforeSnapshotConstructor = beforeSnapshotConstructor;
149
150
  function changeConstructor(raw) {
150
- return cloud_functions_1.Change.fromObjects(beforeSnapshotConstructor(raw), snapshotConstructor(raw));
151
+ return change_1.Change.fromObjects(beforeSnapshotConstructor(raw), snapshotConstructor(raw));
151
152
  }
152
153
  class DocumentBuilder {
153
154
  /** @hidden */