firebase-functions 6.6.0 → 7.0.0-rc.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 (156) hide show
  1. package/lib/_virtual/rolldown_runtime.js +34 -0
  2. package/lib/bin/firebase-functions.js +78 -103
  3. package/lib/common/app.js +35 -55
  4. package/lib/common/change.js +54 -75
  5. package/lib/common/config.js +41 -41
  6. package/lib/common/debug.js +23 -47
  7. package/lib/common/encoding.js +59 -82
  8. package/lib/common/onInit.js +26 -28
  9. package/lib/common/options.js +22 -42
  10. package/lib/common/params.d.ts +6 -6
  11. package/lib/common/params.js +0 -23
  12. package/lib/common/providers/database.js +270 -300
  13. package/lib/common/providers/firestore.js +66 -92
  14. package/lib/common/providers/https.d.ts +0 -1
  15. package/lib/common/providers/https.js +537 -539
  16. package/lib/common/providers/identity.js +393 -444
  17. package/lib/common/providers/tasks.js +64 -98
  18. package/lib/common/timezone.js +544 -542
  19. package/lib/common/trace.d.ts +0 -1
  20. package/lib/common/trace.js +63 -55
  21. package/lib/common/utilities/assertions.d.ts +11 -0
  22. package/lib/common/utilities/assertions.js +18 -0
  23. package/lib/common/utilities/encoder.js +20 -37
  24. package/lib/common/utilities/path-pattern.js +106 -132
  25. package/lib/common/utilities/path.js +28 -27
  26. package/lib/common/utilities/utils.js +23 -45
  27. package/lib/esm/_virtual/rolldown_runtime.mjs +16 -0
  28. package/lib/esm/bin/firebase-functions.mjs +91 -0
  29. package/lib/esm/common/app.mjs +39 -0
  30. package/lib/esm/common/change.mjs +57 -0
  31. package/lib/esm/common/config.mjs +45 -0
  32. package/lib/esm/common/debug.mjs +28 -0
  33. package/lib/esm/common/encoding.mjs +69 -0
  34. package/lib/esm/common/onInit.mjs +33 -0
  35. package/lib/esm/common/options.mjs +22 -0
  36. package/lib/esm/common/params.mjs +1 -0
  37. package/lib/esm/common/providers/database.mjs +269 -0
  38. package/lib/esm/common/providers/firestore.mjs +78 -0
  39. package/lib/esm/common/providers/https.mjs +573 -0
  40. package/lib/esm/common/providers/identity.mjs +428 -0
  41. package/lib/esm/common/providers/tasks.mjs +67 -0
  42. package/lib/esm/common/timezone.mjs +544 -0
  43. package/lib/esm/common/trace.mjs +73 -0
  44. package/lib/esm/common/utilities/assertions.mjs +17 -0
  45. package/lib/esm/common/utilities/encoder.mjs +21 -0
  46. package/lib/esm/common/utilities/path-pattern.mjs +116 -0
  47. package/lib/esm/common/utilities/path.mjs +35 -0
  48. package/lib/esm/common/utilities/utils.mjs +29 -0
  49. package/lib/esm/function-configuration.mjs +1 -0
  50. package/lib/esm/logger/common.mjs +23 -0
  51. package/lib/esm/logger/compat.mjs +25 -0
  52. package/lib/esm/logger/index.mjs +131 -0
  53. package/lib/esm/params/index.mjs +160 -0
  54. package/lib/esm/params/types.mjs +400 -0
  55. package/lib/esm/runtime/loader.mjs +132 -0
  56. package/lib/esm/runtime/manifest.mjs +134 -0
  57. package/lib/esm/types/global.d.mjs +1 -0
  58. package/lib/esm/v1/cloud-functions.mjs +206 -0
  59. package/lib/esm/v1/config.mjs +14 -0
  60. package/lib/esm/v1/function-builder.mjs +252 -0
  61. package/lib/esm/v1/function-configuration.mjs +72 -0
  62. package/lib/esm/v1/index.mjs +27 -0
  63. package/lib/esm/v1/providers/analytics.mjs +212 -0
  64. package/lib/esm/v1/providers/auth.mjs +156 -0
  65. package/lib/esm/v1/providers/database.mjs +243 -0
  66. package/lib/esm/v1/providers/firestore.mjs +131 -0
  67. package/lib/esm/v1/providers/https.mjs +82 -0
  68. package/lib/esm/v1/providers/pubsub.mjs +175 -0
  69. package/lib/esm/v1/providers/remoteConfig.mjs +64 -0
  70. package/lib/esm/v1/providers/storage.mjs +163 -0
  71. package/lib/esm/v1/providers/tasks.mjs +63 -0
  72. package/lib/esm/v1/providers/testLab.mjs +94 -0
  73. package/lib/esm/v2/core.mjs +4 -0
  74. package/lib/esm/v2/index.mjs +28 -0
  75. package/lib/esm/v2/options.mjs +102 -0
  76. package/lib/esm/v2/providers/alerts/alerts.mjs +85 -0
  77. package/lib/esm/v2/providers/alerts/appDistribution.mjs +75 -0
  78. package/lib/esm/v2/providers/alerts/billing.mjs +51 -0
  79. package/lib/esm/v2/providers/alerts/crashlytics.mjs +122 -0
  80. package/lib/esm/v2/providers/alerts/index.mjs +22 -0
  81. package/lib/esm/v2/providers/alerts/performance.mjs +66 -0
  82. package/lib/esm/v2/providers/database.mjs +197 -0
  83. package/lib/esm/v2/providers/dataconnect.mjs +130 -0
  84. package/lib/esm/v2/providers/eventarc.mjs +51 -0
  85. package/lib/esm/v2/providers/firestore.mjs +294 -0
  86. package/lib/esm/v2/providers/https.mjs +210 -0
  87. package/lib/esm/v2/providers/identity.mjs +103 -0
  88. package/lib/esm/v2/providers/pubsub.mjs +148 -0
  89. package/lib/esm/v2/providers/remoteConfig.mjs +52 -0
  90. package/lib/esm/v2/providers/scheduler.mjs +84 -0
  91. package/lib/esm/v2/providers/storage.mjs +155 -0
  92. package/lib/esm/v2/providers/tasks.mjs +65 -0
  93. package/lib/esm/v2/providers/testLab.mjs +53 -0
  94. package/lib/esm/v2/trace.mjs +20 -0
  95. package/lib/function-configuration.d.ts +0 -0
  96. package/lib/function-configuration.js +0 -0
  97. package/lib/logger/common.js +21 -41
  98. package/lib/logger/compat.js +18 -33
  99. package/lib/logger/index.js +119 -130
  100. package/lib/params/index.d.ts +4 -2
  101. package/lib/params/index.js +150 -144
  102. package/lib/params/types.js +389 -423
  103. package/lib/runtime/loader.js +114 -148
  104. package/lib/runtime/manifest.js +106 -126
  105. package/lib/types/global.d.js +0 -0
  106. package/lib/v1/cloud-functions.d.ts +2 -2
  107. package/lib/v1/cloud-functions.js +193 -241
  108. package/lib/v1/config.d.ts +4 -7
  109. package/lib/v1/config.js +13 -75
  110. package/lib/v1/function-builder.js +239 -368
  111. package/lib/v1/function-configuration.js +70 -63
  112. package/lib/v1/index.js +118 -73
  113. package/lib/v1/providers/analytics.js +188 -235
  114. package/lib/v1/providers/auth.d.ts +2 -1
  115. package/lib/v1/providers/auth.js +159 -164
  116. package/lib/v1/providers/database.js +237 -242
  117. package/lib/v1/providers/firestore.js +131 -130
  118. package/lib/v1/providers/https.d.ts +2 -1
  119. package/lib/v1/providers/https.js +79 -86
  120. package/lib/v1/providers/pubsub.js +175 -172
  121. package/lib/v1/providers/remoteConfig.js +64 -68
  122. package/lib/v1/providers/storage.js +161 -163
  123. package/lib/v1/providers/tasks.d.ts +1 -1
  124. package/lib/v1/providers/tasks.js +65 -80
  125. package/lib/v1/providers/testLab.js +94 -94
  126. package/lib/v2/core.d.ts +1 -1
  127. package/lib/v2/core.js +5 -32
  128. package/lib/v2/index.d.ts +6 -3
  129. package/lib/v2/index.js +123 -75
  130. package/lib/v2/options.js +88 -114
  131. package/lib/v2/providers/alerts/alerts.js +76 -95
  132. package/lib/v2/providers/alerts/appDistribution.js +73 -78
  133. package/lib/v2/providers/alerts/billing.js +49 -53
  134. package/lib/v2/providers/alerts/crashlytics.js +110 -102
  135. package/lib/v2/providers/alerts/index.js +56 -53
  136. package/lib/v2/providers/alerts/performance.js +64 -74
  137. package/lib/v2/providers/database.js +177 -180
  138. package/lib/v2/providers/dataconnect.d.ts +95 -0
  139. package/lib/v2/providers/dataconnect.js +137 -0
  140. package/lib/v2/providers/eventarc.js +55 -77
  141. package/lib/v2/providers/firestore.js +262 -260
  142. package/lib/v2/providers/https.d.ts +3 -2
  143. package/lib/v2/providers/https.js +210 -247
  144. package/lib/v2/providers/identity.d.ts +2 -1
  145. package/lib/v2/providers/identity.js +96 -105
  146. package/lib/v2/providers/pubsub.js +149 -167
  147. package/lib/v2/providers/remoteConfig.js +54 -63
  148. package/lib/v2/providers/scheduler.js +84 -96
  149. package/lib/v2/providers/storage.js +147 -162
  150. package/lib/v2/providers/tasks.d.ts +1 -1
  151. package/lib/v2/providers/tasks.js +68 -95
  152. package/lib/v2/providers/testLab.js +55 -64
  153. package/lib/v2/trace.js +18 -19
  154. package/package.json +290 -226
  155. package/protos/compiledFirestore.mjs +3512 -0
  156. package/protos/update.sh +28 -7
@@ -0,0 +1,212 @@
1
+ import { __export } from "../../_virtual/rolldown_runtime.mjs";
2
+ import { makeCloudFunction } from "../cloud-functions.mjs";
3
+
4
+ //#region src/v1/providers/analytics.ts
5
+ var analytics_exports = /* @__PURE__ */ __export({
6
+ AnalyticsEvent: () => AnalyticsEvent,
7
+ AnalyticsEventBuilder: () => AnalyticsEventBuilder,
8
+ ExportBundleInfo: () => ExportBundleInfo,
9
+ UserDimensions: () => UserDimensions,
10
+ UserPropertyValue: () => UserPropertyValue,
11
+ _eventWithOptions: () => _eventWithOptions,
12
+ event: () => event,
13
+ provider: () => provider,
14
+ service: () => service
15
+ });
16
+ /** @internal */
17
+ const provider = "google.analytics";
18
+ /** @internal */
19
+ const service = "app-measurement.com";
20
+ /**
21
+ * Registers a function to handle analytics events.
22
+ *
23
+ * @param analyticsEventType Name of the analytics event type to which
24
+ * this Cloud Function is scoped.
25
+ *
26
+ * @returns Analytics event builder interface.
27
+ */
28
+ function event(analyticsEventType) {
29
+ return _eventWithOptions(analyticsEventType, {});
30
+ }
31
+ /** @internal */
32
+ function _eventWithOptions(analyticsEventType, options) {
33
+ return new AnalyticsEventBuilder(() => {
34
+ if (!process.env.GCLOUD_PROJECT) {
35
+ throw new Error("process.env.GCLOUD_PROJECT is not set.");
36
+ }
37
+ return "projects/" + process.env.GCLOUD_PROJECT + "/events/" + analyticsEventType;
38
+ }, options);
39
+ }
40
+ /**
41
+ * The Firebase Analytics event builder interface.
42
+ *
43
+ * Access via `functions.analytics.event()`.
44
+ */
45
+ var AnalyticsEventBuilder = class {
46
+ /** @hidden */
47
+ constructor(triggerResource, options) {
48
+ this.triggerResource = triggerResource;
49
+ this.options = options;
50
+ }
51
+ /**
52
+ * Event handler that fires every time a Firebase Analytics event occurs.
53
+ *
54
+ * @param handler Event handler that fires every time a Firebase Analytics event
55
+ * occurs.
56
+ *
57
+ * @returns A function that you can export and deploy.
58
+ */
59
+ onLog(handler) {
60
+ const dataConstructor = (raw) => {
61
+ return new AnalyticsEvent(raw.data);
62
+ };
63
+ return makeCloudFunction({
64
+ handler,
65
+ provider,
66
+ eventType: "event.log",
67
+ service,
68
+ legacyEventType: `providers/google.firebase.analytics/eventTypes/event.log`,
69
+ triggerResource: this.triggerResource,
70
+ dataConstructor,
71
+ options: this.options
72
+ });
73
+ }
74
+ };
75
+ /** Interface representing a Firebase Analytics event that was logged for a specific user. */
76
+ var AnalyticsEvent = class {
77
+ /** @hidden */
78
+ constructor(wireFormat) {
79
+ this.params = {};
80
+ if (wireFormat.eventDim && wireFormat.eventDim.length > 0) {
81
+ const eventDim = wireFormat.eventDim[0];
82
+ copyField(eventDim, this, "name");
83
+ copyField(eventDim, this, "params", (p) => mapKeys(p, unwrapValue));
84
+ copyFieldTo(eventDim, this, "valueInUsd", "valueInUSD");
85
+ copyFieldTo(eventDim, this, "date", "reportingDate");
86
+ copyTimestampToString(eventDim, this, "timestampMicros", "logTime");
87
+ copyTimestampToString(eventDim, this, "previousTimestampMicros", "previousLogTime");
88
+ }
89
+ copyFieldTo(wireFormat, this, "userDim", "user", (dim) => new UserDimensions(dim));
90
+ }
91
+ };
92
+ function isValidUserProperty(property) {
93
+ if (property == null || typeof property !== "object" || !("value" in property)) {
94
+ return false;
95
+ }
96
+ const { value } = property;
97
+ if (value == null) {
98
+ return false;
99
+ }
100
+ if (typeof value === "object" && Object.keys(value).length === 0) {
101
+ return false;
102
+ }
103
+ return true;
104
+ }
105
+ /**
106
+ * Interface representing the user who triggered the events.
107
+ */
108
+ var UserDimensions = class {
109
+ /** @hidden */
110
+ constructor(wireFormat) {
111
+ copyFields(wireFormat, this, [
112
+ "userId",
113
+ "deviceInfo",
114
+ "geoInfo",
115
+ "appInfo"
116
+ ]);
117
+ copyTimestampToString(wireFormat, this, "firstOpenTimestampMicros", "firstOpenTime");
118
+ this.userProperties = {};
119
+ copyField(wireFormat, this, "userProperties", (r) => {
120
+ const entries = Object.entries(r).filter(([, v]) => isValidUserProperty(v)).map(([k, v]) => [k, new UserPropertyValue(v)]);
121
+ return Object.fromEntries(entries);
122
+ });
123
+ copyField(wireFormat, this, "bundleInfo", (r) => new ExportBundleInfo(r));
124
+ if (!this.userId && this.userProperties["user_id"]) {
125
+ this.userId = this.userProperties["user_id"].value;
126
+ }
127
+ }
128
+ };
129
+ /** Predefined or custom properties stored on the client side. */
130
+ var UserPropertyValue = class {
131
+ /** @hidden */
132
+ constructor(wireFormat) {
133
+ copyField(wireFormat, this, "value", unwrapValueAsString);
134
+ copyTimestampToString(wireFormat, this, "setTimestampUsec", "setTime");
135
+ }
136
+ };
137
+ /** Interface representing the bundle these events were uploaded to. */
138
+ var ExportBundleInfo = class {
139
+ /** @hidden */
140
+ constructor(wireFormat) {
141
+ copyField(wireFormat, this, "bundleSequenceId");
142
+ copyTimestampToMillis(wireFormat, this, "serverTimestampOffsetMicros", "serverTimestampOffset");
143
+ }
144
+ };
145
+ /** @hidden */
146
+ function copyFieldTo(from, to, fromField, toField, transform) {
147
+ if (typeof from[fromField] === "undefined") {
148
+ return;
149
+ }
150
+ if (transform) {
151
+ to[toField] = transform(from[fromField]);
152
+ return;
153
+ }
154
+ to[toField] = from[fromField];
155
+ }
156
+ /** @hidden */
157
+ function copyField(from, to, field, transform = (from$1) => from$1) {
158
+ copyFieldTo(from, to, field, field, transform);
159
+ }
160
+ /** @hidden */
161
+ function copyFields(from, to, fields) {
162
+ for (const field of fields) {
163
+ copyField(from, to, field);
164
+ }
165
+ }
166
+ function mapKeys(obj, transform) {
167
+ const entries = Object.entries(obj).map(([k, v]) => [k, transform(v)]);
168
+ return Object.fromEntries(entries);
169
+ }
170
+ /** @hidden */
171
+ function unwrapValueAsString(wrapped) {
172
+ if (!wrapped || typeof wrapped !== "object") {
173
+ return "";
174
+ }
175
+ const keys = Object.keys(wrapped);
176
+ if (keys.length === 0) {
177
+ return "";
178
+ }
179
+ const key = keys[0];
180
+ const value = wrapped[key];
181
+ if (value === null || value === undefined) {
182
+ return "";
183
+ }
184
+ return value.toString();
185
+ }
186
+ /** @hidden */
187
+ const xValueNumberFields = [
188
+ "intValue",
189
+ "floatValue",
190
+ "doubleValue"
191
+ ];
192
+ /** @hidden */
193
+ function unwrapValue(wrapped) {
194
+ const key = Object.keys(wrapped)[0];
195
+ const value = unwrapValueAsString(wrapped);
196
+ return xValueNumberFields.includes(key) ? Number(value) : value;
197
+ }
198
+ /** @hidden */
199
+ function copyTimestampToMillis(from, to, fromName, toName) {
200
+ if (from[fromName] !== undefined) {
201
+ to[toName] = Math.round(from[fromName] / 1e3);
202
+ }
203
+ }
204
+ /** @hidden */
205
+ function copyTimestampToString(from, to, fromName, toName) {
206
+ if (from[fromName] !== undefined) {
207
+ to[toName] = new Date(from[fromName] / 1e3).toISOString();
208
+ }
209
+ }
210
+
211
+ //#endregion
212
+ export { AnalyticsEvent, AnalyticsEventBuilder, ExportBundleInfo, UserDimensions, UserPropertyValue, _eventWithOptions, analytics_exports, event, provider, service };
@@ -0,0 +1,156 @@
1
+ import { __export } from "../../_virtual/rolldown_runtime.mjs";
2
+ import { initV1Endpoint } from "../../runtime/manifest.mjs";
3
+ import { makeCloudFunction, optionsToEndpoint, optionsToTrigger } from "../cloud-functions.mjs";
4
+ import { HttpsError } from "../../common/providers/https.mjs";
5
+ import { UserRecordMetadata, userRecordConstructor, wrapHandler } from "../../common/providers/identity.mjs";
6
+
7
+ //#region src/v1/providers/auth.ts
8
+ var auth_exports = /* @__PURE__ */ __export({
9
+ HttpsError: () => HttpsError,
10
+ UserBuilder: () => UserBuilder,
11
+ UserRecordMetadata: () => UserRecordMetadata,
12
+ _userWithOptions: () => _userWithOptions,
13
+ provider: () => provider,
14
+ service: () => service,
15
+ user: () => user,
16
+ userRecordConstructor: () => userRecordConstructor
17
+ });
18
+ /** @internal */
19
+ const provider = "google.firebase.auth";
20
+ /** @internal */
21
+ const service = "firebaseauth.googleapis.com";
22
+ /**
23
+ * Handles events related to Firebase Auth users events.
24
+ *
25
+ * @param userOptions - Resource level options
26
+ * @returns UserBuilder - Builder used to create functions for Firebase Auth user lifecycle events
27
+ *
28
+ * @public
29
+ */
30
+ function user(userOptions) {
31
+ return _userWithOptions({}, userOptions || {});
32
+ }
33
+ /** @internal */
34
+ function _userWithOptions(options, userOptions) {
35
+ return new UserBuilder(() => {
36
+ if (!process.env.GCLOUD_PROJECT) {
37
+ throw new Error("process.env.GCLOUD_PROJECT is not set.");
38
+ }
39
+ return "projects/" + process.env.GCLOUD_PROJECT;
40
+ }, options, userOptions);
41
+ }
42
+ /**
43
+ * Builder used to create functions for Firebase Auth user lifecycle events.
44
+ * @public
45
+ */
46
+ var UserBuilder = class UserBuilder {
47
+ static dataConstructor(raw) {
48
+ return userRecordConstructor(raw.data);
49
+ }
50
+ constructor(triggerResource, options, userOptions) {
51
+ this.triggerResource = triggerResource;
52
+ this.options = options;
53
+ this.userOptions = userOptions;
54
+ }
55
+ /**
56
+ * Responds to the creation of a Firebase Auth user.
57
+ *
58
+ * @param handler Event handler that responds to the creation of a Firebase Auth user.
59
+ *
60
+ * @public
61
+ */
62
+ onCreate(handler) {
63
+ return this.onOperation(handler, "user.create");
64
+ }
65
+ /**
66
+ * Responds to the deletion of a Firebase Auth user.
67
+ *
68
+ * @param handler Event handler that responds to the deletion of a Firebase Auth user.
69
+ *
70
+ * @public
71
+ */
72
+ onDelete(handler) {
73
+ return this.onOperation(handler, "user.delete");
74
+ }
75
+ /**
76
+ * Blocks request to create a Firebase Auth user.
77
+ *
78
+ * @param handler Event handler that blocks creation of a Firebase Auth user.
79
+ *
80
+ * @public
81
+ */
82
+ beforeCreate(handler) {
83
+ return this.beforeOperation(handler, "beforeCreate");
84
+ }
85
+ /**
86
+ * Blocks request to sign-in a Firebase Auth user.
87
+ *
88
+ * @param handler Event handler that blocks sign-in of a Firebase Auth user.
89
+ *
90
+ * @public
91
+ */
92
+ beforeSignIn(handler) {
93
+ return this.beforeOperation(handler, "beforeSignIn");
94
+ }
95
+ beforeEmail(handler) {
96
+ return this.beforeOperation(handler, "beforeSendEmail");
97
+ }
98
+ beforeSms(handler) {
99
+ return this.beforeOperation(handler, "beforeSendSms");
100
+ }
101
+ onOperation(handler, eventType) {
102
+ return makeCloudFunction({
103
+ handler,
104
+ provider,
105
+ eventType,
106
+ service,
107
+ triggerResource: this.triggerResource,
108
+ dataConstructor: UserBuilder.dataConstructor,
109
+ legacyEventType: `providers/firebase.auth/eventTypes/${eventType}`,
110
+ options: this.options
111
+ });
112
+ }
113
+ beforeOperation(handler, eventType) {
114
+ const accessToken = this.userOptions?.blockingOptions?.accessToken || false;
115
+ const idToken = this.userOptions?.blockingOptions?.idToken || false;
116
+ const refreshToken = this.userOptions?.blockingOptions?.refreshToken || false;
117
+ const annotatedHandler = Object.assign(handler, { platform: "gcfv1" });
118
+ const func = wrapHandler(eventType, annotatedHandler);
119
+ const legacyEventType = `providers/cloud.auth/eventTypes/user.${eventType}`;
120
+ func.__trigger = {
121
+ labels: {},
122
+ ...optionsToTrigger(this.options),
123
+ blockingTrigger: {
124
+ eventType: legacyEventType,
125
+ options: {
126
+ accessToken,
127
+ idToken,
128
+ refreshToken
129
+ }
130
+ }
131
+ };
132
+ func.__endpoint = {
133
+ platform: "gcfv1",
134
+ labels: {},
135
+ ...initV1Endpoint(this.options),
136
+ ...optionsToEndpoint(this.options),
137
+ blockingTrigger: {
138
+ eventType: legacyEventType,
139
+ options: {
140
+ accessToken,
141
+ idToken,
142
+ refreshToken
143
+ }
144
+ }
145
+ };
146
+ func.__requiredAPIs = [{
147
+ api: "identitytoolkit.googleapis.com",
148
+ reason: "Needed for auth blocking functions"
149
+ }];
150
+ func.run = handler;
151
+ return func;
152
+ }
153
+ };
154
+
155
+ //#endregion
156
+ export { HttpsError, UserBuilder, UserRecordMetadata, _userWithOptions, auth_exports, provider, service, user, userRecordConstructor };
@@ -0,0 +1,243 @@
1
+ import { __export } from "../../_virtual/rolldown_runtime.mjs";
2
+ import { firebaseConfig } from "../../common/config.mjs";
3
+ import { getApp } from "../../common/app.mjs";
4
+ import { makeCloudFunction } from "../cloud-functions.mjs";
5
+ import { normalizePath } from "../../common/utilities/path.mjs";
6
+ import { DataSnapshot } from "../../common/providers/database.mjs";
7
+ import { applyChange } from "../../common/utilities/utils.mjs";
8
+
9
+ //#region src/v1/providers/database.ts
10
+ var database_exports = /* @__PURE__ */ __export({
11
+ DataSnapshot: () => DataSnapshot,
12
+ InstanceBuilder: () => InstanceBuilder,
13
+ RefBuilder: () => RefBuilder,
14
+ _instanceWithOptions: () => _instanceWithOptions,
15
+ _refWithOptions: () => _refWithOptions,
16
+ extractInstanceAndPath: () => extractInstanceAndPath,
17
+ instance: () => instance,
18
+ provider: () => provider,
19
+ ref: () => ref,
20
+ service: () => service
21
+ });
22
+ /** @internal */
23
+ const provider = "google.firebase.database";
24
+ /** @internal */
25
+ const service = "firebaseio.com";
26
+ const databaseURLRegex = new RegExp("^https://([^.]+).");
27
+ const emulatorDatabaseURLRegex = new RegExp("^http://.*ns=([^&]+)");
28
+ /**
29
+ * Registers a function that triggers on events from a specific
30
+ * Firebase Realtime Database instance.
31
+ *
32
+ * @remarks
33
+ * Use this method together with `ref` to specify the instance on which to
34
+ * watch for database events. For example: `firebase.database.instance('my-app-db-2').ref('/foo/bar')`
35
+ *
36
+ * Note that `functions.database.ref` used without `instance` watches the
37
+ * *default* instance for events.
38
+ *
39
+ * @param instance The instance name of the database instance
40
+ * to watch for write events.
41
+ * @returns Firebase Realtime Database instance builder interface.
42
+ */
43
+ function instance(instance$1) {
44
+ return _instanceWithOptions(instance$1, {});
45
+ }
46
+ /**
47
+ * Registers a function that triggers on Firebase Realtime Database write
48
+ * events.
49
+ *
50
+ * @remarks
51
+ * This method behaves very similarly to the method of the same name in the
52
+ * client and Admin Firebase SDKs. Any change to the Database that affects the
53
+ * data at or below the provided `path` will fire an event in Cloud Functions.
54
+ *
55
+ * There are three important differences between listening to a Realtime
56
+ * Database event in Cloud Functions and using the Realtime Database in the
57
+ * client and Admin SDKs:
58
+ *
59
+ * 1. Cloud Functions allows wildcards in the `path` name. Any `path` component
60
+ * in curly brackets (`{}`) is a wildcard that matches all strings. The value
61
+ * that matched a certain invocation of a Cloud Function is returned as part
62
+ * of the [`EventContext.params`](cloud_functions_eventcontext.html#params object. For
63
+ * example, `ref("messages/{messageId}")` matches changes at
64
+ * `/messages/message1` or `/messages/message2`, resulting in
65
+ * `event.params.messageId` being set to `"message1"` or `"message2"`,
66
+ * respectively.
67
+ *
68
+ * 2. Cloud Functions do not fire an event for data that already existed before
69
+ * the Cloud Function was deployed.
70
+ *
71
+ * 3. Cloud Function events have access to more information, including a
72
+ * snapshot of the previous event data and information about the user who
73
+ * triggered the Cloud Function.
74
+ *
75
+ * @param path The path within the Database to watch for write events.
76
+ * @returns Firebase Realtime Database builder interface.
77
+ */
78
+ function ref(path) {
79
+ return _refWithOptions(path, {});
80
+ }
81
+ /** @internal */
82
+ function _instanceWithOptions(instance$1, options) {
83
+ return new InstanceBuilder(instance$1, options);
84
+ }
85
+ /**
86
+ * The Firebase Realtime Database instance builder interface.
87
+ *
88
+ * Access via [`database.instance()`](providers_database_.html#instance).
89
+ */
90
+ var InstanceBuilder = class {
91
+ constructor(instance$1, options) {
92
+ this.instance = instance$1;
93
+ this.options = options;
94
+ }
95
+ /**
96
+ * @returns Firebase Realtime Database reference builder interface.
97
+ */
98
+ ref(path) {
99
+ const normalized = normalizePath(path);
100
+ return new RefBuilder(() => `projects/_/instances/${this.instance}/refs/${normalized}`, this.options);
101
+ }
102
+ };
103
+ /** @internal */
104
+ function _refWithOptions(path, options) {
105
+ const resourceGetter = () => {
106
+ const normalized = normalizePath(path);
107
+ const databaseURL = firebaseConfig().databaseURL;
108
+ if (!databaseURL) {
109
+ throw new Error("Missing expected firebase config value databaseURL, " + "config is actually" + JSON.stringify(firebaseConfig()) + "\n If you are unit testing, please set process.env.FIREBASE_CONFIG");
110
+ }
111
+ let instance$1;
112
+ const prodMatch = databaseURL.match(databaseURLRegex);
113
+ if (prodMatch) {
114
+ instance$1 = prodMatch[1];
115
+ } else {
116
+ const emulatorMatch = databaseURL.match(emulatorDatabaseURLRegex);
117
+ if (emulatorMatch) {
118
+ instance$1 = emulatorMatch[1];
119
+ }
120
+ }
121
+ if (!instance$1) {
122
+ throw new Error("Invalid value for config firebase.databaseURL: " + databaseURL);
123
+ }
124
+ return `projects/_/instances/${instance$1}/refs/${normalized}`;
125
+ };
126
+ return new RefBuilder(resourceGetter, options);
127
+ }
128
+ /**
129
+ * The Firebase Realtime Database reference builder interface.
130
+ *
131
+ * Access via [`functions.database.ref()`](functions.database#.ref).
132
+ */
133
+ var RefBuilder = class {
134
+ constructor(triggerResource, options) {
135
+ this.triggerResource = triggerResource;
136
+ this.options = options;
137
+ this.changeConstructor = (raw) => {
138
+ const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
139
+ const before = new DataSnapshot(raw.data.data, path, getApp(), dbInstance);
140
+ const after = new DataSnapshot(applyChange(raw.data.data, raw.data.delta), path, getApp(), dbInstance);
141
+ return {
142
+ before,
143
+ after
144
+ };
145
+ };
146
+ }
147
+ /**
148
+ * Event handler that fires every time a Firebase Realtime Database write
149
+ * of any kind (creation, update, or delete) occurs.
150
+ *
151
+ * @param handler Event handler that runs every time a Firebase Realtime Database
152
+ * write occurs.
153
+ * @returns A function that you can export and deploy.
154
+ */
155
+ onWrite(handler) {
156
+ return this.onOperation(handler, "ref.write", this.changeConstructor);
157
+ }
158
+ /**
159
+ * Event handler that fires every time data is updated in
160
+ * Firebase Realtime Database.
161
+ *
162
+ * @param handler Event handler which is run every time a Firebase Realtime Database
163
+ * write occurs.
164
+ * @returns A function which you can export and deploy.
165
+ */
166
+ onUpdate(handler) {
167
+ return this.onOperation(handler, "ref.update", this.changeConstructor);
168
+ }
169
+ /**
170
+ * Event handler that fires every time new data is created in
171
+ * Firebase Realtime Database.
172
+ *
173
+ * @param handler Event handler that runs every time new data is created in
174
+ * Firebase Realtime Database.
175
+ * @returns A function that you can export and deploy.
176
+ */
177
+ onCreate(handler) {
178
+ const dataConstructor = (raw) => {
179
+ const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
180
+ return new DataSnapshot(raw.data.delta, path, getApp(), dbInstance);
181
+ };
182
+ return this.onOperation(handler, "ref.create", dataConstructor);
183
+ }
184
+ /**
185
+ * Event handler that fires every time data is deleted from
186
+ * Firebase Realtime Database.
187
+ *
188
+ * @param handler Event handler that runs every time data is deleted from
189
+ * Firebase Realtime Database.
190
+ * @returns A function that you can export and deploy.
191
+ */
192
+ onDelete(handler) {
193
+ const dataConstructor = (raw) => {
194
+ const [dbInstance, path] = extractInstanceAndPath(raw.context.resource.name, raw.context.domain);
195
+ return new DataSnapshot(raw.data.data, path, getApp(), dbInstance);
196
+ };
197
+ return this.onOperation(handler, "ref.delete", dataConstructor);
198
+ }
199
+ onOperation(handler, eventType, dataConstructor) {
200
+ return makeCloudFunction({
201
+ handler,
202
+ provider,
203
+ service,
204
+ eventType,
205
+ legacyEventType: `providers/${provider}/eventTypes/${eventType}`,
206
+ triggerResource: this.triggerResource,
207
+ dataConstructor,
208
+ options: this.options
209
+ });
210
+ }
211
+ };
212
+ const resourceRegex = /^projects\/([^/]+)\/instances\/([a-zA-Z0-9-]+)\/refs(\/.+)?/;
213
+ /**
214
+ * Utility function to extract database reference from resource string
215
+ *
216
+ * @param optional database domain override for the original of the source database.
217
+ * It defaults to `firebaseio.com`.
218
+ * Multi-region RTDB will be served from different domains.
219
+ * Since region is not part of the resource name, it is provided through context.
220
+ *
221
+ * @internal
222
+ */
223
+ function extractInstanceAndPath(resource, domain = "firebaseio.com") {
224
+ const match = resource.match(new RegExp(resourceRegex));
225
+ if (!match) {
226
+ throw new Error(`Unexpected resource string for Firebase Realtime Database event: ${resource}. ` + "Expected string in the format of \"projects/_/instances/{firebaseioSubdomain}/refs/{ref=**}\"");
227
+ }
228
+ const [, project, dbInstanceName, path] = match;
229
+ if (project !== "_") {
230
+ throw new Error(`Expect project to be '_' in a Firebase Realtime Database event`);
231
+ }
232
+ const emuHost = process.env.FIREBASE_DATABASE_EMULATOR_HOST;
233
+ if (emuHost) {
234
+ const dbInstance = `http://${emuHost}/?ns=${dbInstanceName}`;
235
+ return [dbInstance, path];
236
+ } else {
237
+ const dbInstance = "https://" + dbInstanceName + "." + domain;
238
+ return [dbInstance, path];
239
+ }
240
+ }
241
+
242
+ //#endregion
243
+ export { DataSnapshot, InstanceBuilder, RefBuilder, _instanceWithOptions, _refWithOptions, database_exports, extractInstanceAndPath, instance, provider, ref, service };