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