@firebase/data-connect 0.1.1 → 0.1.2

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 (57) hide show
  1. package/dist/index.cjs.js +1108 -1108
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm2017.js +1108 -1108
  4. package/dist/index.esm2017.js.map +1 -1
  5. package/dist/index.node.cjs.js +1123 -1123
  6. package/dist/index.node.cjs.js.map +1 -1
  7. package/dist/node-esm/index.node.esm.js +1123 -1123
  8. package/dist/node-esm/index.node.esm.js.map +1 -1
  9. package/dist/node-esm/src/api/DataConnect.d.ts +108 -108
  10. package/dist/node-esm/src/api/Mutation.d.ts +61 -61
  11. package/dist/node-esm/src/api/Reference.d.ts +51 -51
  12. package/dist/node-esm/src/api/index.d.ts +23 -23
  13. package/dist/node-esm/src/api/query.d.ts +96 -96
  14. package/dist/node-esm/src/api.browser.d.ts +34 -34
  15. package/dist/node-esm/src/api.node.d.ts +17 -17
  16. package/dist/node-esm/src/core/AppCheckTokenProvider.d.ts +30 -30
  17. package/dist/node-esm/src/core/FirebaseAuthProvider.d.ts +34 -34
  18. package/dist/node-esm/src/core/QueryManager.d.ts +36 -36
  19. package/dist/node-esm/src/core/error.d.ts +51 -51
  20. package/dist/node-esm/src/core/version.d.ts +23 -23
  21. package/dist/node-esm/src/index.d.ts +29 -29
  22. package/dist/node-esm/src/index.node.d.ts +18 -18
  23. package/dist/node-esm/src/logger.d.ts +20 -20
  24. package/dist/node-esm/src/network/fetch.d.ts +21 -21
  25. package/dist/node-esm/src/network/index.d.ts +17 -17
  26. package/dist/node-esm/src/network/transport/index.d.ts +43 -43
  27. package/dist/node-esm/src/network/transport/rest.d.ts +58 -58
  28. package/dist/node-esm/src/register.d.ts +1 -1
  29. package/dist/node-esm/src/util/encoder.d.ts +19 -19
  30. package/dist/node-esm/src/util/map.d.ts +17 -17
  31. package/dist/node-esm/src/util/url.d.ts +19 -19
  32. package/dist/node-esm/src/util/validateArgs.d.ts +33 -33
  33. package/dist/src/api/DataConnect.d.ts +108 -108
  34. package/dist/src/api/Mutation.d.ts +61 -61
  35. package/dist/src/api/Reference.d.ts +51 -51
  36. package/dist/src/api/index.d.ts +23 -23
  37. package/dist/src/api/query.d.ts +96 -96
  38. package/dist/src/api.browser.d.ts +34 -34
  39. package/dist/src/api.node.d.ts +17 -17
  40. package/dist/src/core/AppCheckTokenProvider.d.ts +30 -30
  41. package/dist/src/core/FirebaseAuthProvider.d.ts +34 -34
  42. package/dist/src/core/QueryManager.d.ts +36 -36
  43. package/dist/src/core/error.d.ts +51 -51
  44. package/dist/src/core/version.d.ts +23 -23
  45. package/dist/src/index.d.ts +29 -29
  46. package/dist/src/index.node.d.ts +18 -18
  47. package/dist/src/logger.d.ts +20 -20
  48. package/dist/src/network/fetch.d.ts +21 -21
  49. package/dist/src/network/index.d.ts +17 -17
  50. package/dist/src/network/transport/index.d.ts +43 -43
  51. package/dist/src/network/transport/rest.d.ts +58 -58
  52. package/dist/src/register.d.ts +1 -1
  53. package/dist/src/util/encoder.d.ts +19 -19
  54. package/dist/src/util/map.d.ts +17 -17
  55. package/dist/src/util/url.d.ts +19 -19
  56. package/dist/src/util/validateArgs.d.ts +33 -33
  57. package/package.json +7 -7
package/dist/index.cjs.js CHANGED
@@ -8,1151 +8,1151 @@ var util = require('@firebase/util');
8
8
  var logger$1 = require('@firebase/logger');
9
9
 
10
10
  const name = "@firebase/data-connect";
11
- const version = "0.1.1";
11
+ const version = "0.1.2";
12
12
 
13
- /**
14
- * @license
15
- * Copyright 2024 Google LLC
16
- *
17
- * Licensed under the Apache License, Version 2.0 (the "License");
18
- * you may not use this file except in compliance with the License.
19
- * You may obtain a copy of the License at
20
- *
21
- * http://www.apache.org/licenses/LICENSE-2.0
22
- *
23
- * Unless required by applicable law or agreed to in writing, software
24
- * distributed under the License is distributed on an "AS IS" BASIS,
25
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
- * See the License for the specific language governing permissions and
27
- * limitations under the License.
28
- */
29
- /** The semver (www.semver.org) version of the SDK. */
30
- let SDK_VERSION = '';
31
- /**
32
- * SDK_VERSION should be set before any database instance is created
33
- * @internal
34
- */
35
- function setSDKVersion(version) {
36
- SDK_VERSION = version;
13
+ /**
14
+ * @license
15
+ * Copyright 2024 Google LLC
16
+ *
17
+ * Licensed under the Apache License, Version 2.0 (the "License");
18
+ * you may not use this file except in compliance with the License.
19
+ * You may obtain a copy of the License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing, software
24
+ * distributed under the License is distributed on an "AS IS" BASIS,
25
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
+ * See the License for the specific language governing permissions and
27
+ * limitations under the License.
28
+ */
29
+ /** The semver (www.semver.org) version of the SDK. */
30
+ let SDK_VERSION = '';
31
+ /**
32
+ * SDK_VERSION should be set before any database instance is created
33
+ * @internal
34
+ */
35
+ function setSDKVersion(version) {
36
+ SDK_VERSION = version;
37
37
  }
38
38
 
39
- /**
40
- * @license
41
- * Copyright 2024 Google LLC
42
- *
43
- * Licensed under the Apache License, Version 2.0 (the "License");
44
- * you may not use this file except in compliance with the License.
45
- * You may obtain a copy of the License at
46
- *
47
- * http://www.apache.org/licenses/LICENSE-2.0
48
- *
49
- * Unless required by applicable law or agreed to in writing, software
50
- * distributed under the License is distributed on an "AS IS" BASIS,
51
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
52
- * See the License for the specific language governing permissions and
53
- * limitations under the License.
54
- */
55
- /**
56
- * @internal
57
- * Abstraction around AppCheck's token fetching capabilities.
58
- */
59
- class AppCheckTokenProvider {
60
- constructor(appName_, appCheckProvider) {
61
- this.appName_ = appName_;
62
- this.appCheckProvider = appCheckProvider;
63
- this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
64
- if (!this.appCheck) {
65
- void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)).catch());
66
- }
67
- }
68
- getToken(forceRefresh) {
69
- if (!this.appCheck) {
70
- return new Promise((resolve, reject) => {
71
- // Support delayed initialization of FirebaseAppCheck. This allows our
72
- // customers to initialize the RTDB SDK before initializing Firebase
73
- // AppCheck and ensures that all requests are authenticated if a token
74
- // becomes available before the timoeout below expires.
75
- setTimeout(() => {
76
- if (this.appCheck) {
77
- this.getToken(forceRefresh).then(resolve, reject);
78
- }
79
- else {
80
- resolve(null);
81
- }
82
- }, 0);
83
- });
84
- }
85
- return this.appCheck.getToken(forceRefresh);
86
- }
87
- addTokenChangeListener(listener) {
88
- var _a;
89
- void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)));
90
- }
39
+ /**
40
+ * @license
41
+ * Copyright 2024 Google LLC
42
+ *
43
+ * Licensed under the Apache License, Version 2.0 (the "License");
44
+ * you may not use this file except in compliance with the License.
45
+ * You may obtain a copy of the License at
46
+ *
47
+ * http://www.apache.org/licenses/LICENSE-2.0
48
+ *
49
+ * Unless required by applicable law or agreed to in writing, software
50
+ * distributed under the License is distributed on an "AS IS" BASIS,
51
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
52
+ * See the License for the specific language governing permissions and
53
+ * limitations under the License.
54
+ */
55
+ /**
56
+ * @internal
57
+ * Abstraction around AppCheck's token fetching capabilities.
58
+ */
59
+ class AppCheckTokenProvider {
60
+ constructor(appName_, appCheckProvider) {
61
+ this.appName_ = appName_;
62
+ this.appCheckProvider = appCheckProvider;
63
+ this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
64
+ if (!this.appCheck) {
65
+ void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)).catch());
66
+ }
67
+ }
68
+ getToken(forceRefresh) {
69
+ if (!this.appCheck) {
70
+ return new Promise((resolve, reject) => {
71
+ // Support delayed initialization of FirebaseAppCheck. This allows our
72
+ // customers to initialize the RTDB SDK before initializing Firebase
73
+ // AppCheck and ensures that all requests are authenticated if a token
74
+ // becomes available before the timoeout below expires.
75
+ setTimeout(() => {
76
+ if (this.appCheck) {
77
+ this.getToken(forceRefresh).then(resolve, reject);
78
+ }
79
+ else {
80
+ resolve(null);
81
+ }
82
+ }, 0);
83
+ });
84
+ }
85
+ return this.appCheck.getToken(forceRefresh);
86
+ }
87
+ addTokenChangeListener(listener) {
88
+ var _a;
89
+ void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)));
90
+ }
91
91
  }
92
92
 
93
- /**
94
- * @license
95
- * Copyright 2024 Google LLC
96
- *
97
- * Licensed under the Apache License, Version 2.0 (the "License");
98
- * you may not use this file except in compliance with the License.
99
- * You may obtain a copy of the License at
100
- *
101
- * http://www.apache.org/licenses/LICENSE-2.0
102
- *
103
- * Unless required by applicable law or agreed to in writing, software
104
- * distributed under the License is distributed on an "AS IS" BASIS,
105
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
106
- * See the License for the specific language governing permissions and
107
- * limitations under the License.
108
- */
109
- const Code = {
110
- OTHER: 'other',
111
- ALREADY_INITIALIZED: 'already-initialized',
112
- NOT_INITIALIZED: 'not-initialized',
113
- NOT_SUPPORTED: 'not-supported',
114
- INVALID_ARGUMENT: 'invalid-argument',
115
- PARTIAL_ERROR: 'partial-error',
116
- UNAUTHORIZED: 'unauthorized'
117
- };
118
- /** An error returned by a DataConnect operation. */
119
- class DataConnectError extends util.FirebaseError {
120
- /** @hideconstructor */
121
- constructor(
122
- /**
123
- * The backend error code associated with this error.
124
- */
125
- code,
126
- /**
127
- * A custom error description.
128
- */
129
- message) {
130
- super(code, message);
131
- this.code = code;
132
- this.message = message;
133
- // HACK: We write a toString property directly because Error is not a real
134
- // class and so inheritance does not work correctly. We could alternatively
135
- // do the same "back-door inheritance" trick that FirebaseError does.
136
- this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
137
- }
93
+ /**
94
+ * @license
95
+ * Copyright 2024 Google LLC
96
+ *
97
+ * Licensed under the Apache License, Version 2.0 (the "License");
98
+ * you may not use this file except in compliance with the License.
99
+ * You may obtain a copy of the License at
100
+ *
101
+ * http://www.apache.org/licenses/LICENSE-2.0
102
+ *
103
+ * Unless required by applicable law or agreed to in writing, software
104
+ * distributed under the License is distributed on an "AS IS" BASIS,
105
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
106
+ * See the License for the specific language governing permissions and
107
+ * limitations under the License.
108
+ */
109
+ const Code = {
110
+ OTHER: 'other',
111
+ ALREADY_INITIALIZED: 'already-initialized',
112
+ NOT_INITIALIZED: 'not-initialized',
113
+ NOT_SUPPORTED: 'not-supported',
114
+ INVALID_ARGUMENT: 'invalid-argument',
115
+ PARTIAL_ERROR: 'partial-error',
116
+ UNAUTHORIZED: 'unauthorized'
117
+ };
118
+ /** An error returned by a DataConnect operation. */
119
+ class DataConnectError extends util.FirebaseError {
120
+ /** @hideconstructor */
121
+ constructor(
122
+ /**
123
+ * The backend error code associated with this error.
124
+ */
125
+ code,
126
+ /**
127
+ * A custom error description.
128
+ */
129
+ message) {
130
+ super(code, message);
131
+ this.code = code;
132
+ this.message = message;
133
+ // HACK: We write a toString property directly because Error is not a real
134
+ // class and so inheritance does not work correctly. We could alternatively
135
+ // do the same "back-door inheritance" trick that FirebaseError does.
136
+ this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
137
+ }
138
138
  }
139
139
 
140
- /**
141
- * @license
142
- * Copyright 2024 Google LLC
143
- *
144
- * Licensed under the Apache License, Version 2.0 (the "License");
145
- * you may not use this file except in compliance with the License.
146
- * You may obtain a copy of the License at
147
- *
148
- * http://www.apache.org/licenses/LICENSE-2.0
149
- *
150
- * Unless required by applicable law or agreed to in writing, software
151
- * distributed under the License is distributed on an "AS IS" BASIS,
152
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
153
- * See the License for the specific language governing permissions and
154
- * limitations under the License.
155
- */
156
- const logger = new logger$1.Logger('@firebase/data-connect');
157
- function setLogLevel(logLevel) {
158
- logger.setLogLevel(logLevel);
159
- }
160
- function logDebug(msg) {
161
- logger.debug(`DataConnect (${SDK_VERSION}): ${msg}`);
162
- }
163
- function logError(msg) {
164
- logger.error(`DataConnect (${SDK_VERSION}): ${msg}`);
140
+ /**
141
+ * @license
142
+ * Copyright 2024 Google LLC
143
+ *
144
+ * Licensed under the Apache License, Version 2.0 (the "License");
145
+ * you may not use this file except in compliance with the License.
146
+ * You may obtain a copy of the License at
147
+ *
148
+ * http://www.apache.org/licenses/LICENSE-2.0
149
+ *
150
+ * Unless required by applicable law or agreed to in writing, software
151
+ * distributed under the License is distributed on an "AS IS" BASIS,
152
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
153
+ * See the License for the specific language governing permissions and
154
+ * limitations under the License.
155
+ */
156
+ const logger = new logger$1.Logger('@firebase/data-connect');
157
+ function setLogLevel(logLevel) {
158
+ logger.setLogLevel(logLevel);
159
+ }
160
+ function logDebug(msg) {
161
+ logger.debug(`DataConnect (${SDK_VERSION}): ${msg}`);
162
+ }
163
+ function logError(msg) {
164
+ logger.error(`DataConnect (${SDK_VERSION}): ${msg}`);
165
165
  }
166
166
 
167
- /**
168
- * @license
169
- * Copyright 2024 Google LLC
170
- *
171
- * Licensed under the Apache License, Version 2.0 (the "License");
172
- * you may not use this file except in compliance with the License.
173
- * You may obtain a copy of the License at
174
- *
175
- * http://www.apache.org/licenses/LICENSE-2.0
176
- *
177
- * Unless required by applicable law or agreed to in writing, software
178
- * distributed under the License is distributed on an "AS IS" BASIS,
179
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
- * See the License for the specific language governing permissions and
181
- * limitations under the License.
182
- */
183
- // @internal
184
- class FirebaseAuthProvider {
185
- constructor(_appName, _options, _authProvider) {
186
- this._appName = _appName;
187
- this._options = _options;
188
- this._authProvider = _authProvider;
189
- this._auth = _authProvider.getImmediate({ optional: true });
190
- if (!this._auth) {
191
- _authProvider.onInit(auth => (this._auth = auth));
192
- }
193
- }
194
- getToken(forceRefresh) {
195
- if (!this._auth) {
196
- return new Promise((resolve, reject) => {
197
- setTimeout(() => {
198
- if (this._auth) {
199
- this.getToken(forceRefresh).then(resolve, reject);
200
- }
201
- else {
202
- resolve(null);
203
- }
204
- }, 0);
205
- });
206
- }
207
- return this._auth.getToken(forceRefresh).catch(error => {
208
- if (error && error.code === 'auth/token-not-initialized') {
209
- logDebug('Got auth/token-not-initialized error. Treating as null token.');
210
- return null;
211
- }
212
- else {
213
- logError('Error received when attempting to retrieve token: ' +
214
- JSON.stringify(error));
215
- return Promise.reject(error);
216
- }
217
- });
218
- }
219
- addTokenChangeListener(listener) {
220
- var _a;
221
- (_a = this._auth) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
222
- }
223
- removeTokenChangeListener(listener) {
224
- this._authProvider
225
- .get()
226
- .then(auth => auth.removeAuthTokenListener(listener))
227
- .catch(err => logError(err));
228
- }
167
+ /**
168
+ * @license
169
+ * Copyright 2024 Google LLC
170
+ *
171
+ * Licensed under the Apache License, Version 2.0 (the "License");
172
+ * you may not use this file except in compliance with the License.
173
+ * You may obtain a copy of the License at
174
+ *
175
+ * http://www.apache.org/licenses/LICENSE-2.0
176
+ *
177
+ * Unless required by applicable law or agreed to in writing, software
178
+ * distributed under the License is distributed on an "AS IS" BASIS,
179
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
+ * See the License for the specific language governing permissions and
181
+ * limitations under the License.
182
+ */
183
+ // @internal
184
+ class FirebaseAuthProvider {
185
+ constructor(_appName, _options, _authProvider) {
186
+ this._appName = _appName;
187
+ this._options = _options;
188
+ this._authProvider = _authProvider;
189
+ this._auth = _authProvider.getImmediate({ optional: true });
190
+ if (!this._auth) {
191
+ _authProvider.onInit(auth => (this._auth = auth));
192
+ }
193
+ }
194
+ getToken(forceRefresh) {
195
+ if (!this._auth) {
196
+ return new Promise((resolve, reject) => {
197
+ setTimeout(() => {
198
+ if (this._auth) {
199
+ this.getToken(forceRefresh).then(resolve, reject);
200
+ }
201
+ else {
202
+ resolve(null);
203
+ }
204
+ }, 0);
205
+ });
206
+ }
207
+ return this._auth.getToken(forceRefresh).catch(error => {
208
+ if (error && error.code === 'auth/token-not-initialized') {
209
+ logDebug('Got auth/token-not-initialized error. Treating as null token.');
210
+ return null;
211
+ }
212
+ else {
213
+ logError('Error received when attempting to retrieve token: ' +
214
+ JSON.stringify(error));
215
+ return Promise.reject(error);
216
+ }
217
+ });
218
+ }
219
+ addTokenChangeListener(listener) {
220
+ var _a;
221
+ (_a = this._auth) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
222
+ }
223
+ removeTokenChangeListener(listener) {
224
+ this._authProvider
225
+ .get()
226
+ .then(auth => auth.removeAuthTokenListener(listener))
227
+ .catch(err => logError(err));
228
+ }
229
229
  }
230
230
 
231
- /**
232
- * @license
233
- * Copyright 2024 Google LLC
234
- *
235
- * Licensed under the Apache License, Version 2.0 (the "License");
236
- * you may not use this file except in compliance with the License.
237
- * You may obtain a copy of the License at
238
- *
239
- * http://www.apache.org/licenses/LICENSE-2.0
240
- *
241
- * Unless required by applicable law or agreed to in writing, software
242
- * distributed under the License is distributed on an "AS IS" BASIS,
243
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
244
- * See the License for the specific language governing permissions and
245
- * limitations under the License.
246
- */
247
- const QUERY_STR = 'query';
248
- const MUTATION_STR = 'mutation';
249
- const SOURCE_SERVER = 'SERVER';
231
+ /**
232
+ * @license
233
+ * Copyright 2024 Google LLC
234
+ *
235
+ * Licensed under the Apache License, Version 2.0 (the "License");
236
+ * you may not use this file except in compliance with the License.
237
+ * You may obtain a copy of the License at
238
+ *
239
+ * http://www.apache.org/licenses/LICENSE-2.0
240
+ *
241
+ * Unless required by applicable law or agreed to in writing, software
242
+ * distributed under the License is distributed on an "AS IS" BASIS,
243
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
244
+ * See the License for the specific language governing permissions and
245
+ * limitations under the License.
246
+ */
247
+ const QUERY_STR = 'query';
248
+ const MUTATION_STR = 'mutation';
249
+ const SOURCE_SERVER = 'SERVER';
250
250
  const SOURCE_CACHE = 'CACHE';
251
251
 
252
- /**
253
- * @license
254
- * Copyright 2024 Google LLC
255
- *
256
- * Licensed under the Apache License, Version 2.0 (the "License");
257
- * you may not use this file except in compliance with the License.
258
- * You may obtain a copy of the License at
259
- *
260
- * http://www.apache.org/licenses/LICENSE-2.0
261
- *
262
- * Unless required by applicable law or agreed to in writing, software
263
- * distributed under the License is distributed on an "AS IS" BASIS,
264
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
265
- * See the License for the specific language governing permissions and
266
- * limitations under the License.
267
- */
268
- let encoderImpl;
269
- function setEncoder(encoder) {
270
- encoderImpl = encoder;
271
- }
252
+ /**
253
+ * @license
254
+ * Copyright 2024 Google LLC
255
+ *
256
+ * Licensed under the Apache License, Version 2.0 (the "License");
257
+ * you may not use this file except in compliance with the License.
258
+ * You may obtain a copy of the License at
259
+ *
260
+ * http://www.apache.org/licenses/LICENSE-2.0
261
+ *
262
+ * Unless required by applicable law or agreed to in writing, software
263
+ * distributed under the License is distributed on an "AS IS" BASIS,
264
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
265
+ * See the License for the specific language governing permissions and
266
+ * limitations under the License.
267
+ */
268
+ let encoderImpl;
269
+ function setEncoder(encoder) {
270
+ encoderImpl = encoder;
271
+ }
272
272
  setEncoder(o => JSON.stringify(o));
273
273
 
274
- /**
275
- * @license
276
- * Copyright 2024 Google LLC
277
- *
278
- * Licensed under the Apache License, Version 2.0 (the "License");
279
- * you may not use this file except in compliance with the License.
280
- * You may obtain a copy of the License at
281
- *
282
- * http://www.apache.org/licenses/LICENSE-2.0
283
- *
284
- * Unless required by applicable law or agreed to in writing, software
285
- * distributed under the License is distributed on an "AS IS" BASIS,
286
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
287
- * See the License for the specific language governing permissions and
288
- * limitations under the License.
289
- */
290
- function setIfNotExists(map, key, val) {
291
- if (!map.has(key)) {
292
- map.set(key, val);
293
- }
274
+ /**
275
+ * @license
276
+ * Copyright 2024 Google LLC
277
+ *
278
+ * Licensed under the Apache License, Version 2.0 (the "License");
279
+ * you may not use this file except in compliance with the License.
280
+ * You may obtain a copy of the License at
281
+ *
282
+ * http://www.apache.org/licenses/LICENSE-2.0
283
+ *
284
+ * Unless required by applicable law or agreed to in writing, software
285
+ * distributed under the License is distributed on an "AS IS" BASIS,
286
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
287
+ * See the License for the specific language governing permissions and
288
+ * limitations under the License.
289
+ */
290
+ function setIfNotExists(map, key, val) {
291
+ if (!map.has(key)) {
292
+ map.set(key, val);
293
+ }
294
294
  }
295
295
 
296
- /**
297
- * @license
298
- * Copyright 2024 Google LLC
299
- *
300
- * Licensed under the Apache License, Version 2.0 (the "License");
301
- * you may not use this file except in compliance with the License.
302
- * You may obtain a copy of the License at
303
- *
304
- * http://www.apache.org/licenses/LICENSE-2.0
305
- *
306
- * Unless required by applicable law or agreed to in writing, software
307
- * distributed under the License is distributed on an "AS IS" BASIS,
308
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
309
- * See the License for the specific language governing permissions and
310
- * limitations under the License.
311
- */
312
- function getRefSerializer(queryRef, data, source) {
313
- return function toJSON() {
314
- return {
315
- data,
316
- refInfo: {
317
- name: queryRef.name,
318
- variables: queryRef.variables,
319
- connectorConfig: Object.assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
320
- },
321
- fetchTime: Date.now().toLocaleString(),
322
- source
323
- };
324
- };
325
- }
326
- class QueryManager {
327
- constructor(transport) {
328
- this.transport = transport;
329
- this._queries = new Map();
330
- }
331
- track(queryName, variables, initialCache) {
332
- const ref = {
333
- name: queryName,
334
- variables,
335
- refType: QUERY_STR
336
- };
337
- const key = encoderImpl(ref);
338
- const newTrackedQuery = {
339
- ref,
340
- subscriptions: [],
341
- currentCache: initialCache || null,
342
- lastError: null
343
- };
344
- // @ts-ignore
345
- setIfNotExists(this._queries, key, newTrackedQuery);
346
- return this._queries.get(key);
347
- }
348
- addSubscription(queryRef, onResultCallback, onErrorCallback, initialCache) {
349
- const key = encoderImpl({
350
- name: queryRef.name,
351
- variables: queryRef.variables,
352
- refType: QUERY_STR
353
- });
354
- const trackedQuery = this._queries.get(key);
355
- const subscription = {
356
- userCallback: onResultCallback,
357
- errCallback: onErrorCallback
358
- };
359
- const unsubscribe = () => {
360
- const trackedQuery = this._queries.get(key);
361
- trackedQuery.subscriptions = trackedQuery.subscriptions.filter(sub => sub !== subscription);
362
- };
363
- if (initialCache && trackedQuery.currentCache !== initialCache) {
364
- logDebug('Initial cache found. Comparing dates.');
365
- if (!trackedQuery.currentCache ||
366
- (trackedQuery.currentCache &&
367
- compareDates(trackedQuery.currentCache.fetchTime, initialCache.fetchTime))) {
368
- trackedQuery.currentCache = initialCache;
369
- }
370
- }
371
- if (trackedQuery.currentCache !== null) {
372
- const cachedData = trackedQuery.currentCache.data;
373
- onResultCallback({
374
- data: cachedData,
375
- source: SOURCE_CACHE,
376
- ref: queryRef,
377
- toJSON: getRefSerializer(queryRef, trackedQuery.currentCache.data, SOURCE_CACHE),
378
- fetchTime: trackedQuery.currentCache.fetchTime
379
- });
380
- if (trackedQuery.lastError !== null && onErrorCallback) {
381
- onErrorCallback(undefined);
382
- }
383
- }
384
- trackedQuery.subscriptions.push({
385
- userCallback: onResultCallback,
386
- errCallback: onErrorCallback,
387
- unsubscribe
388
- });
389
- if (!trackedQuery.currentCache) {
390
- logDebug(`No cache available for query ${queryRef.name} with variables ${JSON.stringify(queryRef.variables)}. Calling executeQuery.`);
391
- const promise = this.executeQuery(queryRef);
392
- // We want to ignore the error and let subscriptions handle it
393
- promise.then(undefined, err => { });
394
- }
395
- return unsubscribe;
396
- }
397
- executeQuery(queryRef) {
398
- if (queryRef.refType !== QUERY_STR) {
399
- throw new DataConnectError(Code.INVALID_ARGUMENT, `ExecuteQuery can only execute query operation`);
400
- }
401
- const key = encoderImpl({
402
- name: queryRef.name,
403
- variables: queryRef.variables,
404
- refType: QUERY_STR
405
- });
406
- const trackedQuery = this._queries.get(key);
407
- const result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
408
- const newR = result.then(res => {
409
- const fetchTime = new Date().toString();
410
- const result = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime });
411
- trackedQuery.subscriptions.forEach(subscription => {
412
- subscription.userCallback(result);
413
- });
414
- trackedQuery.currentCache = {
415
- data: res.data,
416
- source: SOURCE_CACHE,
417
- fetchTime
418
- };
419
- return result;
420
- }, err => {
421
- trackedQuery.lastError = err;
422
- trackedQuery.subscriptions.forEach(subscription => {
423
- if (subscription.errCallback) {
424
- subscription.errCallback(err);
425
- }
426
- });
427
- throw err;
428
- });
429
- return newR;
430
- }
431
- enableEmulator(host, port) {
432
- this.transport.useEmulator(host, port);
433
- }
434
- }
435
- function compareDates(str1, str2) {
436
- const date1 = new Date(str1);
437
- const date2 = new Date(str2);
438
- return date1.getTime() < date2.getTime();
296
+ /**
297
+ * @license
298
+ * Copyright 2024 Google LLC
299
+ *
300
+ * Licensed under the Apache License, Version 2.0 (the "License");
301
+ * you may not use this file except in compliance with the License.
302
+ * You may obtain a copy of the License at
303
+ *
304
+ * http://www.apache.org/licenses/LICENSE-2.0
305
+ *
306
+ * Unless required by applicable law or agreed to in writing, software
307
+ * distributed under the License is distributed on an "AS IS" BASIS,
308
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
309
+ * See the License for the specific language governing permissions and
310
+ * limitations under the License.
311
+ */
312
+ function getRefSerializer(queryRef, data, source) {
313
+ return function toJSON() {
314
+ return {
315
+ data,
316
+ refInfo: {
317
+ name: queryRef.name,
318
+ variables: queryRef.variables,
319
+ connectorConfig: Object.assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
320
+ },
321
+ fetchTime: Date.now().toLocaleString(),
322
+ source
323
+ };
324
+ };
325
+ }
326
+ class QueryManager {
327
+ constructor(transport) {
328
+ this.transport = transport;
329
+ this._queries = new Map();
330
+ }
331
+ track(queryName, variables, initialCache) {
332
+ const ref = {
333
+ name: queryName,
334
+ variables,
335
+ refType: QUERY_STR
336
+ };
337
+ const key = encoderImpl(ref);
338
+ const newTrackedQuery = {
339
+ ref,
340
+ subscriptions: [],
341
+ currentCache: initialCache || null,
342
+ lastError: null
343
+ };
344
+ // @ts-ignore
345
+ setIfNotExists(this._queries, key, newTrackedQuery);
346
+ return this._queries.get(key);
347
+ }
348
+ addSubscription(queryRef, onResultCallback, onErrorCallback, initialCache) {
349
+ const key = encoderImpl({
350
+ name: queryRef.name,
351
+ variables: queryRef.variables,
352
+ refType: QUERY_STR
353
+ });
354
+ const trackedQuery = this._queries.get(key);
355
+ const subscription = {
356
+ userCallback: onResultCallback,
357
+ errCallback: onErrorCallback
358
+ };
359
+ const unsubscribe = () => {
360
+ const trackedQuery = this._queries.get(key);
361
+ trackedQuery.subscriptions = trackedQuery.subscriptions.filter(sub => sub !== subscription);
362
+ };
363
+ if (initialCache && trackedQuery.currentCache !== initialCache) {
364
+ logDebug('Initial cache found. Comparing dates.');
365
+ if (!trackedQuery.currentCache ||
366
+ (trackedQuery.currentCache &&
367
+ compareDates(trackedQuery.currentCache.fetchTime, initialCache.fetchTime))) {
368
+ trackedQuery.currentCache = initialCache;
369
+ }
370
+ }
371
+ if (trackedQuery.currentCache !== null) {
372
+ const cachedData = trackedQuery.currentCache.data;
373
+ onResultCallback({
374
+ data: cachedData,
375
+ source: SOURCE_CACHE,
376
+ ref: queryRef,
377
+ toJSON: getRefSerializer(queryRef, trackedQuery.currentCache.data, SOURCE_CACHE),
378
+ fetchTime: trackedQuery.currentCache.fetchTime
379
+ });
380
+ if (trackedQuery.lastError !== null && onErrorCallback) {
381
+ onErrorCallback(undefined);
382
+ }
383
+ }
384
+ trackedQuery.subscriptions.push({
385
+ userCallback: onResultCallback,
386
+ errCallback: onErrorCallback,
387
+ unsubscribe
388
+ });
389
+ if (!trackedQuery.currentCache) {
390
+ logDebug(`No cache available for query ${queryRef.name} with variables ${JSON.stringify(queryRef.variables)}. Calling executeQuery.`);
391
+ const promise = this.executeQuery(queryRef);
392
+ // We want to ignore the error and let subscriptions handle it
393
+ promise.then(undefined, err => { });
394
+ }
395
+ return unsubscribe;
396
+ }
397
+ executeQuery(queryRef) {
398
+ if (queryRef.refType !== QUERY_STR) {
399
+ throw new DataConnectError(Code.INVALID_ARGUMENT, `ExecuteQuery can only execute query operation`);
400
+ }
401
+ const key = encoderImpl({
402
+ name: queryRef.name,
403
+ variables: queryRef.variables,
404
+ refType: QUERY_STR
405
+ });
406
+ const trackedQuery = this._queries.get(key);
407
+ const result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
408
+ const newR = result.then(res => {
409
+ const fetchTime = new Date().toString();
410
+ const result = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime });
411
+ trackedQuery.subscriptions.forEach(subscription => {
412
+ subscription.userCallback(result);
413
+ });
414
+ trackedQuery.currentCache = {
415
+ data: res.data,
416
+ source: SOURCE_CACHE,
417
+ fetchTime
418
+ };
419
+ return result;
420
+ }, err => {
421
+ trackedQuery.lastError = err;
422
+ trackedQuery.subscriptions.forEach(subscription => {
423
+ if (subscription.errCallback) {
424
+ subscription.errCallback(err);
425
+ }
426
+ });
427
+ throw err;
428
+ });
429
+ return newR;
430
+ }
431
+ enableEmulator(host, port) {
432
+ this.transport.useEmulator(host, port);
433
+ }
434
+ }
435
+ function compareDates(str1, str2) {
436
+ const date1 = new Date(str1);
437
+ const date2 = new Date(str2);
438
+ return date1.getTime() < date2.getTime();
439
439
  }
440
440
 
441
- /**
442
- * @license
443
- * Copyright 2024 Google LLC
444
- *
445
- * Licensed under the Apache License, Version 2.0 (the "License");
446
- * you may not use this file except in compliance with the License.
447
- * You may obtain a copy of the License at
448
- *
449
- * http://www.apache.org/licenses/LICENSE-2.0
450
- *
451
- * Unless required by applicable law or agreed to in writing, software
452
- * distributed under the License is distributed on an "AS IS" BASIS,
453
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
454
- * See the License for the specific language governing permissions and
455
- * limitations under the License.
456
- */
457
- function urlBuilder(projectConfig, transportOptions) {
458
- const { connector, location, projectId: project, service } = projectConfig;
459
- const { host, sslEnabled, port } = transportOptions;
460
- const protocol = sslEnabled ? 'https' : 'http';
461
- const realHost = host || `firebasedataconnect.googleapis.com`;
462
- let baseUrl = `${protocol}://${realHost}`;
463
- if (typeof port === 'number') {
464
- baseUrl += `:${port}`;
465
- }
466
- else if (typeof port !== 'undefined') {
467
- logError('Port type is of an invalid type');
468
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
469
- }
470
- return `${baseUrl}/v1beta/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
471
- }
472
- function addToken(url, apiKey) {
473
- if (!apiKey) {
474
- return url;
475
- }
476
- const newUrl = new URL(url);
477
- newUrl.searchParams.append('key', apiKey);
478
- return newUrl.toString();
441
+ /**
442
+ * @license
443
+ * Copyright 2024 Google LLC
444
+ *
445
+ * Licensed under the Apache License, Version 2.0 (the "License");
446
+ * you may not use this file except in compliance with the License.
447
+ * You may obtain a copy of the License at
448
+ *
449
+ * http://www.apache.org/licenses/LICENSE-2.0
450
+ *
451
+ * Unless required by applicable law or agreed to in writing, software
452
+ * distributed under the License is distributed on an "AS IS" BASIS,
453
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
454
+ * See the License for the specific language governing permissions and
455
+ * limitations under the License.
456
+ */
457
+ function urlBuilder(projectConfig, transportOptions) {
458
+ const { connector, location, projectId: project, service } = projectConfig;
459
+ const { host, sslEnabled, port } = transportOptions;
460
+ const protocol = sslEnabled ? 'https' : 'http';
461
+ const realHost = host || `firebasedataconnect.googleapis.com`;
462
+ let baseUrl = `${protocol}://${realHost}`;
463
+ if (typeof port === 'number') {
464
+ baseUrl += `:${port}`;
465
+ }
466
+ else if (typeof port !== 'undefined') {
467
+ logError('Port type is of an invalid type');
468
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
469
+ }
470
+ return `${baseUrl}/v1beta/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
471
+ }
472
+ function addToken(url, apiKey) {
473
+ if (!apiKey) {
474
+ return url;
475
+ }
476
+ const newUrl = new URL(url);
477
+ newUrl.searchParams.append('key', apiKey);
478
+ return newUrl.toString();
479
479
  }
480
480
 
481
- /**
482
- * @license
483
- * Copyright 2024 Google LLC
484
- *
485
- * Licensed under the Apache License, Version 2.0 (the "License");
486
- * you may not use this file except in compliance with the License.
487
- * You may obtain a copy of the License at
488
- *
489
- * http://www.apache.org/licenses/LICENSE-2.0
490
- *
491
- * Unless required by applicable law or agreed to in writing, software
492
- * distributed under the License is distributed on an "AS IS" BASIS,
493
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
494
- * See the License for the specific language governing permissions and
495
- * limitations under the License.
496
- */
497
- let connectFetch = globalThis.fetch;
498
- function getGoogApiClientValue(_isUsingGen) {
499
- let str = 'gl-js/ fire/' + SDK_VERSION;
500
- if (_isUsingGen) {
501
- str += ' js/gen';
502
- }
503
- return str;
504
- }
505
- function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUsingGen) {
506
- if (!connectFetch) {
507
- throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
508
- }
509
- const headers = {
510
- 'Content-Type': 'application/json',
511
- 'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen)
512
- };
513
- if (accessToken) {
514
- headers['X-Firebase-Auth-Token'] = accessToken;
515
- }
516
- if (appId) {
517
- headers['x-firebase-gmpid'] = appId;
518
- }
519
- if (appCheckToken) {
520
- headers['X-Firebase-AppCheck'] = appCheckToken;
521
- }
522
- const bodyStr = JSON.stringify(body);
523
- logDebug(`Making request out to ${url} with body: ${bodyStr}`);
524
- return connectFetch(url, {
525
- body: bodyStr,
526
- method: 'POST',
527
- headers,
528
- signal
529
- })
530
- .catch(err => {
531
- throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
532
- })
533
- .then(async (response) => {
534
- let jsonResponse = null;
535
- try {
536
- jsonResponse = await response.json();
537
- }
538
- catch (e) {
539
- throw new DataConnectError(Code.OTHER, JSON.stringify(e));
540
- }
541
- const message = getMessage(jsonResponse);
542
- if (response.status >= 400) {
543
- logError('Error while performing request: ' + JSON.stringify(jsonResponse));
544
- if (response.status === 401) {
545
- throw new DataConnectError(Code.UNAUTHORIZED, message);
546
- }
547
- throw new DataConnectError(Code.OTHER, message);
548
- }
549
- return jsonResponse;
550
- })
551
- .then(res => {
552
- if (res.errors && res.errors.length) {
553
- const stringified = JSON.stringify(res.errors);
554
- logError('DataConnect error while performing request: ' + stringified);
555
- throw new DataConnectError(Code.OTHER, stringified);
556
- }
557
- return res;
558
- });
559
- }
560
- function getMessage(obj) {
561
- if ('message' in obj) {
562
- return obj.message;
563
- }
564
- return JSON.stringify(obj);
481
+ /**
482
+ * @license
483
+ * Copyright 2024 Google LLC
484
+ *
485
+ * Licensed under the Apache License, Version 2.0 (the "License");
486
+ * you may not use this file except in compliance with the License.
487
+ * You may obtain a copy of the License at
488
+ *
489
+ * http://www.apache.org/licenses/LICENSE-2.0
490
+ *
491
+ * Unless required by applicable law or agreed to in writing, software
492
+ * distributed under the License is distributed on an "AS IS" BASIS,
493
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
494
+ * See the License for the specific language governing permissions and
495
+ * limitations under the License.
496
+ */
497
+ let connectFetch = globalThis.fetch;
498
+ function getGoogApiClientValue(_isUsingGen) {
499
+ let str = 'gl-js/ fire/' + SDK_VERSION;
500
+ if (_isUsingGen) {
501
+ str += ' js/gen';
502
+ }
503
+ return str;
504
+ }
505
+ function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUsingGen) {
506
+ if (!connectFetch) {
507
+ throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
508
+ }
509
+ const headers = {
510
+ 'Content-Type': 'application/json',
511
+ 'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen)
512
+ };
513
+ if (accessToken) {
514
+ headers['X-Firebase-Auth-Token'] = accessToken;
515
+ }
516
+ if (appId) {
517
+ headers['x-firebase-gmpid'] = appId;
518
+ }
519
+ if (appCheckToken) {
520
+ headers['X-Firebase-AppCheck'] = appCheckToken;
521
+ }
522
+ const bodyStr = JSON.stringify(body);
523
+ logDebug(`Making request out to ${url} with body: ${bodyStr}`);
524
+ return connectFetch(url, {
525
+ body: bodyStr,
526
+ method: 'POST',
527
+ headers,
528
+ signal
529
+ })
530
+ .catch(err => {
531
+ throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
532
+ })
533
+ .then(async (response) => {
534
+ let jsonResponse = null;
535
+ try {
536
+ jsonResponse = await response.json();
537
+ }
538
+ catch (e) {
539
+ throw new DataConnectError(Code.OTHER, JSON.stringify(e));
540
+ }
541
+ const message = getMessage(jsonResponse);
542
+ if (response.status >= 400) {
543
+ logError('Error while performing request: ' + JSON.stringify(jsonResponse));
544
+ if (response.status === 401) {
545
+ throw new DataConnectError(Code.UNAUTHORIZED, message);
546
+ }
547
+ throw new DataConnectError(Code.OTHER, message);
548
+ }
549
+ return jsonResponse;
550
+ })
551
+ .then(res => {
552
+ if (res.errors && res.errors.length) {
553
+ const stringified = JSON.stringify(res.errors);
554
+ logError('DataConnect error while performing request: ' + stringified);
555
+ throw new DataConnectError(Code.OTHER, stringified);
556
+ }
557
+ return res;
558
+ });
559
+ }
560
+ function getMessage(obj) {
561
+ if ('message' in obj) {
562
+ return obj.message;
563
+ }
564
+ return JSON.stringify(obj);
565
565
  }
566
566
 
567
- /**
568
- * @license
569
- * Copyright 2024 Google LLC
570
- *
571
- * Licensed under the Apache License, Version 2.0 (the "License");
572
- * you may not use this file except in compliance with the License.
573
- * You may obtain a copy of the License at
574
- *
575
- * http://www.apache.org/licenses/LICENSE-2.0
576
- *
577
- * Unless required by applicable law or agreed to in writing, software
578
- * distributed under the License is distributed on an "AS IS" BASIS,
579
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
580
- * See the License for the specific language governing permissions and
581
- * limitations under the License.
582
- */
583
- class RESTTransport {
584
- constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false) {
585
- var _a, _b;
586
- this.apiKey = apiKey;
587
- this.appId = appId;
588
- this.authProvider = authProvider;
589
- this.appCheckProvider = appCheckProvider;
590
- this._isUsingGen = _isUsingGen;
591
- this._host = '';
592
- this._location = 'l';
593
- this._connectorName = '';
594
- this._secure = true;
595
- this._project = 'p';
596
- this._accessToken = null;
597
- this._appCheckToken = null;
598
- this._lastToken = null;
599
- // TODO(mtewani): Update U to include shape of body defined in line 13.
600
- this.invokeQuery = (queryName, body) => {
601
- const abortController = new AbortController();
602
- // TODO(mtewani): Update to proper value
603
- const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
604
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
605
- operationName: queryName,
606
- variables: body
607
- }, // TODO(mtewani): This is a patch, fix this.
608
- abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen));
609
- return {
610
- then: withAuth.then.bind(withAuth),
611
- catch: withAuth.catch.bind(withAuth)
612
- };
613
- };
614
- this.invokeMutation = (mutationName, body) => {
615
- const abortController = new AbortController();
616
- const taskResult = this.withRetry(() => {
617
- return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
618
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
619
- operationName: mutationName,
620
- variables: body
621
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen);
622
- });
623
- return {
624
- then: taskResult.then.bind(taskResult),
625
- // catch: taskResult.catch.bind(taskResult),
626
- // finally: taskResult.finally.bind(taskResult),
627
- cancel: () => abortController.abort()
628
- };
629
- };
630
- if (transportOptions) {
631
- if (typeof transportOptions.port === 'number') {
632
- this._port = transportOptions.port;
633
- }
634
- if (typeof transportOptions.sslEnabled !== 'undefined') {
635
- this._secure = transportOptions.sslEnabled;
636
- }
637
- this._host = transportOptions.host;
638
- }
639
- const { location, projectId: project, connector, service } = options;
640
- if (location) {
641
- this._location = location;
642
- }
643
- if (project) {
644
- this._project = project;
645
- }
646
- this._serviceName = service;
647
- if (!connector) {
648
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
649
- }
650
- this._connectorName = connector;
651
- (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(token => {
652
- logDebug(`New Token Available: ${token}`);
653
- this._accessToken = token;
654
- });
655
- (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(result => {
656
- const { token } = result;
657
- logDebug(`New App Check Token Available: ${token}`);
658
- this._appCheckToken = token;
659
- });
660
- }
661
- get endpointUrl() {
662
- return urlBuilder({
663
- connector: this._connectorName,
664
- location: this._location,
665
- projectId: this._project,
666
- service: this._serviceName
667
- }, { host: this._host, sslEnabled: this._secure, port: this._port });
668
- }
669
- useEmulator(host, port, isSecure) {
670
- this._host = host;
671
- if (typeof port === 'number') {
672
- this._port = port;
673
- }
674
- if (typeof isSecure !== 'undefined') {
675
- this._secure = isSecure;
676
- }
677
- }
678
- onTokenChanged(newToken) {
679
- this._accessToken = newToken;
680
- }
681
- async getWithAuth(forceToken = false) {
682
- var _a;
683
- let starterPromise = new Promise(resolve => resolve(this._accessToken));
684
- if (this.appCheckProvider) {
685
- this._appCheckToken = (_a = (await this.appCheckProvider.getToken())) === null || _a === void 0 ? void 0 : _a.token;
686
- }
687
- if (this.authProvider) {
688
- starterPromise = this.authProvider
689
- .getToken(/*forceToken=*/ forceToken)
690
- .then(data => {
691
- if (!data) {
692
- return null;
693
- }
694
- this._accessToken = data.accessToken;
695
- return this._accessToken;
696
- });
697
- }
698
- else {
699
- starterPromise = new Promise(resolve => resolve(''));
700
- }
701
- return starterPromise;
702
- }
703
- _setLastToken(lastToken) {
704
- this._lastToken = lastToken;
705
- }
706
- withRetry(promiseFactory, retry = false) {
707
- let isNewToken = false;
708
- return this.getWithAuth(retry)
709
- .then(res => {
710
- isNewToken = this._lastToken !== res;
711
- this._lastToken = res;
712
- return res;
713
- })
714
- .then(promiseFactory)
715
- .catch(err => {
716
- // Only retry if the result is unauthorized and the last token isn't the same as the new one.
717
- if ('code' in err &&
718
- err.code === Code.UNAUTHORIZED &&
719
- !retry &&
720
- isNewToken) {
721
- logDebug('Retrying due to unauthorized');
722
- return this.withRetry(promiseFactory, true);
723
- }
724
- throw err;
725
- });
726
- }
567
+ /**
568
+ * @license
569
+ * Copyright 2024 Google LLC
570
+ *
571
+ * Licensed under the Apache License, Version 2.0 (the "License");
572
+ * you may not use this file except in compliance with the License.
573
+ * You may obtain a copy of the License at
574
+ *
575
+ * http://www.apache.org/licenses/LICENSE-2.0
576
+ *
577
+ * Unless required by applicable law or agreed to in writing, software
578
+ * distributed under the License is distributed on an "AS IS" BASIS,
579
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
580
+ * See the License for the specific language governing permissions and
581
+ * limitations under the License.
582
+ */
583
+ class RESTTransport {
584
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false) {
585
+ var _a, _b;
586
+ this.apiKey = apiKey;
587
+ this.appId = appId;
588
+ this.authProvider = authProvider;
589
+ this.appCheckProvider = appCheckProvider;
590
+ this._isUsingGen = _isUsingGen;
591
+ this._host = '';
592
+ this._location = 'l';
593
+ this._connectorName = '';
594
+ this._secure = true;
595
+ this._project = 'p';
596
+ this._accessToken = null;
597
+ this._appCheckToken = null;
598
+ this._lastToken = null;
599
+ // TODO(mtewani): Update U to include shape of body defined in line 13.
600
+ this.invokeQuery = (queryName, body) => {
601
+ const abortController = new AbortController();
602
+ // TODO(mtewani): Update to proper value
603
+ const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
604
+ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
605
+ operationName: queryName,
606
+ variables: body
607
+ }, // TODO(mtewani): This is a patch, fix this.
608
+ abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen));
609
+ return {
610
+ then: withAuth.then.bind(withAuth),
611
+ catch: withAuth.catch.bind(withAuth)
612
+ };
613
+ };
614
+ this.invokeMutation = (mutationName, body) => {
615
+ const abortController = new AbortController();
616
+ const taskResult = this.withRetry(() => {
617
+ return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
618
+ name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
619
+ operationName: mutationName,
620
+ variables: body
621
+ }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen);
622
+ });
623
+ return {
624
+ then: taskResult.then.bind(taskResult),
625
+ // catch: taskResult.catch.bind(taskResult),
626
+ // finally: taskResult.finally.bind(taskResult),
627
+ cancel: () => abortController.abort()
628
+ };
629
+ };
630
+ if (transportOptions) {
631
+ if (typeof transportOptions.port === 'number') {
632
+ this._port = transportOptions.port;
633
+ }
634
+ if (typeof transportOptions.sslEnabled !== 'undefined') {
635
+ this._secure = transportOptions.sslEnabled;
636
+ }
637
+ this._host = transportOptions.host;
638
+ }
639
+ const { location, projectId: project, connector, service } = options;
640
+ if (location) {
641
+ this._location = location;
642
+ }
643
+ if (project) {
644
+ this._project = project;
645
+ }
646
+ this._serviceName = service;
647
+ if (!connector) {
648
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
649
+ }
650
+ this._connectorName = connector;
651
+ (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(token => {
652
+ logDebug(`New Token Available: ${token}`);
653
+ this._accessToken = token;
654
+ });
655
+ (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(result => {
656
+ const { token } = result;
657
+ logDebug(`New App Check Token Available: ${token}`);
658
+ this._appCheckToken = token;
659
+ });
660
+ }
661
+ get endpointUrl() {
662
+ return urlBuilder({
663
+ connector: this._connectorName,
664
+ location: this._location,
665
+ projectId: this._project,
666
+ service: this._serviceName
667
+ }, { host: this._host, sslEnabled: this._secure, port: this._port });
668
+ }
669
+ useEmulator(host, port, isSecure) {
670
+ this._host = host;
671
+ if (typeof port === 'number') {
672
+ this._port = port;
673
+ }
674
+ if (typeof isSecure !== 'undefined') {
675
+ this._secure = isSecure;
676
+ }
677
+ }
678
+ onTokenChanged(newToken) {
679
+ this._accessToken = newToken;
680
+ }
681
+ async getWithAuth(forceToken = false) {
682
+ var _a;
683
+ let starterPromise = new Promise(resolve => resolve(this._accessToken));
684
+ if (this.appCheckProvider) {
685
+ this._appCheckToken = (_a = (await this.appCheckProvider.getToken())) === null || _a === void 0 ? void 0 : _a.token;
686
+ }
687
+ if (this.authProvider) {
688
+ starterPromise = this.authProvider
689
+ .getToken(/*forceToken=*/ forceToken)
690
+ .then(data => {
691
+ if (!data) {
692
+ return null;
693
+ }
694
+ this._accessToken = data.accessToken;
695
+ return this._accessToken;
696
+ });
697
+ }
698
+ else {
699
+ starterPromise = new Promise(resolve => resolve(''));
700
+ }
701
+ return starterPromise;
702
+ }
703
+ _setLastToken(lastToken) {
704
+ this._lastToken = lastToken;
705
+ }
706
+ withRetry(promiseFactory, retry = false) {
707
+ let isNewToken = false;
708
+ return this.getWithAuth(retry)
709
+ .then(res => {
710
+ isNewToken = this._lastToken !== res;
711
+ this._lastToken = res;
712
+ return res;
713
+ })
714
+ .then(promiseFactory)
715
+ .catch(err => {
716
+ // Only retry if the result is unauthorized and the last token isn't the same as the new one.
717
+ if ('code' in err &&
718
+ err.code === Code.UNAUTHORIZED &&
719
+ !retry &&
720
+ isNewToken) {
721
+ logDebug('Retrying due to unauthorized');
722
+ return this.withRetry(promiseFactory, true);
723
+ }
724
+ throw err;
725
+ });
726
+ }
727
727
  }
728
728
 
729
- /**
730
- * @license
731
- * Copyright 2024 Google LLC
732
- *
733
- * Licensed under the Apache License, Version 2.0 (the "License");
734
- * you may not use this file except in compliance with the License.
735
- * You may obtain a copy of the License at
736
- *
737
- * http://www.apache.org/licenses/LICENSE-2.0
738
- *
739
- * Unless required by applicable law or agreed to in writing, software
740
- * distributed under the License is distributed on an "AS IS" BASIS,
741
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
742
- * See the License for the specific language governing permissions and
743
- * limitations under the License.
744
- */
745
- /**
746
- *
747
- * @param dcInstance Data Connect instance
748
- * @param mutationName name of mutation
749
- * @param variables variables to send with mutation
750
- * @returns `MutationRef`
751
- */
752
- function mutationRef(dcInstance, mutationName, variables) {
753
- dcInstance.setInitialized();
754
- const ref = {
755
- dataConnect: dcInstance,
756
- name: mutationName,
757
- refType: MUTATION_STR,
758
- variables: variables
759
- };
760
- return ref;
761
- }
762
- /**
763
- * @internal
764
- */
765
- class MutationManager {
766
- constructor(_transport) {
767
- this._transport = _transport;
768
- this._inflight = [];
769
- }
770
- executeMutation(mutationRef) {
771
- const result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
772
- const withRefPromise = result.then(res => {
773
- const obj = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
774
- return obj;
775
- });
776
- this._inflight.push(result);
777
- const removePromise = () => (this._inflight = this._inflight.filter(promise => promise !== result));
778
- result.then(removePromise, removePromise);
779
- return withRefPromise;
780
- }
781
- }
782
- /**
783
- * Execute Mutation
784
- * @param mutationRef mutation to execute
785
- * @returns `MutationRef`
786
- */
787
- function executeMutation(mutationRef) {
788
- return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef);
729
+ /**
730
+ * @license
731
+ * Copyright 2024 Google LLC
732
+ *
733
+ * Licensed under the Apache License, Version 2.0 (the "License");
734
+ * you may not use this file except in compliance with the License.
735
+ * You may obtain a copy of the License at
736
+ *
737
+ * http://www.apache.org/licenses/LICENSE-2.0
738
+ *
739
+ * Unless required by applicable law or agreed to in writing, software
740
+ * distributed under the License is distributed on an "AS IS" BASIS,
741
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
742
+ * See the License for the specific language governing permissions and
743
+ * limitations under the License.
744
+ */
745
+ /**
746
+ *
747
+ * @param dcInstance Data Connect instance
748
+ * @param mutationName name of mutation
749
+ * @param variables variables to send with mutation
750
+ * @returns `MutationRef`
751
+ */
752
+ function mutationRef(dcInstance, mutationName, variables) {
753
+ dcInstance.setInitialized();
754
+ const ref = {
755
+ dataConnect: dcInstance,
756
+ name: mutationName,
757
+ refType: MUTATION_STR,
758
+ variables: variables
759
+ };
760
+ return ref;
761
+ }
762
+ /**
763
+ * @internal
764
+ */
765
+ class MutationManager {
766
+ constructor(_transport) {
767
+ this._transport = _transport;
768
+ this._inflight = [];
769
+ }
770
+ executeMutation(mutationRef) {
771
+ const result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
772
+ const withRefPromise = result.then(res => {
773
+ const obj = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
774
+ return obj;
775
+ });
776
+ this._inflight.push(result);
777
+ const removePromise = () => (this._inflight = this._inflight.filter(promise => promise !== result));
778
+ result.then(removePromise, removePromise);
779
+ return withRefPromise;
780
+ }
781
+ }
782
+ /**
783
+ * Execute Mutation
784
+ * @param mutationRef mutation to execute
785
+ * @returns `MutationRef`
786
+ */
787
+ function executeMutation(mutationRef) {
788
+ return mutationRef.dataConnect._mutationManager.executeMutation(mutationRef);
789
789
  }
790
790
 
791
- /**
792
- * @license
793
- * Copyright 2024 Google LLC
794
- *
795
- * Licensed under the Apache License, Version 2.0 (the "License");
796
- * you may not use this file except in compliance with the License.
797
- * You may obtain a copy of the License at
798
- *
799
- * http://www.apache.org/licenses/LICENSE-2.0
800
- *
801
- * Unless required by applicable law or agreed to in writing, software
802
- * distributed under the License is distributed on an "AS IS" BASIS,
803
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
804
- * See the License for the specific language governing permissions and
805
- * limitations under the License.
806
- */
807
- const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
808
- /**
809
- *
810
- * @param fullHost
811
- * @returns TransportOptions
812
- * @internal
813
- */
814
- function parseOptions(fullHost) {
815
- const [protocol, hostName] = fullHost.split('://');
816
- const isSecure = protocol === 'https';
817
- const [host, portAsString] = hostName.split(':');
818
- const port = Number(portAsString);
819
- return { host, port, sslEnabled: isSecure };
820
- }
821
- /**
822
- * Class representing Firebase Data Connect
823
- */
824
- class DataConnect {
825
- // @internal
826
- constructor(app,
827
- // TODO(mtewani): Replace with _dataConnectOptions in the future
828
- dataConnectOptions, _authProvider, _appCheckProvider) {
829
- this.app = app;
830
- this.dataConnectOptions = dataConnectOptions;
831
- this._authProvider = _authProvider;
832
- this._appCheckProvider = _appCheckProvider;
833
- this.isEmulator = false;
834
- this._initialized = false;
835
- this._isUsingGeneratedSdk = false;
836
- if (typeof process !== 'undefined' && process.env) {
837
- const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
838
- if (host) {
839
- logDebug('Found custom host. Using emulator');
840
- this.isEmulator = true;
841
- this._transportOptions = parseOptions(host);
842
- }
843
- }
844
- }
845
- // @internal
846
- _useGeneratedSdk() {
847
- if (!this._isUsingGeneratedSdk) {
848
- this._isUsingGeneratedSdk = true;
849
- }
850
- }
851
- _delete() {
852
- app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
853
- return Promise.resolve();
854
- }
855
- // @internal
856
- getSettings() {
857
- const copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
858
- delete copy.projectId;
859
- return copy;
860
- }
861
- // @internal
862
- setInitialized() {
863
- if (this._initialized) {
864
- return;
865
- }
866
- if (this._transportClass === undefined) {
867
- logDebug('transportClass not provided. Defaulting to RESTTransport.');
868
- this._transportClass = RESTTransport;
869
- }
870
- if (this._authProvider) {
871
- this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
872
- }
873
- if (this._appCheckProvider) {
874
- this._appCheckTokenProvider = new AppCheckTokenProvider(this.app.name, this._appCheckProvider);
875
- }
876
- this._initialized = true;
877
- this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this.app.options.appId, this._authTokenProvider, this._appCheckTokenProvider, undefined, this._isUsingGeneratedSdk);
878
- if (this._transportOptions) {
879
- this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled);
880
- }
881
- this._queryManager = new QueryManager(this._transport);
882
- this._mutationManager = new MutationManager(this._transport);
883
- }
884
- // @internal
885
- enableEmulator(transportOptions) {
886
- if (this._initialized) {
887
- logError('enableEmulator called after initialization');
888
- throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
889
- }
890
- this._transportOptions = transportOptions;
891
- this.isEmulator = true;
892
- }
893
- }
894
- /**
895
- * Connect to the DataConnect Emulator
896
- * @param dc Data Connect instance
897
- * @param host host of emulator server
898
- * @param port port of emulator server
899
- * @param sslEnabled use https
900
- */
901
- function connectDataConnectEmulator(dc, host, port, sslEnabled = false) {
902
- dc.enableEmulator({ host, port, sslEnabled });
903
- }
904
- function getDataConnect(appOrOptions, optionalOptions) {
905
- let app$1;
906
- let dcOptions;
907
- if ('location' in appOrOptions) {
908
- dcOptions = appOrOptions;
909
- app$1 = app.getApp();
910
- }
911
- else {
912
- dcOptions = optionalOptions;
913
- app$1 = appOrOptions;
914
- }
915
- if (!app$1 || Object.keys(app$1).length === 0) {
916
- app$1 = app.getApp();
917
- }
918
- const provider = app._getProvider(app$1, 'data-connect');
919
- const identifier = JSON.stringify(dcOptions);
920
- if (provider.isInitialized(identifier)) {
921
- const dcInstance = provider.getImmediate({ identifier });
922
- const options = provider.getOptions(identifier);
923
- const optionsValid = Object.keys(options).length > 0;
924
- if (optionsValid) {
925
- logDebug('Re-using cached instance');
926
- return dcInstance;
927
- }
928
- }
929
- validateDCOptions(dcOptions);
930
- logDebug('Creating new DataConnect instance');
931
- // Initialize with options.
932
- return provider.initialize({
933
- instanceIdentifier: identifier,
934
- options: dcOptions
935
- });
936
- }
937
- /**
938
- *
939
- * @param dcOptions
940
- * @returns {void}
941
- * @internal
942
- */
943
- function validateDCOptions(dcOptions) {
944
- const fields = ['connector', 'location', 'service'];
945
- if (!dcOptions) {
946
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
947
- }
948
- fields.forEach(field => {
949
- if (dcOptions[field] === null || dcOptions[field] === undefined) {
950
- throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`);
951
- }
952
- });
953
- return true;
954
- }
955
- /**
956
- * Delete DataConnect instance
957
- * @param dataConnect DataConnect instance
958
- * @returns
959
- */
960
- function terminate(dataConnect) {
961
- return dataConnect._delete();
962
- // TODO(mtewani): Stop pending tasks
791
+ /**
792
+ * @license
793
+ * Copyright 2024 Google LLC
794
+ *
795
+ * Licensed under the Apache License, Version 2.0 (the "License");
796
+ * you may not use this file except in compliance with the License.
797
+ * You may obtain a copy of the License at
798
+ *
799
+ * http://www.apache.org/licenses/LICENSE-2.0
800
+ *
801
+ * Unless required by applicable law or agreed to in writing, software
802
+ * distributed under the License is distributed on an "AS IS" BASIS,
803
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
804
+ * See the License for the specific language governing permissions and
805
+ * limitations under the License.
806
+ */
807
+ const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
808
+ /**
809
+ *
810
+ * @param fullHost
811
+ * @returns TransportOptions
812
+ * @internal
813
+ */
814
+ function parseOptions(fullHost) {
815
+ const [protocol, hostName] = fullHost.split('://');
816
+ const isSecure = protocol === 'https';
817
+ const [host, portAsString] = hostName.split(':');
818
+ const port = Number(portAsString);
819
+ return { host, port, sslEnabled: isSecure };
820
+ }
821
+ /**
822
+ * Class representing Firebase Data Connect
823
+ */
824
+ class DataConnect {
825
+ // @internal
826
+ constructor(app,
827
+ // TODO(mtewani): Replace with _dataConnectOptions in the future
828
+ dataConnectOptions, _authProvider, _appCheckProvider) {
829
+ this.app = app;
830
+ this.dataConnectOptions = dataConnectOptions;
831
+ this._authProvider = _authProvider;
832
+ this._appCheckProvider = _appCheckProvider;
833
+ this.isEmulator = false;
834
+ this._initialized = false;
835
+ this._isUsingGeneratedSdk = false;
836
+ if (typeof process !== 'undefined' && process.env) {
837
+ const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
838
+ if (host) {
839
+ logDebug('Found custom host. Using emulator');
840
+ this.isEmulator = true;
841
+ this._transportOptions = parseOptions(host);
842
+ }
843
+ }
844
+ }
845
+ // @internal
846
+ _useGeneratedSdk() {
847
+ if (!this._isUsingGeneratedSdk) {
848
+ this._isUsingGeneratedSdk = true;
849
+ }
850
+ }
851
+ _delete() {
852
+ app._removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
853
+ return Promise.resolve();
854
+ }
855
+ // @internal
856
+ getSettings() {
857
+ const copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
858
+ delete copy.projectId;
859
+ return copy;
860
+ }
861
+ // @internal
862
+ setInitialized() {
863
+ if (this._initialized) {
864
+ return;
865
+ }
866
+ if (this._transportClass === undefined) {
867
+ logDebug('transportClass not provided. Defaulting to RESTTransport.');
868
+ this._transportClass = RESTTransport;
869
+ }
870
+ if (this._authProvider) {
871
+ this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
872
+ }
873
+ if (this._appCheckProvider) {
874
+ this._appCheckTokenProvider = new AppCheckTokenProvider(this.app.name, this._appCheckProvider);
875
+ }
876
+ this._initialized = true;
877
+ this._transport = new this._transportClass(this.dataConnectOptions, this.app.options.apiKey, this.app.options.appId, this._authTokenProvider, this._appCheckTokenProvider, undefined, this._isUsingGeneratedSdk);
878
+ if (this._transportOptions) {
879
+ this._transport.useEmulator(this._transportOptions.host, this._transportOptions.port, this._transportOptions.sslEnabled);
880
+ }
881
+ this._queryManager = new QueryManager(this._transport);
882
+ this._mutationManager = new MutationManager(this._transport);
883
+ }
884
+ // @internal
885
+ enableEmulator(transportOptions) {
886
+ if (this._initialized) {
887
+ logError('enableEmulator called after initialization');
888
+ throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
889
+ }
890
+ this._transportOptions = transportOptions;
891
+ this.isEmulator = true;
892
+ }
893
+ }
894
+ /**
895
+ * Connect to the DataConnect Emulator
896
+ * @param dc Data Connect instance
897
+ * @param host host of emulator server
898
+ * @param port port of emulator server
899
+ * @param sslEnabled use https
900
+ */
901
+ function connectDataConnectEmulator(dc, host, port, sslEnabled = false) {
902
+ dc.enableEmulator({ host, port, sslEnabled });
903
+ }
904
+ function getDataConnect(appOrOptions, optionalOptions) {
905
+ let app$1;
906
+ let dcOptions;
907
+ if ('location' in appOrOptions) {
908
+ dcOptions = appOrOptions;
909
+ app$1 = app.getApp();
910
+ }
911
+ else {
912
+ dcOptions = optionalOptions;
913
+ app$1 = appOrOptions;
914
+ }
915
+ if (!app$1 || Object.keys(app$1).length === 0) {
916
+ app$1 = app.getApp();
917
+ }
918
+ const provider = app._getProvider(app$1, 'data-connect');
919
+ const identifier = JSON.stringify(dcOptions);
920
+ if (provider.isInitialized(identifier)) {
921
+ const dcInstance = provider.getImmediate({ identifier });
922
+ const options = provider.getOptions(identifier);
923
+ const optionsValid = Object.keys(options).length > 0;
924
+ if (optionsValid) {
925
+ logDebug('Re-using cached instance');
926
+ return dcInstance;
927
+ }
928
+ }
929
+ validateDCOptions(dcOptions);
930
+ logDebug('Creating new DataConnect instance');
931
+ // Initialize with options.
932
+ return provider.initialize({
933
+ instanceIdentifier: identifier,
934
+ options: dcOptions
935
+ });
936
+ }
937
+ /**
938
+ *
939
+ * @param dcOptions
940
+ * @returns {void}
941
+ * @internal
942
+ */
943
+ function validateDCOptions(dcOptions) {
944
+ const fields = ['connector', 'location', 'service'];
945
+ if (!dcOptions) {
946
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
947
+ }
948
+ fields.forEach(field => {
949
+ if (dcOptions[field] === null || dcOptions[field] === undefined) {
950
+ throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`);
951
+ }
952
+ });
953
+ return true;
954
+ }
955
+ /**
956
+ * Delete DataConnect instance
957
+ * @param dataConnect DataConnect instance
958
+ * @returns
959
+ */
960
+ function terminate(dataConnect) {
961
+ return dataConnect._delete();
962
+ // TODO(mtewani): Stop pending tasks
963
963
  }
964
964
 
965
- /**
966
- * @license
967
- * Copyright 2024 Google LLC
968
- *
969
- * Licensed under the Apache License, Version 2.0 (the "License");
970
- * you may not use this file except in compliance with the License.
971
- * You may obtain a copy of the License at
972
- *
973
- * http://www.apache.org/licenses/LICENSE-2.0
974
- *
975
- * Unless required by applicable law or agreed to in writing, software
976
- * distributed under the License is distributed on an "AS IS" BASIS,
977
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
978
- * See the License for the specific language governing permissions and
979
- * limitations under the License.
980
- */
981
- function registerDataConnect(variant) {
982
- setSDKVersion(app.SDK_VERSION);
983
- app._registerComponent(new component.Component('data-connect', (container, { instanceIdentifier: settings, options }) => {
984
- const app = container.getProvider('app').getImmediate();
985
- const authProvider = container.getProvider('auth-internal');
986
- const appCheckProvider = container.getProvider('app-check-internal');
987
- let newOpts = options;
988
- if (settings) {
989
- newOpts = JSON.parse(settings);
990
- }
991
- if (!app.options.projectId) {
992
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?');
993
- }
994
- return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
995
- }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
996
- app.registerVersion(name, version, variant);
997
- // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
998
- app.registerVersion(name, version, 'cjs2017');
965
+ /**
966
+ * @license
967
+ * Copyright 2024 Google LLC
968
+ *
969
+ * Licensed under the Apache License, Version 2.0 (the "License");
970
+ * you may not use this file except in compliance with the License.
971
+ * You may obtain a copy of the License at
972
+ *
973
+ * http://www.apache.org/licenses/LICENSE-2.0
974
+ *
975
+ * Unless required by applicable law or agreed to in writing, software
976
+ * distributed under the License is distributed on an "AS IS" BASIS,
977
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
978
+ * See the License for the specific language governing permissions and
979
+ * limitations under the License.
980
+ */
981
+ function registerDataConnect(variant) {
982
+ setSDKVersion(app.SDK_VERSION);
983
+ app._registerComponent(new component.Component('data-connect', (container, { instanceIdentifier: settings, options }) => {
984
+ const app = container.getProvider('app').getImmediate();
985
+ const authProvider = container.getProvider('auth-internal');
986
+ const appCheckProvider = container.getProvider('app-check-internal');
987
+ let newOpts = options;
988
+ if (settings) {
989
+ newOpts = JSON.parse(settings);
990
+ }
991
+ if (!app.options.projectId) {
992
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?');
993
+ }
994
+ return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
995
+ }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
996
+ app.registerVersion(name, version, variant);
997
+ // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
998
+ app.registerVersion(name, version, 'cjs2017');
999
999
  }
1000
1000
 
1001
- /**
1002
- * @license
1003
- * Copyright 2024 Google LLC
1004
- *
1005
- * Licensed under the Apache License, Version 2.0 (the "License");
1006
- * you may not use this file except in compliance with the License.
1007
- * You may obtain a copy of the License at
1008
- *
1009
- * http://www.apache.org/licenses/LICENSE-2.0
1010
- *
1011
- * Unless required by applicable law or agreed to in writing, software
1012
- * distributed under the License is distributed on an "AS IS" BASIS,
1013
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1014
- * See the License for the specific language governing permissions and
1015
- * limitations under the License.
1016
- */
1017
- /**
1018
- * Execute Query
1019
- * @param queryRef query to execute.
1020
- * @returns `QueryPromise`
1021
- */
1022
- function executeQuery(queryRef) {
1023
- return queryRef.dataConnect._queryManager.executeQuery(queryRef);
1024
- }
1025
- /**
1026
- * Execute Query
1027
- * @param dcInstance Data Connect instance to use.
1028
- * @param queryName Query to execute
1029
- * @param variables Variables to execute with
1030
- * @param initialCache initial cache to use for client hydration
1031
- * @returns `QueryRef`
1032
- */
1033
- function queryRef(dcInstance, queryName, variables, initialCache) {
1034
- dcInstance.setInitialized();
1035
- dcInstance._queryManager.track(queryName, variables, initialCache);
1036
- return {
1037
- dataConnect: dcInstance,
1038
- refType: QUERY_STR,
1039
- name: queryName,
1040
- variables: variables
1041
- };
1042
- }
1043
- /**
1044
- * Converts serialized ref to query ref
1045
- * @param serializedRef ref to convert to `QueryRef`
1046
- * @returns `QueryRef`
1047
- */
1048
- function toQueryRef(serializedRef) {
1049
- const { refInfo: { name, variables, connectorConfig } } = serializedRef;
1050
- return queryRef(getDataConnect(connectorConfig), name, variables);
1001
+ /**
1002
+ * @license
1003
+ * Copyright 2024 Google LLC
1004
+ *
1005
+ * Licensed under the Apache License, Version 2.0 (the "License");
1006
+ * you may not use this file except in compliance with the License.
1007
+ * You may obtain a copy of the License at
1008
+ *
1009
+ * http://www.apache.org/licenses/LICENSE-2.0
1010
+ *
1011
+ * Unless required by applicable law or agreed to in writing, software
1012
+ * distributed under the License is distributed on an "AS IS" BASIS,
1013
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1014
+ * See the License for the specific language governing permissions and
1015
+ * limitations under the License.
1016
+ */
1017
+ /**
1018
+ * Execute Query
1019
+ * @param queryRef query to execute.
1020
+ * @returns `QueryPromise`
1021
+ */
1022
+ function executeQuery(queryRef) {
1023
+ return queryRef.dataConnect._queryManager.executeQuery(queryRef);
1024
+ }
1025
+ /**
1026
+ * Execute Query
1027
+ * @param dcInstance Data Connect instance to use.
1028
+ * @param queryName Query to execute
1029
+ * @param variables Variables to execute with
1030
+ * @param initialCache initial cache to use for client hydration
1031
+ * @returns `QueryRef`
1032
+ */
1033
+ function queryRef(dcInstance, queryName, variables, initialCache) {
1034
+ dcInstance.setInitialized();
1035
+ dcInstance._queryManager.track(queryName, variables, initialCache);
1036
+ return {
1037
+ dataConnect: dcInstance,
1038
+ refType: QUERY_STR,
1039
+ name: queryName,
1040
+ variables: variables
1041
+ };
1042
+ }
1043
+ /**
1044
+ * Converts serialized ref to query ref
1045
+ * @param serializedRef ref to convert to `QueryRef`
1046
+ * @returns `QueryRef`
1047
+ */
1048
+ function toQueryRef(serializedRef) {
1049
+ const { refInfo: { name, variables, connectorConfig } } = serializedRef;
1050
+ return queryRef(getDataConnect(connectorConfig), name, variables);
1051
1051
  }
1052
1052
 
1053
- /**
1054
- * @license
1055
- * Copyright 2024 Google LLC
1056
- *
1057
- * Licensed under the Apache License, Version 2.0 (the "License");
1058
- * you may not use this file except in compliance with the License.
1059
- * You may obtain a copy of the License at
1060
- *
1061
- * http://www.apache.org/licenses/LICENSE-2.0
1062
- *
1063
- * Unless required by applicable law or agreed to in writing, software
1064
- * distributed under the License is distributed on an "AS IS" BASIS,
1065
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1066
- * See the License for the specific language governing permissions and
1067
- * limitations under the License.
1068
- */
1069
- /**
1070
- * The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable,
1071
- * and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in.
1072
- * @param connectorConfig
1073
- * @param dcOrVars
1074
- * @param vars
1075
- * @param validateVars
1076
- * @returns {DataConnect} and {Variables} instance
1077
- * @internal
1078
- */
1079
- function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1080
- let dcInstance;
1081
- let realVars;
1082
- if (dcOrVars && 'enableEmulator' in dcOrVars) {
1083
- dcInstance = dcOrVars;
1084
- realVars = vars;
1085
- }
1086
- else {
1087
- dcInstance = getDataConnect(connectorConfig);
1088
- realVars = dcOrVars;
1089
- }
1090
- if (!dcInstance || (!realVars && validateVars)) {
1091
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.');
1092
- }
1093
- return { dc: dcInstance, vars: realVars };
1053
+ /**
1054
+ * @license
1055
+ * Copyright 2024 Google LLC
1056
+ *
1057
+ * Licensed under the Apache License, Version 2.0 (the "License");
1058
+ * you may not use this file except in compliance with the License.
1059
+ * You may obtain a copy of the License at
1060
+ *
1061
+ * http://www.apache.org/licenses/LICENSE-2.0
1062
+ *
1063
+ * Unless required by applicable law or agreed to in writing, software
1064
+ * distributed under the License is distributed on an "AS IS" BASIS,
1065
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1066
+ * See the License for the specific language governing permissions and
1067
+ * limitations under the License.
1068
+ */
1069
+ /**
1070
+ * The generated SDK will allow the user to pass in either the variable or the data connect instance with the variable,
1071
+ * and this function validates the variables and returns back the DataConnect instance and variables based on the arguments passed in.
1072
+ * @param connectorConfig
1073
+ * @param dcOrVars
1074
+ * @param vars
1075
+ * @param validateVars
1076
+ * @returns {DataConnect} and {Variables} instance
1077
+ * @internal
1078
+ */
1079
+ function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1080
+ let dcInstance;
1081
+ let realVars;
1082
+ if (dcOrVars && 'enableEmulator' in dcOrVars) {
1083
+ dcInstance = dcOrVars;
1084
+ realVars = vars;
1085
+ }
1086
+ else {
1087
+ dcInstance = getDataConnect(connectorConfig);
1088
+ realVars = dcOrVars;
1089
+ }
1090
+ if (!dcInstance || (!realVars && validateVars)) {
1091
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Variables required.');
1092
+ }
1093
+ return { dc: dcInstance, vars: realVars };
1094
1094
  }
1095
1095
 
1096
- /**
1097
- * @license
1098
- * Copyright 2024 Google LLC
1099
- *
1100
- * Licensed under the Apache License, Version 2.0 (the "License");
1101
- * you may not use this file except in compliance with the License.
1102
- * You may obtain a copy of the License at
1103
- *
1104
- * http://www.apache.org/licenses/LICENSE-2.0
1105
- *
1106
- * Unless required by applicable law or agreed to in writing, software
1107
- * distributed under the License is distributed on an "AS IS" BASIS,
1108
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1109
- * See the License for the specific language governing permissions and
1110
- * limitations under the License.
1111
- */
1112
- /**
1113
- * Subscribe to a `QueryRef`
1114
- * @param queryRefOrSerializedResult query ref or serialized result.
1115
- * @param observerOrOnNext observer object or next function.
1116
- * @param onError Callback to call when error gets thrown.
1117
- * @param onComplete Called when subscription completes.
1118
- * @returns `SubscriptionOptions`
1119
- */
1120
- function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
1121
- let ref;
1122
- let initialCache;
1123
- if ('refInfo' in queryRefOrSerializedResult) {
1124
- const serializedRef = queryRefOrSerializedResult;
1125
- const { data, source, fetchTime } = serializedRef;
1126
- initialCache = {
1127
- data,
1128
- source,
1129
- fetchTime
1130
- };
1131
- ref = toQueryRef(serializedRef);
1132
- }
1133
- else {
1134
- ref = queryRefOrSerializedResult;
1135
- }
1136
- let onResult = undefined;
1137
- if (typeof observerOrOnNext === 'function') {
1138
- onResult = observerOrOnNext;
1139
- }
1140
- else {
1141
- onResult = observerOrOnNext.onNext;
1142
- onError = observerOrOnNext.onErr;
1143
- observerOrOnNext.onComplete;
1144
- }
1145
- if (!onResult) {
1146
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Must provide onNext');
1147
- }
1148
- return ref.dataConnect._queryManager.addSubscription(ref, onResult, onError, initialCache);
1096
+ /**
1097
+ * @license
1098
+ * Copyright 2024 Google LLC
1099
+ *
1100
+ * Licensed under the Apache License, Version 2.0 (the "License");
1101
+ * you may not use this file except in compliance with the License.
1102
+ * You may obtain a copy of the License at
1103
+ *
1104
+ * http://www.apache.org/licenses/LICENSE-2.0
1105
+ *
1106
+ * Unless required by applicable law or agreed to in writing, software
1107
+ * distributed under the License is distributed on an "AS IS" BASIS,
1108
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1109
+ * See the License for the specific language governing permissions and
1110
+ * limitations under the License.
1111
+ */
1112
+ /**
1113
+ * Subscribe to a `QueryRef`
1114
+ * @param queryRefOrSerializedResult query ref or serialized result.
1115
+ * @param observerOrOnNext observer object or next function.
1116
+ * @param onError Callback to call when error gets thrown.
1117
+ * @param onComplete Called when subscription completes.
1118
+ * @returns `SubscriptionOptions`
1119
+ */
1120
+ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
1121
+ let ref;
1122
+ let initialCache;
1123
+ if ('refInfo' in queryRefOrSerializedResult) {
1124
+ const serializedRef = queryRefOrSerializedResult;
1125
+ const { data, source, fetchTime } = serializedRef;
1126
+ initialCache = {
1127
+ data,
1128
+ source,
1129
+ fetchTime
1130
+ };
1131
+ ref = toQueryRef(serializedRef);
1132
+ }
1133
+ else {
1134
+ ref = queryRefOrSerializedResult;
1135
+ }
1136
+ let onResult = undefined;
1137
+ if (typeof observerOrOnNext === 'function') {
1138
+ onResult = observerOrOnNext;
1139
+ }
1140
+ else {
1141
+ onResult = observerOrOnNext.onNext;
1142
+ onError = observerOrOnNext.onErr;
1143
+ observerOrOnNext.onComplete;
1144
+ }
1145
+ if (!onResult) {
1146
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Must provide onNext');
1147
+ }
1148
+ return ref.dataConnect._queryManager.addSubscription(ref, onResult, onError, initialCache);
1149
1149
  }
1150
1150
 
1151
- /**
1152
- * Firebase Data Connect
1153
- *
1154
- * @packageDocumentation
1155
- */
1151
+ /**
1152
+ * Firebase Data Connect
1153
+ *
1154
+ * @packageDocumentation
1155
+ */
1156
1156
  registerDataConnect();
1157
1157
 
1158
1158
  exports.DataConnect = DataConnect;